compositePart.ts 17.6 KB
Newer Older
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

B
Benjamin Pasero 已提交
6 7
'use strict';

B
Benjamin Pasero 已提交
8
import 'vs/css!./media/compositepart';
9
import nls = require('vs/nls');
10
import { defaultGenerator } from 'vs/base/common/idGenerator';
J
Johannes Rieken 已提交
11 12 13 14
import { TPromise } from 'vs/base/common/winjs.base';
import { Registry } from 'vs/platform/platform';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { Dimension, Builder, $ } from 'vs/base/browser/builder';
15 16
import events = require('vs/base/common/events');
import strings = require('vs/base/common/strings');
J
Johannes Rieken 已提交
17
import { Emitter } from 'vs/base/common/event';
18 19
import types = require('vs/base/common/types');
import errors = require('vs/base/common/errors');
J
Johannes Rieken 已提交
20 21 22 23 24
import { CONTEXT as ToolBarContext, ToolBar } from 'vs/base/browser/ui/toolbar/toolbar';
import { IActionItem, ActionsOrientation } from 'vs/base/browser/ui/actionbar/actionbar';
import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar';
import { IActionBarRegistry, Extensions, prepareActions } from 'vs/workbench/browser/actionBarRegistry';
import { Action, IAction } from 'vs/base/common/actions';
25
import { Part, IPartOptions } from 'vs/workbench/browser/part';
J
Johannes Rieken 已提交
26 27 28 29 30 31 32 33 34 35 36 37
import { Composite, CompositeRegistry } from 'vs/workbench/browser/composite';
import { IComposite } from 'vs/workbench/common/composite';
import { WorkbenchProgressService } from 'vs/workbench/services/progress/browser/progressService';
import { IPartService } from 'vs/workbench/services/part/common/partService';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { IMessageService, Severity } from 'vs/platform/message/common/message';
import { IProgressService } from 'vs/platform/progress/common/progress';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
38
import { IThemeService } from 'vs/platform/theme/common/themeService';
39

40 41 42 43 44 45 46 47
export interface ICompositeTitleLabel {

	/**
	 * Asks to update the title for the composite with the given ID.
	 */
	updateTitle(id: string, title: string, keybinding?: string): void;
}

48
export abstract class CompositePart<T extends Composite> extends Part {
A
Alex Dima 已提交
49
	private instantiatedCompositeListeners: IDisposable[];
50 51 52 53 54
	private mapCompositeToCompositeContainer: { [compositeId: string]: Builder; };
	private mapActionsBindingToComposite: { [compositeId: string]: () => void; };
	private mapProgressServiceToComposite: { [compositeId: string]: IProgressService; };
	private activeComposite: Composite;
	private lastActiveCompositeId: string;
B
Benjamin Pasero 已提交
55
	private instantiatedComposites: Composite[];
56
	private titleLabel: ICompositeTitleLabel;
57 58 59 60 61
	private toolBar: ToolBar;
	private compositeLoaderPromises: { [compositeId: string]: TPromise<Composite>; };
	private progressBar: ProgressBar;
	private contentAreaSize: Dimension;
	private telemetryActionsListener: IDisposable;
62
	private currentCompositeOpenToken: string;
63 64
	protected _onDidCompositeOpen = new Emitter<IComposite>();
	protected _onDidCompositeClose = new Emitter<IComposite>();
65 66 67 68 69 70 71 72

	constructor(
		private messageService: IMessageService,
		private storageService: IStorageService,
		private telemetryService: ITelemetryService,
		private contextMenuService: IContextMenuService,
		protected partService: IPartService,
		private keybindingService: IKeybindingService,
73
		protected instantiationService: IInstantiationService,
74
		themeService: IThemeService,
75 76
		private registry: CompositeRegistry<T>,
		private activeCompositeSettingsKey: string,
77
		private nameForTelemetry: string,
Y
Yuki Ueda 已提交
78
		private compositeCSSClass: string,
79
		private actionContributionScope: string,
80 81
		id: string,
		options: IPartOptions
82
	) {
83
		super(id, options, themeService);
84 85 86 87 88 89

		this.instantiatedCompositeListeners = [];
		this.mapCompositeToCompositeContainer = {};
		this.mapActionsBindingToComposite = {};
		this.mapProgressServiceToComposite = {};
		this.activeComposite = null;
B
Benjamin Pasero 已提交
90
		this.instantiatedComposites = [];
91
		this.compositeLoaderPromises = {};
92
		this.lastActiveCompositeId = storageService.get(activeCompositeSettingsKey, StorageScope.WORKSPACE);
93 94
	}

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
	protected openComposite(id: string, focus?: boolean): TPromise<Composite> {
		// Check if composite already visible and just focus in that case
		if (this.activeComposite && this.activeComposite.getId() === id) {
			if (focus) {
				this.activeComposite.focus();
			}

			// Fullfill promise with composite that is being opened
			return TPromise.as(this.activeComposite);
		}

		// Open
		return this.doOpenComposite(id, focus);
	}

	private doOpenComposite(id: string, focus?: boolean): TPromise<Composite> {

		// Use a generated token to avoid race conditions from long running promises
113
		let currentCompositeOpenToken = defaultGenerator.nextId();
114 115 116
		this.currentCompositeOpenToken = currentCompositeOpenToken;

		// Hide current
117
		let hidePromise: TPromise<Composite>;
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
		if (this.activeComposite) {
			hidePromise = this.hideActiveComposite();
		} else {
			hidePromise = TPromise.as(null);
		}

		return hidePromise.then(() => {

			// Update Title
			this.updateTitle(id);

			// Create composite
			return this.createComposite(id, true).then((composite: Composite) => {

				// Check if another composite opened meanwhile and return in that case
				if ((this.currentCompositeOpenToken !== currentCompositeOpenToken) || (this.activeComposite && this.activeComposite.getId() !== composite.getId())) {
					return TPromise.as(null);
				}

				// Check if composite already visible and just focus in that case
				if (this.activeComposite && this.activeComposite.getId() === composite.getId()) {
					if (focus) {
						composite.focus();
					}

					// Fullfill promise with composite that is being opened
					return TPromise.as(composite);
				}

				// Show Composite and Focus
				return this.showComposite(composite).then(() => {
					if (focus) {
						composite.focus();
					}

					// Fullfill promise with composite that is being opened
					return composite;
				});
			});
157
		}).then(composite => {
158 159 160 161
			if (composite) {
				this._onDidCompositeOpen.fire(composite);
			}

162
			return composite;
163 164 165
		});
	}

166 167 168
	protected createComposite(id: string, isActive?: boolean): TPromise<Composite> {

		// Check if composite is already created
B
Benjamin Pasero 已提交
169 170 171
		for (let i = 0; i < this.instantiatedComposites.length; i++) {
			if (this.instantiatedComposites[i].getId() === id) {
				return TPromise.as(this.instantiatedComposites[i]);
172 173 174 175 176 177 178 179
			}
		}

		// Instantiate composite from registry otherwise
		let compositeDescriptor = this.registry.getComposite(id);
		if (compositeDescriptor) {
			let loaderPromise = this.compositeLoaderPromises[id];
			if (!loaderPromise) {
180
				let progressService = this.instantiationService.createInstance(WorkbenchProgressService, this.progressBar, compositeDescriptor.id, isActive);
181
				let compositeInstantiationService = this.instantiationService.createChild(new ServiceCollection([IProgressService, progressService]));
182 183 184 185 186

				loaderPromise = compositeInstantiationService.createInstance(compositeDescriptor).then((composite: Composite) => {
					this.mapProgressServiceToComposite[composite.getId()] = progressService;

					// Remember as Instantiated
B
Benjamin Pasero 已提交
187
					this.instantiatedComposites.push(composite);
188 189

					// Register to title area update events from the composite
190
					this.instantiatedCompositeListeners.push(composite.onTitleAreaUpdate(() => this.onTitleAreaUpdate(composite.getId())));
191 192 193 194 195 196 197

					// Remove from Promises Cache since Loaded
					delete this.compositeLoaderPromises[id];

					return composite;
				});

B
Benjamin Pasero 已提交
198
				// Report progress for slow loading composites
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
				progressService.showWhile(loaderPromise, this.partService.isCreated() ? 800 : 3200 /* less ugly initial startup */);

				// Add to Promise Cache until Loaded
				this.compositeLoaderPromises[id] = loaderPromise;
			}

			return loaderPromise;
		}

		throw new Error(strings.format('Unable to find composite with id {0}', id));
	}

	protected showComposite(composite: Composite): TPromise<void> {

		// Remember Composite
		this.activeComposite = composite;

		// Store in preferences
		this.storageService.store(this.activeCompositeSettingsKey, this.activeComposite.getId(), StorageScope.WORKSPACE);

		// Remember
		this.lastActiveCompositeId = this.activeComposite.getId();

		let createCompositePromise: TPromise<void>;

B
Benjamin Pasero 已提交
224
		// Composites created for the first time
225 226 227 228 229
		let compositeContainer = this.mapCompositeToCompositeContainer[composite.getId()];
		if (!compositeContainer) {

			// Build Container off-DOM
			compositeContainer = $().div({
Y
Yuki Ueda 已提交
230
				'class': ['composite', this.compositeCSSClass],
231 232 233 234 235 236 237 238 239 240 241 242 243 244
				id: composite.getId()
			}, (div: Builder) => {
				createCompositePromise = composite.create(div);
			});

			// Remember composite container
			this.mapCompositeToCompositeContainer[composite.getId()] = compositeContainer;
		}

		// Composite already exists but is hidden
		else {
			createCompositePromise = TPromise.as(null);
		}

B
Benjamin Pasero 已提交
245
		// Report progress for slow loading composites (but only if we did not create the composites before already)
246 247 248 249 250 251 252 253
		let progressService = this.mapProgressServiceToComposite[composite.getId()];
		if (progressService && !compositeContainer) {
			this.mapProgressServiceToComposite[composite.getId()].showWhile(createCompositePromise, this.partService.isCreated() ? 800 : 3200 /* less ugly initial startup */);
		}

		// Fill Content and Actions
		return createCompositePromise.then(() => {

I
isidor 已提交
254
			// Make sure that the user meanwhile did not open another composite or closed the part containing the composite
255
			if (!this.activeComposite || composite.getId() !== this.activeComposite.getId()) {
M
Matt Bierner 已提交
256
				return undefined;
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
			}

			// Take Composite on-DOM and show
			compositeContainer.build(this.getContentArea());
			compositeContainer.show();

			// Setup action runner
			this.toolBar.actionRunner = composite.getActionRunner();

			// Update title with composite title if it differs from descriptor
			let descriptor = this.registry.getComposite(composite.getId());
			if (descriptor && descriptor.name !== composite.getTitle()) {
				this.updateTitle(composite.getId(), composite.getTitle());
			}

			// Handle Composite Actions
			let actionsBinding = this.mapActionsBindingToComposite[composite.getId()];
			if (!actionsBinding) {
				actionsBinding = this.collectCompositeActions(composite);
				this.mapActionsBindingToComposite[composite.getId()] = actionsBinding;
			}
			actionsBinding();

			if (this.telemetryActionsListener) {
				this.telemetryActionsListener.dispose();
				this.telemetryActionsListener = null;
			}

			// Action Run Handling
			this.telemetryActionsListener = this.toolBar.actionRunner.addListener2(events.EventType.RUN, (e: any) => {

				// Check for Error
				if (e.error && !errors.isPromiseCanceledError(e.error)) {
					this.messageService.show(Severity.Error, e.error);
				}

				// Log in telemetry
				if (this.telemetryService) {
295
					this.telemetryService.publicLog('workbenchActionExecuted', { id: e.action.id, from: this.nameForTelemetry });
296 297 298 299 300 301
				}
			});

			// Indicate to composite that it is now visible
			return composite.setVisible(true).then(() => {

I
isidor 已提交
302
				// Make sure that the user meanwhile did not open another composite or closed the part containing the composite
303 304 305 306 307 308 309 310 311 312 313 314
				if (!this.activeComposite || composite.getId() !== this.activeComposite.getId()) {
					return;
				}

				// Make sure the composite is layed out
				if (this.contentAreaSize) {
					composite.layout(this.contentAreaSize);
				}
			});
		}, (error: any) => this.onError(error));
	}

315
	protected onTitleAreaUpdate(compositeId: string): void {
316 317

		// Active Composite
318
		if (this.activeComposite && this.activeComposite.getId() === compositeId) {
319 320 321 322 323 324 325 326 327 328 329 330

			// Title
			this.updateTitle(this.activeComposite.getId(), this.activeComposite.getTitle());

			// Actions
			let actionsBinding = this.collectCompositeActions(this.activeComposite);
			this.mapActionsBindingToComposite[this.activeComposite.getId()] = actionsBinding;
			actionsBinding();
		}

		// Otherwise invalidate actions binding for next time when the composite becomes visible
		else {
331
			delete this.mapActionsBindingToComposite[compositeId];
332 333 334
		}
	}

335
	private updateTitle(compositeId: string, compositeTitle?: string): void {
336 337 338 339 340 341 342 343 344
		let compositeDescriptor = this.registry.getComposite(compositeId);
		if (!compositeDescriptor) {
			return;
		}

		if (!compositeTitle) {
			compositeTitle = compositeDescriptor.name;
		}

345
		const keybinding = this.keybindingService.lookupKeybinding(compositeId);
346

347
		this.titleLabel.updateTitle(compositeId, compositeTitle, keybinding ? keybinding.getLabel() : undefined);
348

B
Benjamin Pasero 已提交
349
		this.toolBar.setAriaLabel(nls.localize('ariaCompositeToolbarLabel', "{0} actions", compositeTitle));
350 351 352 353 354
	}

	private collectCompositeActions(composite: Composite): () => void {

		// From Composite
355 356
		let primaryActions: IAction[] = composite.getActions().slice(0);
		let secondaryActions: IAction[] = composite.getSecondaryActions().slice(0);
357

I
isidor 已提交
358 359 360 361
		// From Part
		primaryActions.push(...this.getActions());
		secondaryActions.push(...this.getSecondaryActions());

362
		// From Contributions
B
Benjamin Pasero 已提交
363
		let actionBarRegistry = Registry.as<IActionBarRegistry>(Extensions.Actionbar);
364 365
		primaryActions.push(...actionBarRegistry.getActionBarActionsForContext(this.actionContributionScope, composite));
		secondaryActions.push(...actionBarRegistry.getSecondaryActionBarActionsForContext(this.actionContributionScope, composite));
366 367 368 369 370 371 372 373 374 375 376 377 378

		// Return fn to set into toolbar
		return this.toolBar.setActions(prepareActions(primaryActions), prepareActions(secondaryActions));
	}

	protected getActiveComposite(): IComposite {
		return this.activeComposite;
	}

	protected getLastActiveCompositetId(): string {
		return this.lastActiveCompositeId;
	}

379
	protected hideActiveComposite(): TPromise<Composite> {
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
		if (!this.activeComposite) {
			return TPromise.as(null); // Nothing to do
		}

		let composite = this.activeComposite;
		this.activeComposite = null;

		let compositeContainer = this.mapCompositeToCompositeContainer[composite.getId()];

		// Indicate to Composite
		return composite.setVisible(false).then(() => {

			// Take Container Off-DOM and hide
			compositeContainer.offDOM();
			compositeContainer.hide();

			// Clear any running Progress
			this.progressBar.stop().getContainer().hide();

			// Empty Actions
			this.toolBar.setActions([])();
401
			this._onDidCompositeClose.fire(composite);
402

403
			return composite;
404 405 406 407 408 409 410
		});
	}

	public createTitleArea(parent: Builder): Builder {

		// Title Area Container
		let titleArea = $(parent).div({
I
isidor 已提交
411
			'class': ['composite', 'title']
412 413
		});

I
isidor 已提交
414
		// Left Title Label
415
		this.titleLabel = this.createTitleLabel(titleArea);
I
isidor 已提交
416

417 418 419 420 421 422 423 424
		// Right Actions Container
		$(titleArea).div({
			'class': 'title-actions'
		}, (div) => {

			// Toolbar
			this.toolBar = new ToolBar(div.getHTMLElement(), this.contextMenuService, {
				actionItemProvider: (action: Action) => this.actionItemProvider(action),
425
				orientation: ActionsOrientation.HORIZONTAL,
426
				getKeyBinding: (action) => this.keybindingService.lookupKeybinding(action.id)
427 428 429 430 431 432
			});
		});

		return titleArea;
	}

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
	protected createTitleLabel(parent: Builder): ICompositeTitleLabel {
		let titleLabel: Builder;
		$(parent).div({
			'class': 'title-label'
		}, (div) => {
			titleLabel = div.span();
		});

		return {
			updateTitle: (id, title, keybinding) => {
				titleLabel.safeInnerHtml(title);
				titleLabel.title(keybinding ? nls.localize('titleTooltip', "{0} ({1})", title, keybinding) : title);
			}
		};
	}

449 450 451 452 453 454 455 456 457 458
	private actionItemProvider(action: Action): IActionItem {
		let actionItem: IActionItem;

		// Check Active Composite
		if (this.activeComposite) {
			actionItem = this.activeComposite.getActionItem(action);
		}

		// Check Registry
		if (!actionItem) {
B
Benjamin Pasero 已提交
459
			let actionBarRegistry = Registry.as<IActionBarRegistry>(Extensions.Actionbar);
460
			actionItem = actionBarRegistry.getActionItemForContext(this.actionContributionScope, ToolBarContext, action);
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
		}

		return actionItem;
	}

	public createContentArea(parent: Builder): Builder {
		return $(parent).div({
			'class': 'content'
		}, (div: Builder) => {
			this.progressBar = new ProgressBar(div);
			this.progressBar.getContainer().hide();
		});
	}

	private onError(error: any): void {
		this.messageService.show(Severity.Error, types.isString(error) ? new Error(error) : error);
	}
478 479 480 481

	public getProgressIndicator(id: string): IProgressService {
		return this.mapProgressServiceToComposite[id];
	}
482

I
isidor 已提交
483 484 485 486 487 488 489 490
	protected getActions(): IAction[] {
		return [];
	}

	protected getSecondaryActions(): IAction[] {
		return [];
	}

491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
	public layout(dimension: Dimension): Dimension[] {

		// Pass to super
		let sizes = super.layout(dimension);

		// Pass Contentsize to composite
		this.contentAreaSize = sizes[1];
		if (this.activeComposite) {
			this.activeComposite.layout(this.contentAreaSize);
		}

		return sizes;
	}

	public shutdown(): void {
B
Benjamin Pasero 已提交
506
		this.instantiatedComposites.forEach(i => i.shutdown());
507 508 509 510 511 512 513 514 515

		super.shutdown();
	}

	public dispose(): void {
		this.mapCompositeToCompositeContainer = null;
		this.mapProgressServiceToComposite = null;
		this.mapActionsBindingToComposite = null;

B
Benjamin Pasero 已提交
516 517
		for (let i = 0; i < this.instantiatedComposites.length; i++) {
			this.instantiatedComposites[i].dispose();
518 519
		}

B
Benjamin Pasero 已提交
520
		this.instantiatedComposites = [];
521

A
Alex Dima 已提交
522
		this.instantiatedCompositeListeners = dispose(this.instantiatedCompositeListeners);
523 524 525 526 527 528 529 530

		this.progressBar.dispose();
		this.toolBar.dispose();

		// Super Dispose
		super.dispose();
	}
}