workbench.ts 32.5 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

10
import {TPromise, ValueCallback} from 'vs/base/common/winjs.base';
J
Joao Moreno 已提交
11
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');
14
import {Box, Builder, $} from 'vs/base/browser/builder';
E
Erich Gamma 已提交
15 16 17 18
import {Delayer} from 'vs/base/common/async';
import assert = require('vs/base/common/assert');
import timer = require('vs/base/common/timer');
import errors = require('vs/base/common/errors');
19
import {toErrorMessage} from 'vs/base/common/errorMessage';
E
Erich Gamma 已提交
20
import {Registry} from 'vs/platform/platform';
21
import {isWindows, isLinux} from 'vs/base/common/platform';
E
Erich Gamma 已提交
22 23
import {IOptions} from 'vs/workbench/common/options';
import {IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions} from 'vs/workbench/common/contributions';
B
Benjamin Pasero 已提交
24 25
import {BaseEditor} from 'vs/workbench/browser/parts/editor/baseEditor';
import {IEditorRegistry, Extensions as EditorExtensions, TextEditorOptions, EditorInput, EditorOptions} from 'vs/workbench/common/editor';
E
Erich Gamma 已提交
26 27
import {HistoryService} from 'vs/workbench/services/history/browser/history';
import {ActivitybarPart} from 'vs/workbench/browser/parts/activitybar/activitybarPart';
B
Benjamin Pasero 已提交
28
import {EditorPart} from 'vs/workbench/browser/parts/editor/editorPart';
E
Erich Gamma 已提交
29
import {SidebarPart} from 'vs/workbench/browser/parts/sidebar/sidebarPart';
I
isidor 已提交
30
import {PanelPart} from 'vs/workbench/browser/parts/panel/panelPart';
E
Erich Gamma 已提交
31 32 33
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';
I
isidor 已提交
34
import {ViewletRegistry, Extensions as ViewletExtensions} from 'vs/workbench/browser/viewlet';
I
isidor 已提交
35
import {PanelRegistry, Extensions as PanelExtensions} from 'vs/workbench/browser/panel';
E
Erich Gamma 已提交
36
import {QuickOpenController} from 'vs/workbench/browser/parts/quickopen/quickOpenController';
37
import {DiffEditorInput, toDiffLabel} from 'vs/workbench/common/editor/diffEditorInput';
E
Erich Gamma 已提交
38
import {getServices} from 'vs/platform/instantiation/common/extensions';
39
import {IUntitledEditorService} from 'vs/workbench/services/untitled/common/untitledEditorService';
E
Erich Gamma 已提交
40 41
import {WorkbenchEditorService} from 'vs/workbench/services/editor/browser/editorService';
import {Position, Parts, IPartService} from 'vs/workbench/services/part/common/partService';
42
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
M
Martin Aeschlimann 已提交
43
import {IStorageService, StorageScope} from 'vs/platform/storage/common/storage';
44
import {ContextMenuService} from 'vs/workbench/services/contextview/electron-browser/contextmenuService';
A
Alex Dima 已提交
45
import {WorkbenchKeybindingService} from 'vs/workbench/services/keybinding/electron-browser/keybindingService';
46
import {IConfigurationService} from 'vs/platform/configuration/common/configuration';
47 48
import {IConfigurationEditingService} from 'vs/workbench/services/configuration/common/configurationEditing';
import {ConfigurationEditingService} from 'vs/workbench/services/configuration/node/configurationEditingService';
A
Alex Dima 已提交
49
import {ContextKeyService} from 'vs/platform/contextkey/browser/contextKeyService';
50
import {IWorkspace} from 'vs/platform/workspace/common/workspace';
51
import {IKeybindingService} from 'vs/platform/keybinding/common/keybinding';
A
Alex Dima 已提交
52
import {ContextKeyExpr, RawContextKey, IContextKeyService, IContextKey} from 'vs/platform/contextkey/common/contextkey';
E
Erich Gamma 已提交
53 54
import {IActivityService} from 'vs/workbench/services/activity/common/activityService';
import {IViewletService} from 'vs/workbench/services/viewlet/common/viewletService';
55 56
import {FileService} from 'vs/workbench/services/files/electron-browser/fileService';
import {IFileService} from 'vs/platform/files/common/files';
57 58
import {IConfigurationResolverService} from 'vs/workbench/services/configurationResolver/common/configurationResolver';
import {ConfigurationResolverService} from 'vs/workbench/services/configurationResolver/node/configurationResolverService';
I
isidor 已提交
59
import {IPanelService} from 'vs/workbench/services/panel/common/panelService';
E
Erich Gamma 已提交
60
import {WorkbenchMessageService} from 'vs/workbench/services/message/browser/messageService';
B
Benjamin Pasero 已提交
61
import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService';
62
import {IQuickOpenService} from 'vs/workbench/services/quickopen/common/quickOpenService';
63
import {IEditorGroupService} from 'vs/workbench/services/group/common/groupService';
E
Erich Gamma 已提交
64 65
import {IHistoryService} from 'vs/workbench/services/history/common/history';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
66
import {SyncDescriptor} from 'vs/platform/instantiation/common/descriptors';
67 68
import {TextFileService} from 'vs/workbench/services/textfile/electron-browser/textFileService';
import {ITextFileService} from 'vs/workbench/services/textfile/common/textfiles';
69
import {ServiceCollection} from 'vs/platform/instantiation/common/serviceCollection';
E
Erich Gamma 已提交
70 71
import {ILifecycleService} from 'vs/platform/lifecycle/common/lifecycle';
import {IMessageService} from 'vs/platform/message/common/message';
72
import {IStatusbarService} from 'vs/platform/statusbar/common/statusbar';
73
import {IMenuService} from 'vs/platform/actions/common/actions';
J
Johannes Rieken 已提交
74
import {MenuService} from 'vs/platform/actions/common/menuService';
75
import {IContextMenuService} from 'vs/platform/contextview/browser/contextView';
B
Benjamin Pasero 已提交
76
import {IEnvironmentService} from 'vs/platform/environment/common/environment';
77
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
E
Erich Gamma 已提交
78

A
Alex Dima 已提交
79 80
export const MessagesVisibleContext = new RawContextKey<boolean>('globalMessageVisible', false);
export const EditorsVisibleContext = new RawContextKey<boolean>('editorIsOpen', false);
A
Alex Dima 已提交
81
export const NoEditorsVisibleContext:ContextKeyExpr = EditorsVisibleContext.toNegated();
A
Alex Dima 已提交
82

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

export interface IWorkbenchCallbacks {
	onServicesCreated?: () => void;
91
	onWorkbenchStarted?: (customKeybindingsCount: number) => void;
E
Erich Gamma 已提交
92 93
}

94 95 96 97 98 99 100 101 102
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 已提交
103
/**
B
Benjamin Pasero 已提交
104
 * The workbench creates and lays out all parts that make up the workbench.
E
Erich Gamma 已提交
105 106 107
 */
export class Workbench implements IPartService {

108
	private static statusbarHiddenSettingKey = 'workbench.statusbar.hidden';
E
Erich Gamma 已提交
109
	private static sidebarHiddenSettingKey = 'workbench.sidebar.hidden';
110
	private static sidebarRestoreSettingKey = 'workbench.sidebar.restore';
I
isidor 已提交
111
	private static panelHiddenSettingKey = 'workbench.panel.hidden';
E
Erich Gamma 已提交
112

113 114
	private static sidebarPositionConfigurationKey = 'workbench.sideBar.location';

115
	public _serviceBrand: any;
E
Erich Gamma 已提交
116 117 118 119 120 121 122 123

	private container: HTMLElement;
	private workbenchParams: WorkbenchParams;
	private workbenchContainer: Builder;
	private workbench: Builder;
	private workbenchStarted: boolean;
	private workbenchCreated: boolean;
	private workbenchShutdown: boolean;
124
	private editorService: WorkbenchEditorService;
125
	private contextKeyService: IContextKeyService;
126
	private keybindingService: IKeybindingService;
127
	private configurationEditingService: IConfigurationEditingService;
E
Erich Gamma 已提交
128 129
	private activitybarPart: ActivitybarPart;
	private sidebarPart: SidebarPart;
I
isidor 已提交
130
	private panelPart: PanelPart;
E
Erich Gamma 已提交
131 132 133 134 135 136 137 138 139 140
	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;
141
	private statusBarHidden: boolean;
E
Erich Gamma 已提交
142
	private sideBarPosition: Position;
I
isidor 已提交
143
	private panelHidden: boolean;
E
Erich Gamma 已提交
144
	private editorBackgroundDelayer: Delayer<void>;
A
Alex Dima 已提交
145 146
	private messagesVisibleContext: IContextKey<boolean>;
	private editorsVisibleContext: IContextKey<boolean>;
147
	private hasFilesToCreateOpenOrDiff: boolean;
E
Erich Gamma 已提交
148

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

		this.workbenchParams = {
			workspace: workspace,
168
			options,
169
			serviceCollection
E
Erich Gamma 已提交
170 171
		};

172 173
		this.hasFilesToCreateOpenOrDiff = (options.filesToCreate && options.filesToCreate.length > 0) || (options.filesToOpen && options.filesToOpen.length > 0) || (options.filesToDiff && options.filesToDiff.length > 0);

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

178
		this.creationPromise = new TPromise<boolean>(c => {
E
Erich Gamma 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
			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();
			}

204
			// Contexts
205 206
			this.messagesVisibleContext = MessagesVisibleContext.bindTo(this.contextKeyService);
			this.editorsVisibleContext = EditorsVisibleContext.bindTo(this.contextKeyService);
207

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

			// Settings
			this.initSettings();

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

			// Workbench Layout
			this.createWorkbenchLayout();

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

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

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

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

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

B
Benjamin Pasero 已提交
255 256 257
					editorOpenPromise = this.editorPart.openEditors(editors);
				} else {
					editorOpenPromise = this.editorPart.restoreEditors();
258
				}
259 260

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

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

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

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

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

			// Print out error
285
			console.error(toErrorMessage(error, true));
E
Erich Gamma 已提交
286 287 288 289 290 291

			// Rethrow
			throw error;
		}
	}

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

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

			// Files to diff is exclusive
			if (filesToDiff && filesToDiff.length) {
303
				return TPromise.join<EditorInput>(filesToDiff.map(resourceInput => this.editorService.createInput(resourceInput))).then((inputsToDiff) => {
B
Benjamin Pasero 已提交
304 305 306 307 308 309
					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 已提交
310 311
				const inputs: EditorInput[] = [];
				const options: EditorOptions[] = [];
B
Benjamin Pasero 已提交
312 313

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

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

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

		// Empty workbench
328
		else if (!this.workbenchParams.workspace && this.telemetryService.getExperiments().openUntitledFile) {
B
Benjamin Pasero 已提交
329 330 331 332 333 334
			return TPromise.as([{ input: this.untitledEditorService.createOrGet() }]);
		}

		return TPromise.as([]);
	}

E
Erich Gamma 已提交
335
	private initServices(): void {
336 337
		const {serviceCollection} = this.workbenchParams;

338
		this.toDispose.push(this.lifecycleService.onShutdown(this.shutdownComponents, this));
E
Erich Gamma 已提交
339 340

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

343 344 345 346 347 348 349
		// 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 已提交
350
		this.contextKeyService = this.instantiationService.createInstance(ContextKeyService);
351
		serviceCollection.set(IContextKeyService, this.contextKeyService);
352

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

356
		// Context Menu
357
		serviceCollection.set(IContextMenuService, this.instantiationService.createInstance(ContextMenuService));
358

359 360
		// Menus/Actions
		serviceCollection.set(IMenuService, new SyncDescriptor(MenuService));
361

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

I
isidor 已提交
368
		// Panel service (panel part)
369
		this.panelPart = this.instantiationService.createInstance(PanelPart, Identifiers.PANEL_PART);
I
isidor 已提交
370 371
		this.toDispose.push(this.panelPart);
		this.toShutdown.push(this.panelPart);
372
		serviceCollection.set(IPanelService, this.panelPart);
I
isidor 已提交
373

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

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

388
		// File Service
389 390 391
		const fileService = this.instantiationService.createInstance(FileService);
		serviceCollection.set(IFileService, fileService);

392
		// History
393
		serviceCollection.set(IHistoryService, this.instantiationService.createInstance(HistoryService));
394

395 396 397
		// Text File Service
		serviceCollection.set(ITextFileService, this.instantiationService.createInstance(TextFileService));

398
		// Configuration Editing
399 400
		this.configurationEditingService = this.instantiationService.createInstance(ConfigurationEditingService);
		serviceCollection.set(IConfigurationEditingService, this.configurationEditingService);
401

402
		// Configuration Resolver
403 404
		const workspace = this.contextService.getWorkspace();
		const configurationResolverService = this.instantiationService.createInstance(ConfigurationResolverService, workspace ? workspace.resource : null, process.env);
405 406
		serviceCollection.set(IConfigurationResolverService, configurationResolverService);

E
Erich Gamma 已提交
407
		// Quick open service (quick open controller)
408
		this.quickOpen = this.instantiationService.createInstance(QuickOpenController);
E
Erich Gamma 已提交
409 410
		this.toDispose.push(this.quickOpen);
		this.toShutdown.push(this.quickOpen);
411
		serviceCollection.set(IQuickOpenService, this.quickOpen);
E
Erich Gamma 已提交
412

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

		// Set the some services to registries that have been created eagerly
		<IActionBarRegistry>Registry.as(ActionBarExtensions.Actionbar).setInstantiationService(this.instantiationService);
		<IWorkbenchContributionsRegistry>Registry.as(WorkbenchExtensions.Workbench).setInstantiationService(this.instantiationService);
		<IEditorRegistry>Registry.as(EditorExtensions.Editors).setInstantiationService(this.instantiationService);
	}

	private initSettings(): void {

		// Sidebar visibility
		this.sideBarHidden = this.storageService.getBoolean(Workbench.sidebarHiddenSettingKey, StorageScope.WORKSPACE, false);
B
Benjamin Pasero 已提交
429
		if (!this.contextService.getWorkspace()) {
430
			this.sideBarHidden = !this.telemetryService.getExperiments().showDefaultViewlet;
E
Erich Gamma 已提交
431 432
		}

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

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

E
Erich Gamma 已提交
445
		// Sidebar position
446 447
		const sideBarPosition = this.configurationService.lookup<string>(Workbench.sidebarPositionConfigurationKey).value;
		this.sideBarPosition = (sideBarPosition === 'right') ? Position.RIGHT : Position.LEFT;
B
Benjamin Pasero 已提交
448 449

		// Statusbar visibility
450
		this.statusBarHidden = this.storageService.getBoolean(Workbench.statusbarHiddenSettingKey, StorageScope.GLOBAL, false);
E
Erich Gamma 已提交
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
	}

	/**
	 * 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 已提交
472
		const activeElement = document.activeElement;
E
Erich Gamma 已提交
473 474 475 476
		if (!activeElement) {
			return false;
		}

477 478 479 480 481
		const container = this.getContainer(part);
		return DOM.isAncestor(activeElement, container);
	}

	public getContainer(part: Parts): HTMLElement {
E
Erich Gamma 已提交
482 483 484 485 486 487 488 489
		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 已提交
490 491 492
			case Parts.PANEL_PART:
				container = this.panelPart.getContainer();
				break;
E
Erich Gamma 已提交
493 494 495 496 497 498 499
			case Parts.EDITOR_PART:
				container = this.editorPart.getContainer();
				break;
			case Parts.STATUSBAR_PART:
				container = this.statusbarPart.getContainer();
				break;
		}
500
		return container && container.getHTMLElement();
E
Erich Gamma 已提交
501 502 503
	}

	public isVisible(part: Parts): boolean {
B
Benjamin Pasero 已提交
504 505 506 507 508 509 510
		switch (part) {
			case Parts.SIDEBAR_PART:
				return !this.sideBarHidden;
			case Parts.PANEL_PART:
				return !this.panelHidden;
			case Parts.STATUSBAR_PART:
				return !this.statusBarHidden;
511
		}
E
Erich Gamma 已提交
512 513 514 515

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

516 517 518 519 520 521 522 523 524 525 526
	public isStatusBarHidden(): boolean {
		return this.statusBarHidden;
	}

	public setStatusBarHidden(hidden: boolean, skipLayout?: boolean): void {
		this.statusBarHidden = hidden;

		// Layout
		if (!skipLayout) {
			this.workbenchLayout.layout(true);
		}
527

528
		this.storageService.store(Workbench.statusbarHiddenSettingKey, hidden ? 'true' : 'false');
529 530
	}

E
Erich Gamma 已提交
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
	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) {
			this.workbenchLayout.layout(true);
		}

B
Benjamin Pasero 已提交
550
		// If sidebar becomes hidden, also hide the current active Viewlet if any
E
Erich Gamma 已提交
551 552 553 554
		if (hidden && this.sidebarPart.getActiveViewlet()) {
			this.sidebarPart.hideActiveViewlet();

			// Pass Focus to Editor if Sidebar is now hidden
B
Benjamin Pasero 已提交
555
			const editor = this.editorPart.getActiveEditor();
E
Erich Gamma 已提交
556 557 558 559 560
			if (editor) {
				editor.focus();
			}
		}

B
Benjamin Pasero 已提交
561
		// If sidebar becomes visible, show last active Viewlet or default viewlet
E
Erich Gamma 已提交
562
		else if (!hidden && !this.sidebarPart.getActiveViewlet()) {
B
Benjamin Pasero 已提交
563 564
			const registry = (<ViewletRegistry>Registry.as(ViewletExtensions.Viewlets));
			const viewletToOpen = this.sidebarPart.getLastActiveViewletId() || registry.getDefaultViewletId();
E
Erich Gamma 已提交
565 566 567 568 569 570 571 572 573
			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 已提交
574 575
	public isPanelHidden(): boolean {
		return this.panelHidden;
I
isidor 已提交
576 577
	}

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

581 582 583 584 585 586 587
		// Adjust CSS
		if (hidden) {
			this.workbench.addClass('nopanel');
		} else {
			this.workbench.removeClass('nopanel');
		}

I
isidor 已提交
588 589 590 591 592 593 594 595 596 597
		// Layout
		if (!skipLayout) {
			this.workbenchLayout.layout(true);
		}

		// 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 已提交
598
			const editor = this.editorPart.getActiveEditor();
I
isidor 已提交
599 600 601 602 603 604 605
			if (editor) {
				editor.focus();
			}
		}

		// If panel part becomes visible, show last active panel or default panel
		else if (!hidden && !this.panelPart.getActivePanel()) {
B
Benjamin Pasero 已提交
606 607
			const registry = (<PanelRegistry>Registry.as(PanelExtensions.Panels));
			const panelToOpen = this.panelPart.getLastActivePanelId() || registry.getDefaultPanelId();
I
isidor 已提交
608 609 610 611 612 613
			if (panelToOpen) {
				this.panelPart.openPanel(panelToOpen, true).done(null, errors.onUnexpectedError);
			}
		}

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

E
Erich Gamma 已提交
617 618 619 620
	public getSideBarPosition(): Position {
		return this.sideBarPosition;
	}

621
	private setSideBarPosition(position: Position): void {
E
Erich Gamma 已提交
622 623 624 625
		if (this.sideBarHidden) {
			this.setSideBarHidden(false, true /* Skip Layout */);
		}

B
Benjamin Pasero 已提交
626 627
		const newPositionValue = (position === Position.LEFT) ? 'left' : 'right';
		const oldPositionValue = (this.sideBarPosition === Position.LEFT) ? 'left' : 'right';
E
Erich Gamma 已提交
628 629 630 631 632 633 634 635 636 637 638 639
		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
		this.workbenchLayout.layout(true);
	}

B
Benjamin Pasero 已提交
640
	public dispose(): void {
E
Erich Gamma 已提交
641
		if (this.isStarted()) {
B
Benjamin Pasero 已提交
642
			this.shutdownComponents();
E
Erich Gamma 已提交
643 644 645
			this.workbenchShutdown = true;
		}

J
Joao Moreno 已提交
646
		this.toDispose = dispose(this.toDispose);
E
Erich Gamma 已提交
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
	}

	/**
	 * 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
668
		this.toDispose.push(this.editorPart.onEditorsChanged(() => this.onEditorsChanged()));
669 670

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

674 675 676 677 678
		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 已提交
679 680
	}

681
	private onEditorsChanged(): void {
B
Benjamin Pasero 已提交
682
		const visibleEditors = this.editorService.getVisibleEditors().length;
E
Erich Gamma 已提交
683 684 685 686

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

687
		const editorContainer = this.editorPart.getContainer();
E
Erich Gamma 已提交
688
		if (visibleEditors === 0) {
689
			this.editorsVisibleContext.reset();
690
			this.editorBackgroundDelayer.trigger(() => editorContainer.addClass('empty'));
E
Erich Gamma 已提交
691
		} else {
692
			this.editorsVisibleContext.set(true);
693
			this.editorBackgroundDelayer.trigger(() => editorContainer.removeClass('empty'));
E
Erich Gamma 已提交
694 695 696
		}
	}

697 698 699 700 701 702 703 704 705
	private onDidUpdateConfiguration(): void {
		const newSidebarPositionValue = this.configurationService.lookup<string>(Workbench.sidebarPositionConfigurationKey).value;
		const newSidebarPosition = newSidebarPositionValue === 'right' ? Position.RIGHT : Position.LEFT;

		if (newSidebarPosition !== this.getSideBarPosition()) {
			this.setSideBarPosition(newSidebarPosition);
		}
	}

E
Erich Gamma 已提交
706
	private createWorkbenchLayout(): void {
B
Benjamin Pasero 已提交
707
		const options = new LayoutOptions();
E
Erich Gamma 已提交
708 709 710 711 712
		options.setMargin(new Box(0, 0, 0, 0));

		this.workbenchLayout = this.instantiationService.createInstance(WorkbenchLayout,
			$(this.container),							// Parent
			this.workbench,								// Workbench Container
I
isidor 已提交
713 714 715 716 717 718 719
			{
				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 已提交
720 721 722 723 724 725 726 727 728 729 730
			this.quickOpen,								// Quickopen
			options										// Layout Options
		);

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

	private createWorkbench(): void {

		// Create Workbench DIV Off-DOM
		this.workbenchContainer = $('.monaco-workbench-container');
731
		this.workbench = $().div({ 'class': 'monaco-workbench ' + (isWindows ? 'windows' : isLinux ? 'linux' : 'mac'), id: Identifiers.WORKBENCH_CONTAINER }).appendTo(this.workbenchContainer);
E
Erich Gamma 已提交
732 733 734 735 736 737 738 739
	}

	private renderWorkbench(): void {

		// Apply sidebar state as CSS class
		if (this.sideBarHidden) {
			this.workbench.addClass('nosidebar');
		}
740 741 742
		if (this.panelHidden) {
			this.workbench.addClass('nopanel');
		}
E
Erich Gamma 已提交
743 744 745 746 747 748 749 750 751 752

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

		// Create Parts
		this.createActivityBarPart();
		this.createSidebarPart();
		this.createEditorPart();
753
		this.createPanelPart();
E
Erich Gamma 已提交
754 755 756 757 758 759 760
		this.createStatusbarPart();

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

	private createActivityBarPart(): void {
B
Benjamin Pasero 已提交
761
		const activitybarPartContainer = $(this.workbench)
E
Erich Gamma 已提交
762 763
			.div({
				'class': ['part', 'activitybar', this.sideBarPosition === Position.LEFT ? 'left' : 'right'],
764 765
				id: Identifiers.ACTIVITYBAR_PART,
				role: 'navigation'
E
Erich Gamma 已提交
766 767 768 769 770 771
			});

		this.activitybarPart.create(activitybarPartContainer);
	}

	private createSidebarPart(): void {
B
Benjamin Pasero 已提交
772
		const sidebarPartContainer = $(this.workbench)
E
Erich Gamma 已提交
773 774
			.div({
				'class': ['part', 'sidebar', this.sideBarPosition === Position.LEFT ? 'left' : 'right'],
775 776
				id: Identifiers.SIDEBAR_PART,
				role: 'complementary'
E
Erich Gamma 已提交
777 778 779 780 781
			});

		this.sidebarPart.create(sidebarPartContainer);
	}

I
isidor 已提交
782
	private createPanelPart(): void {
B
Benjamin Pasero 已提交
783
		const panelPartContainer = $(this.workbench)
I
isidor 已提交
784
			.div({
785
				'class': ['part', 'panel', 'monaco-editor-background'],
786 787
				id: Identifiers.PANEL_PART,
				role: 'complementary'
I
isidor 已提交
788 789 790 791 792
			});

		this.panelPart.create(panelPartContainer);
	}

E
Erich Gamma 已提交
793
	private createEditorPart(): void {
B
Benjamin Pasero 已提交
794
		const editorContainer = $(this.workbench)
E
Erich Gamma 已提交
795
			.div({
796
				'class': ['part', 'editor', 'monaco-editor-background'],
797 798
				id: Identifiers.EDITOR_PART,
				role: 'main'
E
Erich Gamma 已提交
799 800 801 802 803 804
			});

		this.editorPart.create(editorContainer);
	}

	private createStatusbarPart(): void {
B
Benjamin Pasero 已提交
805
		const statusbarContainer = $(this.workbench).div({
E
Erich Gamma 已提交
806
			'class': ['part', 'statusbar'],
807 808
			id: Identifiers.STATUSBAR_PART,
			role: 'contentinfo'
E
Erich Gamma 已提交
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
		});

		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 已提交
826 827 828 829 830 831
	public getPanelPart(): PanelPart {
		assert.ok(this.workbenchStarted, 'Workbench is not started. Call startup() first.');

		return this.panelPart;
	}

E
Erich Gamma 已提交
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
	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);
		}
	}
849 850 851 852

	public getWorkbenchElementId(): string {
		return Identifiers.WORKBENCH_CONTAINER;
	}
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869

	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 已提交
870
}