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

'use strict';

import 'vs/css!./media/workbench';
9

J
Johannes Rieken 已提交
10 11
import { TPromise, ValueCallback } from 'vs/base/common/winjs.base';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
E
Erich Gamma 已提交
12 13
import strings = require('vs/base/common/strings');
import DOM = require('vs/base/browser/dom');
J
Johannes Rieken 已提交
14 15
import { Box, Builder, $ } from 'vs/base/browser/builder';
import { Delayer } from 'vs/base/common/async';
E
Erich Gamma 已提交
16 17 18
import assert = require('vs/base/common/assert');
import timer = require('vs/base/common/timer');
import errors = require('vs/base/common/errors');
J
Johannes Rieken 已提交
19 20 21 22
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { Registry } from 'vs/platform/platform';
import { isWindows, isLinux } from 'vs/base/common/platform';
import { IOptions } from 'vs/workbench/common/options';
23
import { Position as EditorPosition } from 'vs/platform/editor/common/editor';
J
Johannes Rieken 已提交
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
import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions';
import { BaseEditor } from 'vs/workbench/browser/parts/editor/baseEditor';
import { IEditorRegistry, Extensions as EditorExtensions, TextEditorOptions, EditorInput, EditorOptions } from 'vs/workbench/common/editor';
import { HistoryService } from 'vs/workbench/services/history/browser/history';
import { ActivitybarPart } from 'vs/workbench/browser/parts/activitybar/activitybarPart';
import { EditorPart } from 'vs/workbench/browser/parts/editor/editorPart';
import { SidebarPart } from 'vs/workbench/browser/parts/sidebar/sidebarPart';
import { PanelPart } from 'vs/workbench/browser/parts/panel/panelPart';
import { StatusbarPart } from 'vs/workbench/browser/parts/statusbar/statusbarPart';
import { WorkbenchLayout, LayoutOptions } from 'vs/workbench/browser/layout';
import { IActionBarRegistry, Extensions as ActionBarExtensions } from 'vs/workbench/browser/actionBarRegistry';
import { ViewletRegistry, Extensions as ViewletExtensions } from 'vs/workbench/browser/viewlet';
import { PanelRegistry, Extensions as PanelExtensions } from 'vs/workbench/browser/panel';
import { QuickOpenController } from 'vs/workbench/browser/parts/quickopen/quickOpenController';
import { DiffEditorInput, toDiffLabel } from 'vs/workbench/common/editor/diffEditorInput';
import { getServices } from 'vs/platform/instantiation/common/extensions';
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { WorkbenchEditorService } from 'vs/workbench/services/editor/browser/editorService';
import { Position, Parts, IPartService } from 'vs/workbench/services/part/common/partService';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { ContextMenuService } from 'vs/workbench/services/contextview/electron-browser/contextmenuService';
import { WorkbenchKeybindingService } from 'vs/workbench/services/keybinding/electron-browser/keybindingService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IConfigurationEditingService } from 'vs/workbench/services/configuration/common/configurationEditing';
import { ConfigurationEditingService } from 'vs/workbench/services/configuration/node/configurationEditingService';
import { ContextKeyService } from 'vs/platform/contextkey/browser/contextKeyService';
import { IWorkspace } from 'vs/platform/workspace/common/workspace';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { ContextKeyExpr, RawContextKey, IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IActivityService } from 'vs/workbench/services/activity/common/activityService';
import { IViewletService } from 'vs/workbench/services/viewlet/common/viewletService';
import { FileService } from 'vs/workbench/services/files/electron-browser/fileService';
import { IFileService } from 'vs/platform/files/common/files';
import { IConfigurationResolverService } from 'vs/workbench/services/configurationResolver/common/configurationResolver';
import { ConfigurationResolverService } from 'vs/workbench/services/configurationResolver/node/configurationResolverService';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { WorkbenchMessageService } from 'vs/workbench/services/message/browser/messageService';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IQuickOpenService } from 'vs/workbench/services/quickopen/common/quickOpenService';
import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService';
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 { TextFileService } from 'vs/workbench/services/textfile/electron-browser/textFileService';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
70
import { TextModelResolverService } from 'vs/workbench/services/textmodelResolver/common/textModelResolverService';
71
import { ITextModelResolverService } from 'vs/platform/textmodelResolver/common/resolver';
J
Johannes Rieken 已提交
72 73 74 75 76 77 78 79 80
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
import { IMessageService } from 'vs/platform/message/common/message';
import { IStatusbarService } from 'vs/platform/statusbar/common/statusbar';
import { IMenuService } from 'vs/platform/actions/common/actions';
import { MenuService } from 'vs/platform/actions/common/menuService';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
E
Erich Gamma 已提交
81

A
Alex Dima 已提交
82 83
export const MessagesVisibleContext = new RawContextKey<boolean>('globalMessageVisible', false);
export const EditorsVisibleContext = new RawContextKey<boolean>('editorIsOpen', false);
J
Johannes Rieken 已提交
84
export const NoEditorsVisibleContext: ContextKeyExpr = EditorsVisibleContext.toNegated();
A
Alex Dima 已提交
85

E
Erich Gamma 已提交
86 87 88
interface WorkbenchParams {
	workspace?: IWorkspace;
	options: IOptions;
89
	serviceCollection: ServiceCollection;
E
Erich Gamma 已提交
90 91 92 93
}

export interface IWorkbenchCallbacks {
	onServicesCreated?: () => void;
94
	onWorkbenchStarted?: (customKeybindingsCount: number) => void;
E
Erich Gamma 已提交
95 96
}

97 98 99 100 101 102 103 104 105
const Identifiers = {
	WORKBENCH_CONTAINER: 'workbench.main.container',
	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'
};

E
Erich Gamma 已提交
106
/**
B
Benjamin Pasero 已提交
107
 * The workbench creates and lays out all parts that make up the workbench.
E
Erich Gamma 已提交
108 109 110 111
 */
export class Workbench implements IPartService {

	private static sidebarHiddenSettingKey = 'workbench.sidebar.hidden';
112
	private static sidebarRestoreSettingKey = 'workbench.sidebar.restore';
I
isidor 已提交
113
	private static panelHiddenSettingKey = 'workbench.panel.hidden';
E
Erich Gamma 已提交
114

115
	private static sidebarPositionConfigurationKey = 'workbench.sideBar.location';
116
	private static statusbarVisibleConfigurationKey = 'workbench.statusBar.visible';
117

118
	public _serviceBrand: any;
E
Erich Gamma 已提交
119 120 121 122 123 124 125 126

	private container: HTMLElement;
	private workbenchParams: WorkbenchParams;
	private workbenchContainer: Builder;
	private workbench: Builder;
	private workbenchStarted: boolean;
	private workbenchCreated: boolean;
	private workbenchShutdown: boolean;
127
	private editorService: WorkbenchEditorService;
128
	private contextKeyService: IContextKeyService;
129
	private keybindingService: IKeybindingService;
130
	private configurationEditingService: IConfigurationEditingService;
E
Erich Gamma 已提交
131 132
	private activitybarPart: ActivitybarPart;
	private sidebarPart: SidebarPart;
I
isidor 已提交
133
	private panelPart: PanelPart;
E
Erich Gamma 已提交
134 135 136 137 138 139 140 141 142 143
	private editorPart: EditorPart;
	private statusbarPart: StatusbarPart;
	private quickOpen: QuickOpenController;
	private workbenchLayout: WorkbenchLayout;
	private toDispose: IDisposable[];
	private toShutdown: { shutdown: () => void; }[];
	private callbacks: IWorkbenchCallbacks;
	private creationPromise: TPromise<boolean>;
	private creationPromiseComplete: ValueCallback;
	private sideBarHidden: boolean;
144
	private statusBarHidden: boolean;
E
Erich Gamma 已提交
145
	private sideBarPosition: Position;
I
isidor 已提交
146
	private panelHidden: boolean;
E
Erich Gamma 已提交
147
	private editorBackgroundDelayer: Delayer<void>;
A
Alex Dima 已提交
148 149
	private messagesVisibleContext: IContextKey<boolean>;
	private editorsVisibleContext: IContextKey<boolean>;
150
	private hasFilesToCreateOpenOrDiff: boolean;
E
Erich Gamma 已提交
151

152 153 154 155 156
	constructor(
		container: HTMLElement,
		workspace: IWorkspace,
		options: IOptions,
		serviceCollection: ServiceCollection,
157 158
		@IInstantiationService private instantiationService: IInstantiationService,
		@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
159
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
160 161 162
		@IStorageService private storageService: IStorageService,
		@ILifecycleService private lifecycleService: ILifecycleService,
		@IMessageService private messageService: IMessageService,
163
		@IConfigurationService private configurationService: IConfigurationService,
164
		@ITelemetryService private telemetryService: ITelemetryService,
D
Daniel Imms 已提交
165
		@IEnvironmentService private environmentService: IEnvironmentService
166
	) {
167
		this.container = container;
E
Erich Gamma 已提交
168 169 170

		this.workbenchParams = {
			workspace: workspace,
171
			options,
172
			serviceCollection
E
Erich Gamma 已提交
173 174
		};

D
Daniel Imms 已提交
175
		this.hasFilesToCreateOpenOrDiff = (options.filesToCreate && options.filesToCreate.length > 0) || (options.filesToOpen && options.filesToOpen.length > 0) || (options.filesToDiff && options.filesToDiff.length > 0);
176

E
Erich Gamma 已提交
177 178 179 180
		this.toDispose = [];
		this.toShutdown = [];
		this.editorBackgroundDelayer = new Delayer<void>(50);

181
		this.creationPromise = new TPromise<boolean>(c => {
E
Erich Gamma 已提交
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
			this.creationPromiseComplete = c;
		});
	}

	/**
	 * Starts the workbench and creates the HTML elements on the container. A workbench can only be started
	 * once. Use the shutdown function to free up resources created by the workbench on startup.
	 */
	public startup(callbacks?: IWorkbenchCallbacks): void {
		assert.ok(!this.workbenchStarted, 'Can not start a workbench that was already started');
		assert.ok(!this.workbenchShutdown, 'Can not start a workbench that was shutdown');

		try {
			this.workbenchStarted = true;
			this.callbacks = callbacks;

			// Create Workbench
			this.createWorkbench();

			// Services
			this.initServices();
			if (this.callbacks && this.callbacks.onServicesCreated) {
				this.callbacks.onServicesCreated();
			}

207
			// Contexts
208 209
			this.messagesVisibleContext = MessagesVisibleContext.bindTo(this.contextKeyService);
			this.editorsVisibleContext = EditorsVisibleContext.bindTo(this.contextKeyService);
210

E
Erich Gamma 已提交
211 212 213 214 215 216 217 218 219 220 221 222
			// Register Listeners
			this.registerListeners();

			// Settings
			this.initSettings();

			// Create Workbench and Parts
			this.renderWorkbench();

			// Workbench Layout
			this.createWorkbenchLayout();

I
isidor 已提交
223
			// Load composits and editors in parallel
B
Benjamin Pasero 已提交
224
			const compositeAndEditorPromises: TPromise<any>[] = [];
E
Erich Gamma 已提交
225

B
Benjamin Pasero 已提交
226
			// Load Viewlet
227
			const viewletRegistry = Registry.as<ViewletRegistry>(ViewletExtensions.Viewlets);
228
			let viewletId = viewletRegistry.getDefaultViewletId();
229
			if (this.shouldRestoreSidebar()) {
230
				viewletId = this.storageService.get(SidebarPart.activeViewletSettingsKey, StorageScope.WORKSPACE, viewletId); // help developers and restore last view
231 232 233
			}

			if (!this.sideBarHidden && !!viewletId) {
B
Benjamin Pasero 已提交
234
				const viewletTimerEvent = timer.start(timer.Topic.STARTUP, strings.format('Opening Viewlet: {0}', viewletId));
I
isidor 已提交
235
				compositeAndEditorPromises.push(this.sidebarPart.openViewlet(viewletId, false).then(() => viewletTimerEvent.stop()));
E
Erich Gamma 已提交
236 237
			}

B
Benjamin Pasero 已提交
238
			// Load Panel
239
			const panelRegistry = Registry.as<PanelRegistry>(PanelExtensions.Panels);
240 241
			const panelId = this.storageService.get(PanelPart.activePanelSettingsKey, StorageScope.WORKSPACE, panelRegistry.getDefaultPanelId());
			if (!this.panelHidden && !!panelId) {
I
isidor 已提交
242
				compositeAndEditorPromises.push(this.panelPart.openPanel(panelId, false));
243 244
			}

B
Benjamin Pasero 已提交
245
			// Load Editors
B
Benjamin Pasero 已提交
246
			const editorTimerEvent = timer.start(timer.Topic.STARTUP, strings.format('Restoring Editor(s)'));
247
			compositeAndEditorPromises.push(this.resolveEditorsToOpen().then(inputsWithOptions => {
B
Benjamin Pasero 已提交
248 249
				let editorOpenPromise: TPromise<BaseEditor[]>;
				if (inputsWithOptions.length) {
250
					const editors = inputsWithOptions.map(inputWithOptions => {
B
Benjamin Pasero 已提交
251 252 253
						return {
							input: inputWithOptions.input,
							options: inputWithOptions.options,
254
							position: EditorPosition.ONE
B
Benjamin Pasero 已提交
255
						};
256 257
					});

B
Benjamin Pasero 已提交
258 259
					editorOpenPromise = this.editorPart.openEditors(editors);
				} else {
260
					editorOpenPromise = this.editorPart.restoreEditors();
261
				}
262 263

				return editorOpenPromise.then(() => {
264
					this.onEditorsChanged(); // make sure we show the proper background in the editor area
E
Erich Gamma 已提交
265 266 267 268 269
					editorTimerEvent.stop();
				});
			}));

			// Flag workbench as created once done
270
			const workbenchDone = (error?: Error) => {
E
Erich Gamma 已提交
271 272 273
				this.workbenchCreated = true;
				this.creationPromiseComplete(true);

B
Benjamin Pasero 已提交
274
				if (this.callbacks && this.callbacks.onWorkbenchStarted) {
275
					this.callbacks.onWorkbenchStarted(this.keybindingService.customKeybindingsCount());
B
Benjamin Pasero 已提交
276
				}
277 278 279 280 281 282

				if (error) {
					errors.onUnexpectedError(error);
				}
			};

B
polish  
Benjamin Pasero 已提交
283
			// Join viewlet, panel and editor promises
284
			TPromise.join(compositeAndEditorPromises).then(() => workbenchDone(), error => workbenchDone(error));
E
Erich Gamma 已提交
285 286 287
		} catch (error) {

			// Print out error
288
			console.error(toErrorMessage(error, true));
E
Erich Gamma 已提交
289 290 291 292 293 294

			// Rethrow
			throw error;
		}
	}

B
Benjamin Pasero 已提交
295 296 297
	private resolveEditorsToOpen(): TPromise<{ input: EditorInput, options?: EditorOptions }[]> {

		// Files to open, diff or create
298 299
		if (this.hasFilesToCreateOpenOrDiff) {
			const wbopt = this.workbenchParams.options;
B
Benjamin Pasero 已提交
300 301 302
			const filesToCreate = wbopt.filesToCreate || [];
			const filesToOpen = wbopt.filesToOpen || [];
			const filesToDiff = wbopt.filesToDiff;
B
Benjamin Pasero 已提交
303 304 305

			// Files to diff is exclusive
			if (filesToDiff && filesToDiff.length) {
306
				return TPromise.join<EditorInput>(filesToDiff.map(resourceInput => this.editorService.createInput(resourceInput))).then((inputsToDiff) => {
B
Benjamin Pasero 已提交
307 308 309 310 311 312
					return [{ input: new DiffEditorInput(toDiffLabel(filesToDiff[0].resource, filesToDiff[1].resource, this.contextService), null, inputsToDiff[0], inputsToDiff[1]) }];
				});
			}

			// Otherwise: Open/Create files
			else {
B
Benjamin Pasero 已提交
313 314
				const inputs: EditorInput[] = [];
				const options: EditorOptions[] = [];
B
Benjamin Pasero 已提交
315 316

				// Files to create
317
				inputs.push(...filesToCreate.map(resourceInput => this.untitledEditorService.createOrGet(resourceInput.resource)));
B
Benjamin Pasero 已提交
318 319 320
				options.push(...filesToCreate.map(r => null)); // fill empty options for files to create because we dont have options there

				// Files to open
D
Daniel Imms 已提交
321
				return TPromise.join<EditorInput>(filesToOpen.map(resourceInput => this.editorService.createInput(resourceInput))).then((inputsToOpen) => {
B
Benjamin Pasero 已提交
322
					inputs.push(...inputsToOpen);
D
Daniel Imms 已提交
323
					options.push(...filesToOpen.map(resourceInput => TextEditorOptions.from(resourceInput)));
B
Benjamin Pasero 已提交
324 325 326 327 328 329 330

					return inputs.map((input, index) => { return { input, options: options[index] }; });
				});
			}
		}

		// Empty workbench
331 332
		else if (!this.workbenchParams.workspace && this.telemetryService.getExperiments().openUntitledFile) {
			// some first time users will not have an untiled file; returning users will always have one
B
Benjamin Pasero 已提交
333 334 335 336 337 338
			return TPromise.as([{ input: this.untitledEditorService.createOrGet() }]);
		}

		return TPromise.as([]);
	}

E
Erich Gamma 已提交
339
	private initServices(): void {
340 341
		const {serviceCollection} = this.workbenchParams;

342
		this.toDispose.push(this.lifecycleService.onShutdown(this.shutdownComponents, this));
E
Erich Gamma 已提交
343 344

		// Services we contribute
345
		serviceCollection.set(IPartService, this);
E
Erich Gamma 已提交
346

347 348 349 350 351 352 353
		// Status bar
		this.statusbarPart = this.instantiationService.createInstance(StatusbarPart, Identifiers.STATUSBAR_PART);
		this.toDispose.push(this.statusbarPart);
		this.toShutdown.push(this.statusbarPart);
		serviceCollection.set(IStatusbarService, this.statusbarPart);

		// Keybindings
A
Alex Dima 已提交
354
		this.contextKeyService = this.instantiationService.createInstance(ContextKeyService);
355
		serviceCollection.set(IContextKeyService, this.contextKeyService);
356

A
Alex Dima 已提交
357
		this.keybindingService = this.instantiationService.createInstance(WorkbenchKeybindingService, <any>window);
358
		serviceCollection.set(IKeybindingService, this.keybindingService);
A
Alex Dima 已提交
359

360
		// Context Menu
361
		serviceCollection.set(IContextMenuService, this.instantiationService.createInstance(ContextMenuService));
362

363 364
		// Menus/Actions
		serviceCollection.set(IMenuService, new SyncDescriptor(MenuService));
365

E
Erich Gamma 已提交
366
		// Viewlet service (sidebar part)
367
		this.sidebarPart = this.instantiationService.createInstance(SidebarPart, Identifiers.SIDEBAR_PART);
E
Erich Gamma 已提交
368 369
		this.toDispose.push(this.sidebarPart);
		this.toShutdown.push(this.sidebarPart);
370
		serviceCollection.set(IViewletService, this.sidebarPart);
E
Erich Gamma 已提交
371

I
isidor 已提交
372
		// Panel service (panel part)
373
		this.panelPart = this.instantiationService.createInstance(PanelPart, Identifiers.PANEL_PART);
I
isidor 已提交
374 375
		this.toDispose.push(this.panelPart);
		this.toShutdown.push(this.panelPart);
376
		serviceCollection.set(IPanelService, this.panelPart);
I
isidor 已提交
377

E
Erich Gamma 已提交
378
		// Activity service (activitybar part)
379
		this.activitybarPart = this.instantiationService.createInstance(ActivitybarPart, Identifiers.ACTIVITYBAR_PART);
E
Erich Gamma 已提交
380 381
		this.toDispose.push(this.activitybarPart);
		this.toShutdown.push(this.activitybarPart);
382
		serviceCollection.set(IActivityService, this.activitybarPart);
E
Erich Gamma 已提交
383 384

		// Editor service (editor part)
385
		this.editorPart = this.instantiationService.createInstance(EditorPart, Identifiers.EDITOR_PART, !this.hasFilesToCreateOpenOrDiff);
E
Erich Gamma 已提交
386 387
		this.toDispose.push(this.editorPart);
		this.toShutdown.push(this.editorPart);
388
		this.editorService = this.instantiationService.createInstance(WorkbenchEditorService, this.editorPart);
389
		serviceCollection.set(IWorkbenchEditorService, this.editorService);
390
		serviceCollection.set(IEditorGroupService, this.editorPart);
E
Erich Gamma 已提交
391

392
		// File Service
393 394 395
		const fileService = this.instantiationService.createInstance(FileService);
		serviceCollection.set(IFileService, fileService);

396
		// History
397
		serviceCollection.set(IHistoryService, this.instantiationService.createInstance(HistoryService));
398

399 400 401
		// Text File Service
		serviceCollection.set(ITextFileService, this.instantiationService.createInstance(TextFileService));

B
Benjamin Pasero 已提交
402 403 404
		// Text Model Resolver Service
		serviceCollection.set(ITextModelResolverService, this.instantiationService.createInstance(TextModelResolverService));

405
		// Configuration Editing
406 407
		this.configurationEditingService = this.instantiationService.createInstance(ConfigurationEditingService);
		serviceCollection.set(IConfigurationEditingService, this.configurationEditingService);
408

409
		// Configuration Resolver
410 411
		const workspace = this.contextService.getWorkspace();
		const configurationResolverService = this.instantiationService.createInstance(ConfigurationResolverService, workspace ? workspace.resource : null, process.env);
412 413
		serviceCollection.set(IConfigurationResolverService, configurationResolverService);

E
Erich Gamma 已提交
414
		// Quick open service (quick open controller)
415
		this.quickOpen = this.instantiationService.createInstance(QuickOpenController);
E
Erich Gamma 已提交
416 417
		this.toDispose.push(this.quickOpen);
		this.toShutdown.push(this.quickOpen);
418
		serviceCollection.set(IQuickOpenService, this.quickOpen);
E
Erich Gamma 已提交
419

B
polish  
Benjamin Pasero 已提交
420
		// Contributed services
B
Benjamin Pasero 已提交
421
		const contributedServices = getServices();
E
Erich Gamma 已提交
422
		for (let contributedService of contributedServices) {
423
			serviceCollection.set(contributedService.id, contributedService.descriptor);
E
Erich Gamma 已提交
424 425 426
		}

		// Set the some services to registries that have been created eagerly
427 428 429
		Registry.as<IActionBarRegistry>(ActionBarExtensions.Actionbar).setInstantiationService(this.instantiationService);
		Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).setInstantiationService(this.instantiationService);
		Registry.as<IEditorRegistry>(EditorExtensions.Editors).setInstantiationService(this.instantiationService);
E
Erich Gamma 已提交
430 431 432 433 434 435
	}

	private initSettings(): void {

		// Sidebar visibility
		this.sideBarHidden = this.storageService.getBoolean(Workbench.sidebarHiddenSettingKey, StorageScope.WORKSPACE, false);
B
Benjamin Pasero 已提交
436
		if (!this.contextService.getWorkspace()) {
437 438
			// some first time users will see a sidebar; returning users will not see the sidebar
			this.sideBarHidden = !this.telemetryService.getExperiments().showDefaultViewlet;
E
Erich Gamma 已提交
439 440
		}

441
		const viewletRegistry = Registry.as<ViewletRegistry>(ViewletExtensions.Viewlets);
I
isidor 已提交
442
		if (!viewletRegistry.getDefaultViewletId()) {
B
Benjamin Pasero 已提交
443
			this.sideBarHidden = true; // can only hide sidebar if we dont have a default Viewlet id
E
Erich Gamma 已提交
444 445
		}

I
isidor 已提交
446
		// Panel part visibility
447
		const panelRegistry = Registry.as<PanelRegistry>(PanelExtensions.Panels);
I
isidor 已提交
448
		this.panelHidden = this.storageService.getBoolean(Workbench.panelHiddenSettingKey, StorageScope.WORKSPACE, true);
B
Benjamin Pasero 已提交
449
		if (!this.contextService.getWorkspace() || !panelRegistry.getDefaultPanelId()) {
450
			this.panelHidden = true; // we hide panel part in single-file-mode or if there is no default panel
I
isidor 已提交
451
		}
I
isidor 已提交
452

E
Erich Gamma 已提交
453
		// Sidebar position
454 455
		const sideBarPosition = this.configurationService.lookup<string>(Workbench.sidebarPositionConfigurationKey).value;
		this.sideBarPosition = (sideBarPosition === 'right') ? Position.RIGHT : Position.LEFT;
B
Benjamin Pasero 已提交
456 457

		// Statusbar visibility
458 459
		const statusBarVisible = this.configurationService.lookup<string>(Workbench.statusbarVisibleConfigurationKey).value;
		this.statusBarHidden = !statusBarVisible;
E
Erich Gamma 已提交
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
	}

	/**
	 * Returns whether the workbench has been started.
	 */
	public isStarted(): boolean {
		return this.workbenchStarted && !this.workbenchShutdown;
	}

	/**
	 * Returns whether the workbench has been fully created.
	 */
	public isCreated(): boolean {
		return this.workbenchCreated && this.workbenchStarted;
	}

	public joinCreation(): TPromise<boolean> {
		return this.creationPromise;
	}

	public hasFocus(part: Parts): boolean {
B
Benjamin Pasero 已提交
481
		const activeElement = document.activeElement;
E
Erich Gamma 已提交
482 483 484 485
		if (!activeElement) {
			return false;
		}

486 487 488 489 490
		const container = this.getContainer(part);
		return DOM.isAncestor(activeElement, container);
	}

	public getContainer(part: Parts): HTMLElement {
E
Erich Gamma 已提交
491 492 493 494 495 496 497 498
		let container: Builder = null;
		switch (part) {
			case Parts.ACTIVITYBAR_PART:
				container = this.activitybarPart.getContainer();
				break;
			case Parts.SIDEBAR_PART:
				container = this.sidebarPart.getContainer();
				break;
I
isidor 已提交
499 500 501
			case Parts.PANEL_PART:
				container = this.panelPart.getContainer();
				break;
E
Erich Gamma 已提交
502 503 504 505 506 507 508
			case Parts.EDITOR_PART:
				container = this.editorPart.getContainer();
				break;
			case Parts.STATUSBAR_PART:
				container = this.statusbarPart.getContainer();
				break;
		}
509
		return container && container.getHTMLElement();
E
Erich Gamma 已提交
510 511 512
	}

	public isVisible(part: Parts): boolean {
B
Benjamin Pasero 已提交
513 514 515 516 517 518 519
		switch (part) {
			case Parts.SIDEBAR_PART:
				return !this.sideBarHidden;
			case Parts.PANEL_PART:
				return !this.panelHidden;
			case Parts.STATUSBAR_PART:
				return !this.statusBarHidden;
520
		}
E
Erich Gamma 已提交
521 522 523 524

		return true; // any other part cannot be hidden
	}

525 526 527 528
	public isStatusBarHidden(): boolean {
		return this.statusBarHidden;
	}

529
	private setStatusBarHidden(hidden: boolean, skipLayout?: boolean): void {
530 531 532 533
		this.statusBarHidden = hidden;

		// Layout
		if (!skipLayout) {
B
Benjamin Pasero 已提交
534
			this.workbenchLayout.layout({ forceStyleReCompute: true });
535 536 537
		}
	}

E
Erich Gamma 已提交
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
	public isSideBarHidden(): boolean {
		return this.sideBarHidden;
	}

	public setSideBarHidden(hidden: boolean, skipLayout?: boolean): void {
		this.sideBarHidden = hidden;

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

		// Layout
		if (!skipLayout) {
B
Benjamin Pasero 已提交
554
			this.workbenchLayout.layout({ forceStyleReCompute: true });
E
Erich Gamma 已提交
555 556
		}

B
Benjamin Pasero 已提交
557
		// If sidebar becomes hidden, also hide the current active Viewlet if any
E
Erich Gamma 已提交
558 559 560
		if (hidden && this.sidebarPart.getActiveViewlet()) {
			this.sidebarPart.hideActiveViewlet();

B
Benjamin Pasero 已提交
561 562 563 564 565 566 567 568
			const activeEditor = this.editorPart.getActiveEditor();
			const activePanel = this.panelPart.getActivePanel();

			// Pass Focus to Editor or Panel if Sidebar is now hidden
			if (this.hasFocus(Parts.PANEL_PART) && activePanel) {
				activePanel.focus();
			} else if (activeEditor) {
				activeEditor.focus();
E
Erich Gamma 已提交
569 570 571
			}
		}

B
Benjamin Pasero 已提交
572
		// If sidebar becomes visible, show last active Viewlet or default viewlet
E
Erich Gamma 已提交
573
		else if (!hidden && !this.sidebarPart.getActiveViewlet()) {
574
			const registry = Registry.as<ViewletRegistry>(ViewletExtensions.Viewlets);
B
Benjamin Pasero 已提交
575
			const viewletToOpen = this.sidebarPart.getLastActiveViewletId() || registry.getDefaultViewletId();
E
Erich Gamma 已提交
576 577 578 579 580 581 582 583 584
			if (viewletToOpen) {
				this.sidebarPart.openViewlet(viewletToOpen, true).done(null, errors.onUnexpectedError);
			}
		}

		// Remember in settings
		this.storageService.store(Workbench.sidebarHiddenSettingKey, hidden ? 'true' : 'false', StorageScope.WORKSPACE);
	}

I
isidor 已提交
585 586
	public isPanelHidden(): boolean {
		return this.panelHidden;
I
isidor 已提交
587 588
	}

B
Benjamin Pasero 已提交
589
	public setPanelHidden(hidden: boolean, skipLayout?: boolean): void {
I
isidor 已提交
590
		this.panelHidden = hidden;
I
isidor 已提交
591

592 593 594 595 596 597 598
		// Adjust CSS
		if (hidden) {
			this.workbench.addClass('nopanel');
		} else {
			this.workbench.removeClass('nopanel');
		}

I
isidor 已提交
599 600
		// Layout
		if (!skipLayout) {
B
Benjamin Pasero 已提交
601
			this.workbenchLayout.layout({ forceStyleReCompute: true });
I
isidor 已提交
602 603 604 605 606 607 608
		}

		// If panel part becomes hidden, also hide the current active panel if any
		if (hidden && this.panelPart.getActivePanel()) {
			this.panelPart.hideActivePanel();

			// Pass Focus to Editor if Panel part is now hidden
B
Benjamin Pasero 已提交
609
			const editor = this.editorPart.getActiveEditor();
I
isidor 已提交
610 611 612 613 614 615 616
			if (editor) {
				editor.focus();
			}
		}

		// If panel part becomes visible, show last active panel or default panel
		else if (!hidden && !this.panelPart.getActivePanel()) {
617
			const registry = Registry.as<PanelRegistry>(PanelExtensions.Panels);
B
Benjamin Pasero 已提交
618
			const panelToOpen = this.panelPart.getLastActivePanelId() || registry.getDefaultPanelId();
I
isidor 已提交
619 620 621 622 623 624
			if (panelToOpen) {
				this.panelPart.openPanel(panelToOpen, true).done(null, errors.onUnexpectedError);
			}
		}

		// Remember in settings
I
isidor 已提交
625
		this.storageService.store(Workbench.panelHiddenSettingKey, hidden ? 'true' : 'false', StorageScope.WORKSPACE);
I
isidor 已提交
626 627
	}

I
isidor 已提交
628
	public toggleMaximizedPanel(): void {
B
Benjamin Pasero 已提交
629
		this.workbenchLayout.layout({ forceStyleReCompute: true, toggleMaximizedPanel: true });
I
isidor 已提交
630 631
	}

E
Erich Gamma 已提交
632 633 634 635
	public getSideBarPosition(): Position {
		return this.sideBarPosition;
	}

636
	private setSideBarPosition(position: Position): void {
E
Erich Gamma 已提交
637 638 639 640
		if (this.sideBarHidden) {
			this.setSideBarHidden(false, true /* Skip Layout */);
		}

B
Benjamin Pasero 已提交
641 642
		const newPositionValue = (position === Position.LEFT) ? 'left' : 'right';
		const oldPositionValue = (this.sideBarPosition === Position.LEFT) ? 'left' : 'right';
E
Erich Gamma 已提交
643 644 645 646 647 648 649 650 651
		this.sideBarPosition = position;

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

		// Layout
B
Benjamin Pasero 已提交
652
		this.workbenchLayout.layout({ forceStyleReCompute: true });
E
Erich Gamma 已提交
653 654
	}

B
Benjamin Pasero 已提交
655
	public dispose(): void {
E
Erich Gamma 已提交
656
		if (this.isStarted()) {
B
Benjamin Pasero 已提交
657
			this.shutdownComponents();
E
Erich Gamma 已提交
658 659 660
			this.workbenchShutdown = true;
		}

J
Joao Moreno 已提交
661
		this.toDispose = dispose(this.toDispose);
E
Erich Gamma 已提交
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
	}

	/**
	 * Asks the workbench and all its UI components inside to lay out according to
	 * the containers dimension the workbench is living in.
	 */
	public layout(): void {
		if (this.isStarted()) {
			this.workbenchLayout.layout();
		}
	}

	private shutdownComponents(): void {

		// Pass shutdown on to each participant
		this.toShutdown.forEach(s => s.shutdown());
	}

	private registerListeners(): void {

		// Listen to editor changes
683
		this.toDispose.push(this.editorPart.onEditorsChanged(() => this.onEditorsChanged()));
684 685

		// Handle message service and quick open events
686 687
		this.toDispose.push((<WorkbenchMessageService>this.messageService).onMessagesShowing(() => this.messagesVisibleContext.set(true)));
		this.toDispose.push((<WorkbenchMessageService>this.messageService).onMessagesCleared(() => this.messagesVisibleContext.reset()));
688

689 690 691 692 693
		this.toDispose.push(this.quickOpen.onShow(() => (<WorkbenchMessageService>this.messageService).suspend())); // when quick open is open, don't show messages behind
		this.toDispose.push(this.quickOpen.onHide(() => (<WorkbenchMessageService>this.messageService).resume()));  // resume messages once quick open is closed again

		// Configuration changes
		this.toDispose.push(this.configurationService.onDidUpdateConfiguration(() => this.onDidUpdateConfiguration()));
E
Erich Gamma 已提交
694 695
	}

696
	private onEditorsChanged(): void {
B
Benjamin Pasero 已提交
697
		const visibleEditors = this.editorService.getVisibleEditors().length;
E
Erich Gamma 已提交
698 699 700 701

		// We update the editorpart class to indicate if an editor is opened or not
		// through a delay to accomodate for fast editor switching

702
		const editorContainer = this.editorPart.getContainer();
E
Erich Gamma 已提交
703
		if (visibleEditors === 0) {
704
			this.editorsVisibleContext.reset();
705
			this.editorBackgroundDelayer.trigger(() => editorContainer.addClass('empty'));
E
Erich Gamma 已提交
706
		} else {
707
			this.editorsVisibleContext.set(true);
708
			this.editorBackgroundDelayer.trigger(() => editorContainer.removeClass('empty'));
E
Erich Gamma 已提交
709 710 711
		}
	}

712 713
	private onDidUpdateConfiguration(): void {
		const newSidebarPositionValue = this.configurationService.lookup<string>(Workbench.sidebarPositionConfigurationKey).value;
714
		const newSidebarPosition = (newSidebarPositionValue === 'right') ? Position.RIGHT : Position.LEFT;
715 716 717
		if (newSidebarPosition !== this.getSideBarPosition()) {
			this.setSideBarPosition(newSidebarPosition);
		}
718 719 720 721 722

		const newStatusbarHiddenValue = !this.configurationService.lookup<boolean>(Workbench.statusbarVisibleConfigurationKey).value;
		if (newStatusbarHiddenValue !== this.isStatusBarHidden()) {
			this.setStatusBarHidden(newStatusbarHiddenValue);
		}
723 724
	}

E
Erich Gamma 已提交
725
	private createWorkbenchLayout(): void {
B
Benjamin Pasero 已提交
726
		const options = new LayoutOptions();
E
Erich Gamma 已提交
727 728 729 730 731
		options.setMargin(new Box(0, 0, 0, 0));

		this.workbenchLayout = this.instantiationService.createInstance(WorkbenchLayout,
			$(this.container),							// Parent
			this.workbench,								// Workbench Container
I
isidor 已提交
732 733 734 735 736 737 738
			{
				activitybar: this.activitybarPart,		// Activity Bar
				editor: this.editorPart,				// Editor
				sidebar: this.sidebarPart,				// Sidebar
				panel: this.panelPart,					// Panel Part
				statusbar: this.statusbarPart,			// Statusbar
			},
E
Erich Gamma 已提交
739 740 741 742 743 744 745 746 747 748 749
			this.quickOpen,								// Quickopen
			options										// Layout Options
		);

		this.toDispose.push(this.workbenchLayout);
	}

	private createWorkbench(): void {

		// Create Workbench DIV Off-DOM
		this.workbenchContainer = $('.monaco-workbench-container');
750
		this.workbench = $().div({ 'class': 'monaco-workbench ' + (isWindows ? 'windows' : isLinux ? 'linux' : 'mac'), id: Identifiers.WORKBENCH_CONTAINER }).appendTo(this.workbenchContainer);
E
Erich Gamma 已提交
751 752 753 754 755 756 757 758
	}

	private renderWorkbench(): void {

		// Apply sidebar state as CSS class
		if (this.sideBarHidden) {
			this.workbench.addClass('nosidebar');
		}
759 760 761
		if (this.panelHidden) {
			this.workbench.addClass('nopanel');
		}
E
Erich Gamma 已提交
762 763 764 765 766 767 768 769 770 771

		// Apply no-workspace state as CSS class
		if (!this.workbenchParams.workspace) {
			this.workbench.addClass('no-workspace');
		}

		// Create Parts
		this.createActivityBarPart();
		this.createSidebarPart();
		this.createEditorPart();
772
		this.createPanelPart();
E
Erich Gamma 已提交
773 774 775 776 777 778 779
		this.createStatusbarPart();

		// Add Workbench to DOM
		this.workbenchContainer.build(this.container);
	}

	private createActivityBarPart(): void {
B
Benjamin Pasero 已提交
780
		const activitybarPartContainer = $(this.workbench)
E
Erich Gamma 已提交
781 782
			.div({
				'class': ['part', 'activitybar', this.sideBarPosition === Position.LEFT ? 'left' : 'right'],
783 784
				id: Identifiers.ACTIVITYBAR_PART,
				role: 'navigation'
E
Erich Gamma 已提交
785 786 787 788 789 790
			});

		this.activitybarPart.create(activitybarPartContainer);
	}

	private createSidebarPart(): void {
B
Benjamin Pasero 已提交
791
		const sidebarPartContainer = $(this.workbench)
E
Erich Gamma 已提交
792 793
			.div({
				'class': ['part', 'sidebar', this.sideBarPosition === Position.LEFT ? 'left' : 'right'],
794 795
				id: Identifiers.SIDEBAR_PART,
				role: 'complementary'
E
Erich Gamma 已提交
796 797 798 799 800
			});

		this.sidebarPart.create(sidebarPartContainer);
	}

I
isidor 已提交
801
	private createPanelPart(): void {
B
Benjamin Pasero 已提交
802
		const panelPartContainer = $(this.workbench)
I
isidor 已提交
803
			.div({
804
				'class': ['part', 'panel', 'monaco-editor-background'],
805 806
				id: Identifiers.PANEL_PART,
				role: 'complementary'
I
isidor 已提交
807 808 809 810 811
			});

		this.panelPart.create(panelPartContainer);
	}

E
Erich Gamma 已提交
812
	private createEditorPart(): void {
B
Benjamin Pasero 已提交
813
		const editorContainer = $(this.workbench)
E
Erich Gamma 已提交
814
			.div({
815
				'class': ['part', 'editor', 'monaco-editor-background', 'empty'],
816 817
				id: Identifiers.EDITOR_PART,
				role: 'main'
E
Erich Gamma 已提交
818 819 820 821 822 823
			});

		this.editorPart.create(editorContainer);
	}

	private createStatusbarPart(): void {
B
Benjamin Pasero 已提交
824
		const statusbarContainer = $(this.workbench).div({
E
Erich Gamma 已提交
825
			'class': ['part', 'statusbar'],
826 827
			id: Identifiers.STATUSBAR_PART,
			role: 'contentinfo'
E
Erich Gamma 已提交
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
		});

		this.statusbarPart.create(statusbarContainer);
	}

	public getEditorPart(): EditorPart {
		assert.ok(this.workbenchStarted, 'Workbench is not started. Call startup() first.');

		return this.editorPart;
	}

	public getSidebarPart(): SidebarPart {
		assert.ok(this.workbenchStarted, 'Workbench is not started. Call startup() first.');

		return this.sidebarPart;
	}

I
isidor 已提交
845 846 847 848 849 850
	public getPanelPart(): PanelPart {
		assert.ok(this.workbenchStarted, 'Workbench is not started. Call startup() first.');

		return this.panelPart;
	}

E
Erich Gamma 已提交
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
	public getInstantiationService(): IInstantiationService {
		assert.ok(this.workbenchStarted, 'Workbench is not started. Call startup() first.');

		return this.instantiationService;
	}

	public addClass(clazz: string): void {
		if (this.workbench) {
			this.workbench.addClass(clazz);
		}
	}

	public removeClass(clazz: string): void {
		if (this.workbench) {
			this.workbench.removeClass(clazz);
		}
	}
868 869 870 871

	public getWorkbenchElementId(): string {
		return Identifiers.WORKBENCH_CONTAINER;
	}
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888

	public setRestoreSidebar(): void {
		this.storageService.store(Workbench.sidebarRestoreSettingKey, 'true', StorageScope.WORKSPACE);
	}

	private shouldRestoreSidebar(): boolean {
		if (!this.environmentService.isBuilt) {
			return true; // always restore sidebar when we are in development mode
		}

		const restore = this.storageService.getBoolean(Workbench.sidebarRestoreSettingKey, StorageScope.WORKSPACE);
		if (restore) {
			this.storageService.remove(Workbench.sidebarRestoreSettingKey, StorageScope.WORKSPACE); // only support once
		}

		return restore;
	}
E
Erich Gamma 已提交
889
}