workbench.ts 30.2 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';
E
Erich Gamma 已提交
11
import types = require('vs/base/common/types');
J
Joao Moreno 已提交
12
import {IDisposable, dispose} from 'vs/base/common/lifecycle';
E
Erich Gamma 已提交
13 14 15 16 17 18 19 20
import strings = require('vs/base/common/strings');
import DOM = require('vs/base/browser/dom');
import {Box, Builder, withElementById, $} from 'vs/base/browser/builder';
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');
import {Registry} from 'vs/platform/platform';
M
Martin Aeschlimann 已提交
21
import {Identifiers} from 'vs/workbench/common/constants';
22
import {isWindows, isLinux} from 'vs/base/common/platform';
E
Erich Gamma 已提交
23 24
import {IOptions} from 'vs/workbench/common/options';
import {IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions} from 'vs/workbench/common/contributions';
B
Benjamin Pasero 已提交
25 26
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 已提交
27 28 29
import {Part} from 'vs/workbench/browser/part';
import {HistoryService} from 'vs/workbench/services/history/browser/history';
import {ActivitybarPart} from 'vs/workbench/browser/parts/activitybar/activitybarPart';
B
Benjamin Pasero 已提交
30
import {EditorPart} from 'vs/workbench/browser/parts/editor/editorPart';
E
Erich Gamma 已提交
31
import {SidebarPart} from 'vs/workbench/browser/parts/sidebar/sidebarPart';
I
isidor 已提交
32
import {PanelPart} from 'vs/workbench/browser/parts/panel/panelPart';
E
Erich Gamma 已提交
33 34 35
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 已提交
36
import {ViewletRegistry, Extensions as ViewletExtensions} from 'vs/workbench/browser/viewlet';
I
isidor 已提交
37
import {PanelRegistry, Extensions as PanelExtensions} from 'vs/workbench/browser/panel';
E
Erich Gamma 已提交
38
import {QuickOpenController} from 'vs/workbench/browser/parts/quickopen/quickOpenController';
39
import {DiffEditorInput, toDiffLabel} from 'vs/workbench/common/editor/diffEditorInput';
E
Erich Gamma 已提交
40
import {getServices} from 'vs/platform/instantiation/common/extensions';
41
import {IUntitledEditorService} from 'vs/workbench/services/untitled/common/untitledEditorService';
E
Erich Gamma 已提交
42 43 44
import {WorkbenchEditorService} from 'vs/workbench/services/editor/browser/editorService';
import {Position, Parts, IPartService} from 'vs/workbench/services/part/common/partService';
import {IWorkspaceContextService as IWorkbenchWorkspaceContextService} from 'vs/workbench/services/workspace/common/contextService';
M
Martin Aeschlimann 已提交
45
import {IStorageService, StorageScope} from 'vs/platform/storage/common/storage';
46
import {ContextMenuService} from 'vs/workbench/services/contextview/electron-browser/contextmenuService';
47 48
import {WorkbenchKeybindingService2} from 'vs/workbench/services/keybinding/electron-browser/keybindingService';
import {KeybindingService} from 'vs/platform/contextkey/browser/contextKeyService';
B
Benjamin Pasero 已提交
49
import {IWorkspace, IConfiguration} from 'vs/platform/workspace/common/workspace';
50
import {IKeybindingService2} from 'vs/platform/keybinding/common/keybinding';
A
Alex Dima 已提交
51
import {ContextKeyExpr, RawContextKey, IContextKeyService, IContextKey} from 'vs/platform/contextkey/common/contextkey';
E
Erich Gamma 已提交
52 53
import {IActivityService} from 'vs/workbench/services/activity/common/activityService';
import {IViewletService} from 'vs/workbench/services/viewlet/common/viewletService';
I
isidor 已提交
54
import {IPanelService} from 'vs/workbench/services/panel/common/panelService';
E
Erich Gamma 已提交
55
import {WorkbenchMessageService} from 'vs/workbench/services/message/browser/messageService';
B
Benjamin Pasero 已提交
56
import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService';
57
import {IQuickOpenService} from 'vs/workbench/services/quickopen/common/quickOpenService';
58
import {IEditorGroupService} from 'vs/workbench/services/group/common/groupService';
E
Erich Gamma 已提交
59 60 61
import {IHistoryService} from 'vs/workbench/services/history/common/history';
import {IEventService} from 'vs/platform/event/common/event';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
62
import {SyncDescriptor} from 'vs/platform/instantiation/common/descriptors';
63
import {ServiceCollection} from 'vs/platform/instantiation/common/serviceCollection';
E
Erich Gamma 已提交
64 65
import {ILifecycleService} from 'vs/platform/lifecycle/common/lifecycle';
import {IMessageService} from 'vs/platform/message/common/message';
66
import {IThreadService} from 'vs/workbench/services/thread/common/threadService';
67
import {IStatusbarService} from 'vs/platform/statusbar/common/statusbar';
68
import {IMenuService} from 'vs/platform/actions/common/actions';
J
Johannes Rieken 已提交
69
import {MenuService} from 'vs/platform/actions/common/menuService';
70
import {IContextMenuService} from 'vs/platform/contextview/browser/contextView';
E
Erich Gamma 已提交
71

A
Alex Dima 已提交
72 73
export const MessagesVisibleContext = new RawContextKey<boolean>('globalMessageVisible', false);
export const EditorsVisibleContext = new RawContextKey<boolean>('editorIsOpen', false);
A
Alex Dima 已提交
74
export const NoEditorsVisibleContext:ContextKeyExpr = EditorsVisibleContext.toNegated();
A
Alex Dima 已提交
75

E
Erich Gamma 已提交
76 77 78 79
interface WorkbenchParams {
	workspace?: IWorkspace;
	configuration: IConfiguration;
	options: IOptions;
80
	serviceCollection: ServiceCollection;
E
Erich Gamma 已提交
81 82 83 84
}

export interface IWorkbenchCallbacks {
	onServicesCreated?: () => void;
85
	onWorkbenchStarted?: (customKeybindingsCount: number) => void;
E
Erich Gamma 已提交
86 87 88
}

/**
B
Benjamin Pasero 已提交
89
 * The workbench creates and lays out all parts that make up the workbench.
E
Erich Gamma 已提交
90 91 92 93
 */
export class Workbench implements IPartService {

	private static sidebarPositionSettingKey = 'workbench.sidebar.position';
94
	private static statusbarHiddenSettingKey = 'workbench.statusbar.hidden';
E
Erich Gamma 已提交
95
	private static sidebarHiddenSettingKey = 'workbench.sidebar.hidden';
I
isidor 已提交
96
	private static panelHiddenSettingKey = 'workbench.panel.hidden';
E
Erich Gamma 已提交
97

98
	public _serviceBrand: any;
E
Erich Gamma 已提交
99 100 101 102 103 104 105 106

	private container: HTMLElement;
	private workbenchParams: WorkbenchParams;
	private workbenchContainer: Builder;
	private workbench: Builder;
	private workbenchStarted: boolean;
	private workbenchCreated: boolean;
	private workbenchShutdown: boolean;
107
	private editorService: WorkbenchEditorService;
108
	private contextKeyService: IContextKeyService;
A
Alex Dima 已提交
109
	private keybindingService2: IKeybindingService2;
E
Erich Gamma 已提交
110 111
	private activitybarPart: ActivitybarPart;
	private sidebarPart: SidebarPart;
I
isidor 已提交
112
	private panelPart: PanelPart;
E
Erich Gamma 已提交
113 114 115 116 117 118 119 120 121 122
	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;
123
	private statusBarHidden: boolean;
E
Erich Gamma 已提交
124
	private sideBarPosition: Position;
I
isidor 已提交
125
	private panelHidden: boolean;
E
Erich Gamma 已提交
126
	private editorBackgroundDelayer: Delayer<void>;
A
Alex Dima 已提交
127 128
	private messagesVisibleContext: IContextKey<boolean>;
	private editorsVisibleContext: IContextKey<boolean>;
E
Erich Gamma 已提交
129

130 131 132 133 134 135
	constructor(
		container: HTMLElement,
		workspace: IWorkspace,
		configuration: IConfiguration,
		options: IOptions,
		serviceCollection: ServiceCollection,
136 137 138 139 140 141 142
		@IInstantiationService private instantiationService: IInstantiationService,
		@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
		@IEventService private eventService: IEventService,
		@IWorkbenchWorkspaceContextService private contextService: IWorkbenchWorkspaceContextService,
		@IStorageService private storageService: IStorageService,
		@ILifecycleService private lifecycleService: ILifecycleService,
		@IMessageService private messageService: IMessageService,
143
		@IThreadService private threadService: IThreadService
144
	) {
E
Erich Gamma 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163

		// Validate params
		this.validateParams(container, configuration, options);

		// If String passed in as container, try to find it in DOM
		if (types.isString(container)) {
			let element = withElementById(container.toString());
			this.container = element.getHTMLElement();
		}

		// Otherwise use as HTMLElement
		else {
			this.container = container;
		}

		this.workbenchParams = {
			workspace: workspace,
			configuration: configuration,
			options: options || {},
164
			serviceCollection
E
Erich Gamma 已提交
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
		};

		this.toDispose = [];
		this.toShutdown = [];
		this.editorBackgroundDelayer = new Delayer<void>(50);

		this.creationPromise = new TPromise<boolean>((c, e, p) => {
			this.creationPromiseComplete = c;
		});
	}

	private validateParams(container: HTMLElement, configuration: IConfiguration, options: IOptions): void {

		// Container
		assert.ok(container, 'Workbench requires a container to be created with');
		if (types.isString(container)) {
			let element = withElementById(container.toString());
			assert.ok(element, strings.format('Can not find HTMLElement with id \'{0}\'.', container));
		}
	}

	/**
	 * 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 223 224 225
			// Register Listeners
			this.registerListeners();

			// Settings
			this.initSettings();

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

			// Workbench Layout
			this.createWorkbenchLayout();

			// Register Emitters
			this.registerEmitters();

I
isidor 已提交
226
			// Load composits and editors in parallel
227
			let compositeAndEditorPromises: TPromise<any>[] = [];
E
Erich Gamma 已提交
228

B
Benjamin Pasero 已提交
229
			// Load Viewlet
230 231
			let viewletRegistry = (<ViewletRegistry>Registry.as(ViewletExtensions.Viewlets));
			let viewletId = viewletRegistry.getDefaultViewletId();
232
			if (!this.workbenchParams.configuration.env.isBuilt) {
233
				viewletId = this.storageService.get(SidebarPart.activeViewletSettingsKey, StorageScope.WORKSPACE, viewletRegistry.getDefaultViewletId()); // help developers and restore last view
234 235 236 237
			}

			if (!this.sideBarHidden && !!viewletId) {
				let viewletTimerEvent = timer.start(timer.Topic.STARTUP, strings.format('Opening Viewlet: {0}', viewletId));
I
isidor 已提交
238
				compositeAndEditorPromises.push(this.sidebarPart.openViewlet(viewletId, false).then(() => viewletTimerEvent.stop()));
E
Erich Gamma 已提交
239 240
			}

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

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

B
Benjamin Pasero 已提交
261 262 263
					editorOpenPromise = this.editorPart.openEditors(editors);
				} else {
					editorOpenPromise = this.editorPart.restoreEditors();
264
				}
265 266

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

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

B
Benjamin Pasero 已提交
277
				if (this.callbacks && this.callbacks.onWorkbenchStarted) {
A
Alex Dima 已提交
278
					this.callbacks.onWorkbenchStarted(this.keybindingService2.customKeybindingsCount());
B
Benjamin Pasero 已提交
279
				}
280 281 282 283 284 285

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

B
polish  
Benjamin Pasero 已提交
286
			// Join viewlet, panel and editor promises
287
			TPromise.join(compositeAndEditorPromises).then(() => workbenchDone(), (error) => workbenchDone(error));
E
Erich Gamma 已提交
288 289 290 291 292 293 294 295 296 297
		} catch (error) {

			// Print out error
			console.error(errors.toErrorMessage(error, true));

			// Rethrow
			throw error;
		}
	}

B
Benjamin Pasero 已提交
298 299 300 301 302 303 304 305 306 307 308
	private resolveEditorsToOpen(): TPromise<{ input: EditorInput, options?: EditorOptions }[]> {

		// Files to open, diff or create
		const wbopt = this.workbenchParams.options;
		if ((wbopt.filesToCreate && wbopt.filesToCreate.length) || (wbopt.filesToOpen && wbopt.filesToOpen.length) || (wbopt.filesToDiff && wbopt.filesToDiff.length)) {
			let filesToCreate = wbopt.filesToCreate || [];
			let filesToOpen = wbopt.filesToOpen || [];
			let filesToDiff = wbopt.filesToDiff;

			// Files to diff is exclusive
			if (filesToDiff && filesToDiff.length) {
309
				return TPromise.join<EditorInput>(filesToDiff.map((resourceInput) => this.editorService.createInput(resourceInput))).then((inputsToDiff) => {
B
Benjamin Pasero 已提交
310 311 312 313 314 315 316 317 318 319 320 321 322 323
					return [{ input: new DiffEditorInput(toDiffLabel(filesToDiff[0].resource, filesToDiff[1].resource, this.contextService), null, inputsToDiff[0], inputsToDiff[1]) }];
				});
			}

			// Otherwise: Open/Create files
			else {
				let inputs: EditorInput[] = [];
				let options: EditorOptions[] = [];

				// Files to create
				inputs.push(...filesToCreate.map((resourceInput) => this.untitledEditorService.createOrGet(resourceInput.resource)));
				options.push(...filesToCreate.map(r => null)); // fill empty options for files to create because we dont have options there

				// Files to open
324
				return TPromise.join<EditorInput>(filesToOpen.map((resourceInput) => this.editorService.createInput(resourceInput))).then((inputsToOpen) => {
B
Benjamin Pasero 已提交
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
					inputs.push(...inputsToOpen);
					options.push(...filesToOpen.map(resourceInput => TextEditorOptions.from(resourceInput)));

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

		// Empty workbench
		else if (!this.workbenchParams.workspace) {
			return TPromise.as([{ input: this.untitledEditorService.createOrGet() }]);
		}

		return TPromise.as([]);
	}

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

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

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

349 350 351 352 353 354 355
		// 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
356 357
		this.contextKeyService = this.instantiationService.createInstance(KeybindingService);
		serviceCollection.set(IContextKeyService, this.contextKeyService);
358

A
Alex Dima 已提交
359 360
		this.keybindingService2 = this.instantiationService.createInstance(WorkbenchKeybindingService2, <any>window);
		serviceCollection.set(IKeybindingService2, this.keybindingService2);
A
Alex Dima 已提交
361

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

365 366
		// Menus/Actions
		serviceCollection.set(IMenuService, new SyncDescriptor(MenuService));
367

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

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

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

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

394
		// History
395
		serviceCollection.set(IHistoryService, this.instantiationService.createInstance(HistoryService));
396

E
Erich Gamma 已提交
397
		// Quick open service (quick open controller)
398
		this.quickOpen = this.instantiationService.createInstance(QuickOpenController);
E
Erich Gamma 已提交
399 400
		this.toDispose.push(this.quickOpen);
		this.toShutdown.push(this.quickOpen);
401
		serviceCollection.set(IQuickOpenService, this.quickOpen);
E
Erich Gamma 已提交
402

B
polish  
Benjamin Pasero 已提交
403
		// Contributed services
E
Erich Gamma 已提交
404 405
		let contributedServices = getServices();
		for (let contributedService of contributedServices) {
406
			serviceCollection.set(contributedService.id, contributedService.descriptor);
E
Erich Gamma 已提交
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
		}

		// 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);
		if (!!this.workbenchParams.options.singleFileMode) {
			this.sideBarHidden = true; // we hide sidebar in single-file-mode
		}

I
isidor 已提交
423 424
		let viewletRegistry = (<ViewletRegistry>Registry.as(ViewletExtensions.Viewlets));
		if (!viewletRegistry.getDefaultViewletId()) {
E
Erich Gamma 已提交
425 426 427
			this.sideBarHidden = true; // can only hide sidebar if we dont have a default viewlet id
		}

I
isidor 已提交
428
		// Panel part visibility
I
isidor 已提交
429
		let panelRegistry = (<PanelRegistry>Registry.as(PanelExtensions.Panels));
I
isidor 已提交
430
		this.panelHidden = this.storageService.getBoolean(Workbench.panelHiddenSettingKey, StorageScope.WORKSPACE, true);
I
isidor 已提交
431
		if (!!this.workbenchParams.options.singleFileMode || !panelRegistry.getDefaultPanelId()) {
432
			this.panelHidden = true; // we hide panel part in single-file-mode or if there is no default panel
I
isidor 已提交
433
		}
I
isidor 已提交
434

E
Erich Gamma 已提交
435 436 437
		// Sidebar position
		let rawPosition = this.storageService.get(Workbench.sidebarPositionSettingKey, StorageScope.GLOBAL, 'left');
		this.sideBarPosition = (rawPosition === 'left') ? Position.LEFT : Position.RIGHT;
B
Benjamin Pasero 已提交
438 439

		// Statusbar visibility
440
		this.statusBarHidden = this.storageService.getBoolean(Workbench.statusbarHiddenSettingKey, StorageScope.GLOBAL, false);
E
Erich Gamma 已提交
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
	}

	/**
	 * 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 {
		let activeElement = document.activeElement;
		if (!activeElement) {
			return false;
		}

		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 已提交
475 476 477
			case Parts.PANEL_PART:
				container = this.panelPart.getContainer();
				break;
E
Erich Gamma 已提交
478 479 480 481 482 483 484 485 486 487 488 489
			case Parts.EDITOR_PART:
				container = this.editorPart.getContainer();
				break;
			case Parts.STATUSBAR_PART:
				container = this.statusbarPart.getContainer();
				break;
		}

		return DOM.isAncestor(activeElement, container.getHTMLElement());
	}

	public isVisible(part: Parts): boolean {
B
Benjamin Pasero 已提交
490 491 492 493 494 495 496
		switch (part) {
			case Parts.SIDEBAR_PART:
				return !this.sideBarHidden;
			case Parts.PANEL_PART:
				return !this.panelHidden;
			case Parts.STATUSBAR_PART:
				return !this.statusBarHidden;
497
		}
E
Erich Gamma 已提交
498 499 500 501

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

502 503 504 505 506 507 508 509 510 511 512
	public isStatusBarHidden(): boolean {
		return this.statusBarHidden;
	}

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

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

514
		this.storageService.store(Workbench.statusbarHiddenSettingKey, hidden ? 'true' : 'false');
515 516
	}

E
Erich Gamma 已提交
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
	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);
		}

		// If sidebar becomes hidden, also hide the current active viewlet if any
		if (hidden && this.sidebarPart.getActiveViewlet()) {
			this.sidebarPart.hideActiveViewlet();

			// Pass Focus to Editor if Sidebar is now hidden
			let editor = this.editorPart.getActiveEditor();
			if (editor) {
				editor.focus();
			}
		}

		// If sidebar becomes visible, show last active viewlet or default viewlet
		else if (!hidden && !this.sidebarPart.getActiveViewlet()) {
I
isidor 已提交
549
			let registry = (<ViewletRegistry>Registry.as(ViewletExtensions.Viewlets));
E
Erich Gamma 已提交
550 551 552 553 554 555 556 557 558 559
			let viewletToOpen = this.sidebarPart.getLastActiveViewletId() || registry.getDefaultViewletId();
			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 已提交
560 561
	public isPanelHidden(): boolean {
		return this.panelHidden;
I
isidor 已提交
562 563
	}

B
Benjamin Pasero 已提交
564
	public setPanelHidden(hidden: boolean, skipLayout?: boolean): void {
I
isidor 已提交
565
		this.panelHidden = hidden;
I
isidor 已提交
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592

		// 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
			let editor = this.editorPart.getActiveEditor();
			if (editor) {
				editor.focus();
			}
		}

		// If panel part becomes visible, show last active panel or default panel
		else if (!hidden && !this.panelPart.getActivePanel()) {
			let registry = (<PanelRegistry>Registry.as(PanelExtensions.Panels));
			let panelToOpen = this.panelPart.getLastActivePanelId() || registry.getDefaultPanelId();
			if (panelToOpen) {
				this.panelPart.openPanel(panelToOpen, true).done(null, errors.onUnexpectedError);
			}
		}

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

E
Erich Gamma 已提交
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
	public getSideBarPosition(): Position {
		return this.sideBarPosition;
	}

	public setSideBarPosition(position: Position): void {
		if (this.sideBarHidden) {
			this.setSideBarHidden(false, true /* Skip Layout */);
		}

		let newPositionValue = (position === Position.LEFT) ? 'left' : 'right';
		let oldPositionValue = (this.sideBarPosition === Position.LEFT) ? 'left' : 'right';
		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);

		// Remember in settings
		this.storageService.store(Workbench.sidebarPositionSettingKey, position === Position.LEFT ? 'left' : 'right', StorageScope.GLOBAL);
	}

B
Benjamin Pasero 已提交
622
	public dispose(): void {
E
Erich Gamma 已提交
623
		if (this.isStarted()) {
B
Benjamin Pasero 已提交
624
			this.shutdownComponents();
E
Erich Gamma 已提交
625 626 627
			this.workbenchShutdown = true;
		}

J
Joao Moreno 已提交
628
		this.toDispose = dispose(this.toDispose);
E
Erich Gamma 已提交
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
	}

	/**
	 * 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 registerEmitters(): void {

		// Part Emitters
		this.hookPartListeners(this.activitybarPart);
		this.hookPartListeners(this.editorPart);
		this.hookPartListeners(this.sidebarPart);
I
isidor 已提交
653
		this.hookPartListeners(this.panelPart);
E
Erich Gamma 已提交
654 655 656
	}

	private hookPartListeners(part: Part): void {
A
Alex Dima 已提交
657
		this.toDispose.push(this.eventService.addEmitter2(part, part.getId()));
E
Erich Gamma 已提交
658 659 660 661 662
	}

	private registerListeners(): void {

		// Listen to editor changes
663
		this.toDispose.push(this.editorPart.onEditorsChanged(() => this.onEditorsChanged()));
664 665 666

		// Handle message service and quick open events
		if (this.messageService instanceof WorkbenchMessageService) {
667 668
			this.toDispose.push((<WorkbenchMessageService>this.messageService).onMessagesShowing(() => this.messagesVisibleContext.set(true)));
			this.toDispose.push((<WorkbenchMessageService>this.messageService).onMessagesCleared(() => this.messagesVisibleContext.reset()));
669 670 671 672

			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
		}
E
Erich Gamma 已提交
673 674
	}

675
	private onEditorsChanged(): void {
E
Erich Gamma 已提交
676 677 678 679 680
		let visibleEditors = this.editorService.getVisibleEditors().length;

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

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

	private createWorkbenchLayout(): void {
		let options = new LayoutOptions();
		options.setMargin(new Box(0, 0, 0, 0));

		this.workbenchLayout = this.instantiationService.createInstance(WorkbenchLayout,
			$(this.container),							// Parent
			this.workbench,								// Workbench Container
I
isidor 已提交
698 699 700 701 702 703 704
			{
				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 已提交
705 706 707 708 709 710 711 712 713 714 715
			this.quickOpen,								// Quickopen
			options										// Layout Options
		);

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

	private createWorkbench(): void {

		// Create Workbench DIV Off-DOM
		this.workbenchContainer = $('.monaco-workbench-container');
716
		this.workbench = $().div({ 'class': 'monaco-workbench ' + (isWindows ? 'windows' : isLinux ? 'linux' : 'mac'), id: Identifiers.WORKBENCH_CONTAINER }).appendTo(this.workbenchContainer);
E
Erich Gamma 已提交
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
	}

	private renderWorkbench(): void {

		// Apply sidebar state as CSS class
		if (this.sideBarHidden) {
			this.workbench.addClass('nosidebar');
		}

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

		// Create Parts
		this.createActivityBarPart();
		this.createSidebarPart();
		this.createEditorPart();
735
		this.createPanelPart();
E
Erich Gamma 已提交
736 737 738 739 740 741 742 743 744 745
		this.createStatusbarPart();

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

	private createActivityBarPart(): void {
		let activitybarPartContainer = $(this.workbench)
			.div({
				'class': ['part', 'activitybar', this.sideBarPosition === Position.LEFT ? 'left' : 'right'],
746 747
				id: Identifiers.ACTIVITYBAR_PART,
				role: 'navigation'
E
Erich Gamma 已提交
748 749 750 751 752 753 754 755 756
			});

		this.activitybarPart.create(activitybarPartContainer);
	}

	private createSidebarPart(): void {
		let sidebarPartContainer = $(this.workbench)
			.div({
				'class': ['part', 'sidebar', this.sideBarPosition === Position.LEFT ? 'left' : 'right'],
757 758
				id: Identifiers.SIDEBAR_PART,
				role: 'complementary'
E
Erich Gamma 已提交
759 760 761 762 763
			});

		this.sidebarPart.create(sidebarPartContainer);
	}

I
isidor 已提交
764 765 766
	private createPanelPart(): void {
		let panelPartContainer = $(this.workbench)
			.div({
767
				'class': ['part', 'panel', 'monaco-editor-background'],
768 769
				id: Identifiers.PANEL_PART,
				role: 'complementary'
I
isidor 已提交
770 771 772 773 774
			});

		this.panelPart.create(panelPartContainer);
	}

E
Erich Gamma 已提交
775 776 777
	private createEditorPart(): void {
		let editorContainer = $(this.workbench)
			.div({
778
				'class': ['part', 'editor', 'monaco-editor-background'],
779 780
				id: Identifiers.EDITOR_PART,
				role: 'main'
E
Erich Gamma 已提交
781 782 783 784 785 786 787 788
			});

		this.editorPart.create(editorContainer);
	}

	private createStatusbarPart(): void {
		let statusbarContainer = $(this.workbench).div({
			'class': ['part', 'statusbar'],
789 790
			id: Identifiers.STATUSBAR_PART,
			role: 'contentinfo'
E
Erich Gamma 已提交
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
		});

		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 已提交
808 809 810 811 812 813
	public getPanelPart(): PanelPart {
		assert.ok(this.workbenchStarted, 'Workbench is not started. Call startup() first.');

		return this.panelPart;
	}

E
Erich Gamma 已提交
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
	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);
		}
	}
}