views.ts 33.7 KB
Newer Older
S
Sandeep Somavarapu 已提交
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.
 *--------------------------------------------------------------------------------------------*/

S
Sandeep Somavarapu 已提交
6
import 'vs/css!./media/views';
7
import { Disposable, IDisposable, toDisposable, DisposableStore } from 'vs/base/common/lifecycle';
S
SteVen Batten 已提交
8
import { IViewDescriptorService, ViewContainer, IViewDescriptor, IViewContainersRegistry, Extensions as ViewExtensions, IView, IViewDescriptorCollection, IViewsRegistry, ViewContainerLocation, IViewsService } from 'vs/workbench/common/views';
S
Sandeep Somavarapu 已提交
9
import { Registry } from 'vs/platform/registry/common/platform';
B
Benjamin Pasero 已提交
10
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
11
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
S
Sandeep Somavarapu 已提交
12
import { IContextKeyService, IContextKeyChangeEvent, IReadableSet, IContextKey, RawContextKey, ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
J
Joao Moreno 已提交
13
import { Event, Emitter } from 'vs/base/common/event';
S
Sandeep Somavarapu 已提交
14
import { firstIndex, move, isNonEmptyArray } from 'vs/base/common/arrays';
S
Sandeep Somavarapu 已提交
15
import { isUndefinedOrNull, isUndefined } from 'vs/base/common/types';
S
Sandeep Somavarapu 已提交
16
import { MenuId, MenuRegistry, ICommandAction } from 'vs/platform/actions/common/actions';
S
Sandeep Somavarapu 已提交
17 18 19
import { CommandsRegistry } from 'vs/platform/commands/common/commands';
import { localize } from 'vs/nls';
import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
B
Benjamin Pasero 已提交
20
import { values } from 'vs/base/common/map';
J
Joao Moreno 已提交
21 22
import { IFileIconTheme, IWorkbenchThemeService } from 'vs/workbench/services/themes/common/workbenchThemeService';
import { toggleClass, addClass } from 'vs/base/browser/dom';
23
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
S
SteVen Batten 已提交
24 25
import { IPaneComposite } from 'vs/workbench/common/panecomposite';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
26

27
function filterViewRegisterEvent(container: ViewContainer, event: Event<{ viewContainer: ViewContainer, views: IViewDescriptor[]; }>): Event<IViewDescriptor[]> {
J
Joao Moreno 已提交
28
	return Event.chain(event)
29
		.map(({ views, viewContainer }) => viewContainer === container ? views : [])
30 31 32 33
		.filter(views => views.length > 0)
		.event;
}

34
function filterViewMoveEvent(container: ViewContainer, event: Event<{ from: ViewContainer, to: ViewContainer, views: IViewDescriptor[]; }>): Event<{ added?: IViewDescriptor[], removed?: IViewDescriptor[]; }> {
35 36 37 38 39 40
	return Event.chain(event)
		.map(({ views, from, to }) => from === container ? { removed: views } : to === container ? { added: views } : {})
		.filter(({ added, removed }) => isNonEmptyArray(added) || isNonEmptyArray(removed))
		.event;
}

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
class CounterSet<T> implements IReadableSet<T> {

	private map = new Map<T, number>();

	add(value: T): CounterSet<T> {
		this.map.set(value, (this.map.get(value) || 0) + 1);
		return this;
	}

	delete(value: T): boolean {
		let counter = this.map.get(value) || 0;

		if (counter === 0) {
			return false;
		}

		counter--;

		if (counter === 0) {
			this.map.delete(value);
		} else {
			this.map.set(value, counter);
		}

		return true;
	}

	has(value: T): boolean {
		return this.map.has(value);
	}
}

interface IViewItem {
	viewDescriptor: IViewDescriptor;
	active: boolean;
}

78
class ViewDescriptorCollection extends Disposable implements IViewDescriptorCollection {
79 80 81 82

	private contextKeys = new CounterSet<string>();
	private items: IViewItem[] = [];

S
Sandeep Somavarapu 已提交
83 84 85 86 87
	private _onDidChangeViews: Emitter<{ added: IViewDescriptor[], removed: IViewDescriptor[]; }> = this._register(new Emitter<{ added: IViewDescriptor[], removed: IViewDescriptor[]; }>());
	readonly onDidChangeViews: Event<{ added: IViewDescriptor[], removed: IViewDescriptor[]; }> = this._onDidChangeViews.event;

	private _onDidChangeActiveViews: Emitter<{ added: IViewDescriptor[], removed: IViewDescriptor[]; }> = this._register(new Emitter<{ added: IViewDescriptor[], removed: IViewDescriptor[]; }>());
	readonly onDidChangeActiveViews: Event<{ added: IViewDescriptor[], removed: IViewDescriptor[]; }> = this._onDidChangeActiveViews.event;
88

S
Sandeep Somavarapu 已提交
89
	get activeViewDescriptors(): IViewDescriptor[] {
90 91 92 93 94
		return this.items
			.filter(i => i.active)
			.map(i => i.viewDescriptor);
	}

S
Sandeep Somavarapu 已提交
95 96 97 98
	get allViewDescriptors(): IViewDescriptor[] {
		return this.items.map(i => i.viewDescriptor);
	}

99
	constructor(
S
SteVen Batten 已提交
100
		@IContextKeyService private readonly contextKeyService: IContextKeyService,
101 102
	) {
		super();
S
Sandeep Somavarapu 已提交
103
		this._register(Event.filter(contextKeyService.onDidChangeContext, e => e.affectsSome(this.contextKeys))(this.onContextChanged, this));
104 105
	}

S
Sandeep Somavarapu 已提交
106
	addViews(viewDescriptors: IViewDescriptor[]): void {
S
Sandeep Somavarapu 已提交
107
		const added: IViewDescriptor[] = [];
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123

		for (const viewDescriptor of viewDescriptors) {
			const item = {
				viewDescriptor,
				active: this.isViewDescriptorActive(viewDescriptor) // TODO: should read from some state?
			};

			this.items.push(item);

			if (viewDescriptor.when) {
				for (const key of viewDescriptor.when.keys()) {
					this.contextKeys.add(key);
				}
			}

			if (item.active) {
S
Sandeep Somavarapu 已提交
124
				added.push(viewDescriptor);
125 126 127
			}
		}

S
Sandeep Somavarapu 已提交
128 129
		this._onDidChangeViews.fire({ added: viewDescriptors, removed: [] });

S
Sandeep Somavarapu 已提交
130
		if (added.length) {
S
Sandeep Somavarapu 已提交
131
			this._onDidChangeActiveViews.fire({ added, removed: [] });
132 133 134
		}
	}

S
Sandeep Somavarapu 已提交
135
	removeViews(viewDescriptors: IViewDescriptor[]): void {
S
Sandeep Somavarapu 已提交
136
		const removed: IViewDescriptor[] = [];
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154

		for (const viewDescriptor of viewDescriptors) {
			const index = firstIndex(this.items, i => i.viewDescriptor.id === viewDescriptor.id);

			if (index === -1) {
				continue;
			}

			const item = this.items[index];
			this.items.splice(index, 1);

			if (viewDescriptor.when) {
				for (const key of viewDescriptor.when.keys()) {
					this.contextKeys.delete(key);
				}
			}

			if (item.active) {
S
Sandeep Somavarapu 已提交
155
				removed.push(viewDescriptor);
156 157 158
			}
		}

S
Sandeep Somavarapu 已提交
159 160
		this._onDidChangeViews.fire({ added: [], removed: viewDescriptors });

S
Sandeep Somavarapu 已提交
161
		if (removed.length) {
S
Sandeep Somavarapu 已提交
162
			this._onDidChangeActiveViews.fire({ added: [], removed });
163 164 165
		}
	}

166
	private onContextChanged(event: IContextKeyChangeEvent): void {
S
Sandeep Somavarapu 已提交
167 168
		const removed: IViewDescriptor[] = [];
		const added: IViewDescriptor[] = [];
169 170 171 172 173

		for (const item of this.items) {
			const active = this.isViewDescriptorActive(item.viewDescriptor);

			if (item.active !== active) {
S
Sandeep Somavarapu 已提交
174 175 176 177 178
				if (active) {
					added.push(item.viewDescriptor);
				} else {
					removed.push(item.viewDescriptor);
				}
179 180 181 182 183
			}

			item.active = active;
		}

S
Sandeep Somavarapu 已提交
184
		if (added.length || removed.length) {
S
Sandeep Somavarapu 已提交
185
			this._onDidChangeActiveViews.fire({ added, removed });
186 187 188 189 190 191 192 193 194
		}
	}

	private isViewDescriptorActive(viewDescriptor: IViewDescriptor): boolean {
		return !viewDescriptor.when || this.contextKeyService.contextMatchesRules(viewDescriptor.when);
	}
}

export interface IViewState {
S
Sandeep Somavarapu 已提交
195 196 197
	visibleGlobal: boolean | undefined;
	visibleWorkspace: boolean | undefined;
	collapsed: boolean | undefined;
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
	order?: number;
	size?: number;
}

export interface IViewDescriptorRef {
	viewDescriptor: IViewDescriptor;
	index: number;
}

export interface IAddedViewDescriptorRef extends IViewDescriptorRef {
	collapsed: boolean;
	size?: number;
}

export class ContributableViewsModel extends Disposable {

S
Sandeep Somavarapu 已提交
214 215 216 217 218
	private _viewDescriptors: IViewDescriptor[] = [];
	get viewDescriptors(): ReadonlyArray<IViewDescriptor> {
		return this._viewDescriptors;
	}

219
	get visibleViewDescriptors(): IViewDescriptor[] {
S
Sandeep Somavarapu 已提交
220
		return this.viewDescriptors.filter(v => this.isViewDescriptorVisible(v));
221 222
	}

223 224
	private _onDidAdd = this._register(new Emitter<IAddedViewDescriptorRef[]>());
	readonly onDidAdd: Event<IAddedViewDescriptorRef[]> = this._onDidAdd.event;
225

226 227
	private _onDidRemove = this._register(new Emitter<IViewDescriptorRef[]>());
	readonly onDidRemove: Event<IViewDescriptorRef[]> = this._onDidRemove.event;
228 229 230 231

	private _onDidMove = this._register(new Emitter<{ from: IViewDescriptorRef; to: IViewDescriptorRef; }>());
	readonly onDidMove: Event<{ from: IViewDescriptorRef; to: IViewDescriptorRef; }> = this._onDidMove.event;

S
Sandeep Somavarapu 已提交
232 233 234
	private _onDidChangeViewState = this._register(new Emitter<IViewDescriptorRef>());
	protected readonly onDidChangeViewState: Event<IViewDescriptorRef> = this._onDidChangeViewState.event;

S
Sandeep Somavarapu 已提交
235 236
	private _onDidChangeActiveViews = this._register(new Emitter<ReadonlyArray<IViewDescriptor>>());
	readonly onDidChangeActiveViews: Event<ReadonlyArray<IViewDescriptor>> = this._onDidChangeActiveViews.event;
237

238
	constructor(
S
Sandeep Somavarapu 已提交
239
		container: ViewContainer,
S
SteVen Batten 已提交
240
		viewsService: IViewDescriptorService,
241
		protected viewStates = new Map<string, IViewState>(),
242 243
	) {
		super();
244
		const viewDescriptorCollection = viewsService.getViewDescriptors(container);
S
Sandeep Somavarapu 已提交
245 246
		this._register(viewDescriptorCollection.onDidChangeActiveViews(() => this.onDidChangeViewDescriptors(viewDescriptorCollection.activeViewDescriptors)));
		this.onDidChangeViewDescriptors(viewDescriptorCollection.activeViewDescriptors);
247 248 249
	}

	isVisible(id: string): boolean {
S
Sandeep Somavarapu 已提交
250
		const viewDescriptor = this.viewDescriptors.filter(v => v.id === id)[0];
251

S
Sandeep Somavarapu 已提交
252
		if (!viewDescriptor) {
253 254 255
			throw new Error(`Unknown view ${id}`);
		}

S
Sandeep Somavarapu 已提交
256
		return this.isViewDescriptorVisible(viewDescriptor);
257 258
	}

259
	setVisible(id: string, visible: boolean, size?: number): void {
260 261 262 263 264 265
		const { visibleIndex, viewDescriptor, state } = this.find(id);

		if (!viewDescriptor.canToggleVisibility) {
			throw new Error(`Can't toggle this view's visibility`);
		}

S
Sandeep Somavarapu 已提交
266
		if (this.isViewDescriptorVisible(viewDescriptor) === visible) {
267 268 269
			return;
		}

S
Sandeep Somavarapu 已提交
270 271 272 273 274
		if (viewDescriptor.workspace) {
			state.visibleWorkspace = visible;
		} else {
			state.visibleGlobal = visible;
		}
275

276 277 278 279
		if (typeof size === 'number') {
			state.size = size;
		}

280
		if (visible) {
S
Sandeep Somavarapu 已提交
281
			this._onDidAdd.fire([{ index: visibleIndex, viewDescriptor, size: state.size, collapsed: !!state.collapsed }]);
282
		} else {
283
			this._onDidRemove.fire([{ index: visibleIndex, viewDescriptor }]);
284 285 286 287 288 289 290 291 292 293
		}
	}

	isCollapsed(id: string): boolean {
		const state = this.viewStates.get(id);

		if (!state) {
			throw new Error(`Unknown view ${id}`);
		}

S
Sandeep Somavarapu 已提交
294
		return !!state.collapsed;
295 296 297
	}

	setCollapsed(id: string, collapsed: boolean): void {
S
Sandeep Somavarapu 已提交
298 299 300 301 302
		const { index, state, viewDescriptor } = this.find(id);
		if (state.collapsed !== collapsed) {
			state.collapsed = collapsed;
			this._onDidChangeViewState.fire({ viewDescriptor, index });
		}
303 304 305 306 307 308 309 310 311 312 313 314 315
	}

	getSize(id: string): number | undefined {
		const state = this.viewStates.get(id);

		if (!state) {
			throw new Error(`Unknown view ${id}`);
		}

		return state.size;
	}

	setSize(id: string, size: number): void {
S
Sandeep Somavarapu 已提交
316 317 318 319 320
		const { index, state, viewDescriptor } = this.find(id);
		if (state.size !== size) {
			state.size = size;
			this._onDidChangeViewState.fire({ viewDescriptor, index });
		}
321 322 323 324 325 326 327 328 329
	}

	move(from: string, to: string): void {
		const fromIndex = firstIndex(this.viewDescriptors, v => v.id === from);
		const toIndex = firstIndex(this.viewDescriptors, v => v.id === to);

		const fromViewDescriptor = this.viewDescriptors[fromIndex];
		const toViewDescriptor = this.viewDescriptors[toIndex];

S
Sandeep Somavarapu 已提交
330
		move(this._viewDescriptors, fromIndex, toIndex);
331 332

		for (let index = 0; index < this.viewDescriptors.length; index++) {
333
			const state = this.viewStates.get(this.viewDescriptors[index].id)!;
334 335 336 337 338 339 340 341 342
			state.order = index;
		}

		this._onDidMove.fire({
			from: { index: fromIndex, viewDescriptor: fromViewDescriptor },
			to: { index: toIndex, viewDescriptor: toViewDescriptor }
		});
	}

S
Sandeep Somavarapu 已提交
343 344 345 346 347
	private isViewDescriptorVisible(viewDescriptor: IViewDescriptor): boolean {
		const viewState = this.viewStates.get(viewDescriptor.id);
		if (!viewState) {
			throw new Error(`Unknown view ${viewDescriptor.id}`);
		}
S
Sandeep Somavarapu 已提交
348
		return viewDescriptor.workspace ? !!viewState.visibleWorkspace : !!viewState.visibleGlobal;
S
Sandeep Somavarapu 已提交
349 350
	}

351
	private find(id: string): { index: number, visibleIndex: number, viewDescriptor: IViewDescriptor, state: IViewState; } {
352 353 354
		for (let i = 0, visibleIndex = 0; i < this.viewDescriptors.length; i++) {
			const viewDescriptor = this.viewDescriptors[i];
			const state = this.viewStates.get(viewDescriptor.id);
355 356 357
			if (!state) {
				throw new Error(`View state for ${id} not found`);
			}
358 359 360 361 362

			if (viewDescriptor.id === id) {
				return { index: i, visibleIndex, viewDescriptor, state };
			}

S
Sandeep Somavarapu 已提交
363
			if (viewDescriptor.workspace ? state.visibleWorkspace : state.visibleGlobal) {
364 365 366 367 368 369 370 371 372 373 374 375
				visibleIndex++;
			}
		}

		throw new Error(`view descriptor ${id} not found`);
	}

	private compareViewDescriptors(a: IViewDescriptor, b: IViewDescriptor): number {
		if (a.id === b.id) {
			return 0;
		}

S
Sandeep Somavarapu 已提交
376
		return (this.getViewOrder(a) - this.getViewOrder(b)) || this.getGroupOrderResult(a, b);
377 378 379 380 381 382 383 384 385 386 387 388
	}

	private getGroupOrderResult(a: IViewDescriptor, b: IViewDescriptor) {
		if (!a.group || !b.group) {
			return 0;
		}

		if (a.group === b.group) {
			return 0;
		}

		return a.group < b.group ? -1 : 1;
389 390 391 392 393 394
	}

	private getViewOrder(viewDescriptor: IViewDescriptor): number {
		const viewState = this.viewStates.get(viewDescriptor.id);
		const viewOrder = viewState && typeof viewState.order === 'number' ? viewState.order : viewDescriptor.order;
		return typeof viewOrder === 'number' ? viewOrder : Number.MAX_VALUE;
395 396 397 398
	}

	private onDidChangeViewDescriptors(viewDescriptors: IViewDescriptor[]): void {
		for (const viewDescriptor of viewDescriptors) {
S
Sandeep Somavarapu 已提交
399 400
			const viewState = this.viewStates.get(viewDescriptor.id);
			if (viewState) {
S
Sandeep Somavarapu 已提交
401
				// set defaults if not set
S
Sandeep Somavarapu 已提交
402 403 404 405 406
				if (viewDescriptor.workspace) {
					viewState.visibleWorkspace = isUndefinedOrNull(viewState.visibleWorkspace) ? !viewDescriptor.hideByDefault : viewState.visibleWorkspace;
				} else {
					viewState.visibleGlobal = isUndefinedOrNull(viewState.visibleGlobal) ? !viewDescriptor.hideByDefault : viewState.visibleGlobal;
				}
S
Sandeep Somavarapu 已提交
407
				viewState.collapsed = isUndefinedOrNull(viewState.collapsed) ? !!viewDescriptor.collapsed : viewState.collapsed;
S
Sandeep Somavarapu 已提交
408
			} else {
409
				this.viewStates.set(viewDescriptor.id, {
S
Sandeep Somavarapu 已提交
410 411
					visibleGlobal: !viewDescriptor.hideByDefault,
					visibleWorkspace: !viewDescriptor.hideByDefault,
M
Matt Bierner 已提交
412
					collapsed: !!viewDescriptor.collapsed
413 414 415 416
				});
			}
		}

417
		viewDescriptors = viewDescriptors.sort(this.compareViewDescriptors.bind(this));
418

S
Sandeep Somavarapu 已提交
419
		const toRemove: { index: number, viewDescriptor: IViewDescriptor; }[] = [];
420
		for (let index = 0; index < this._viewDescriptors.length; index++) {
S
Sandeep Somavarapu 已提交
421 422 423 424
			const previousViewDescriptor = this._viewDescriptors[index];
			if (this.isViewDescriptorVisible(previousViewDescriptor) && viewDescriptors.every(viewDescriptor => viewDescriptor.id !== previousViewDescriptor.id)) {
				const { visibleIndex } = this.find(previousViewDescriptor.id);
				toRemove.push({ index: visibleIndex, viewDescriptor: previousViewDescriptor });
425
			}
S
Sandeep Somavarapu 已提交
426
		}
427

428 429
		const previous = this._viewDescriptors;
		this._viewDescriptors = viewDescriptors.slice(0);
S
Sandeep Somavarapu 已提交
430 431

		const toAdd: { index: number, viewDescriptor: IViewDescriptor, size?: number, collapsed: boolean; }[] = [];
432 433
		for (let i = 0; i < this._viewDescriptors.length; i++) {
			const viewDescriptor = this._viewDescriptors[i];
434
			if (this.isViewDescriptorVisible(viewDescriptor) && previous.every(previousViewDescriptor => previousViewDescriptor.id !== viewDescriptor.id)) {
435 436
				const { visibleIndex, state } = this.find(viewDescriptor.id);
				toAdd.push({ index: visibleIndex, viewDescriptor, size: state.size, collapsed: !!state.collapsed });
437 438 439
			}
		}

440 441 442 443 444 445 446
		if (toRemove.length) {
			this._onDidRemove.fire(toRemove);
		}

		if (toAdd.length) {
			this._onDidAdd.fire(toAdd);
		}
447 448

		this._onDidChangeActiveViews.fire(this.viewDescriptors);
449
	}
450 451
}

S
Sandeep Somavarapu 已提交
452 453 454 455 456 457 458 459 460 461 462 463 464
interface IStoredWorkspaceViewState {
	collapsed: boolean;
	isHidden: boolean;
	size?: number;
	order?: number;
}

interface IStoredGlobalViewState {
	id: string;
	isHidden: boolean;
	order?: number;
}

465 466
export class PersistentContributableViewsModel extends ContributableViewsModel {

S
Sandeep Somavarapu 已提交
467 468
	private readonly workspaceViewsStateStorageId: string;
	private readonly globalViewsStateStorageId: string;
469

470
	private storageService: IStorageService;
471 472

	constructor(
S
Sandeep Somavarapu 已提交
473
		container: ViewContainer,
474
		viewletStateStorageId: string,
S
SteVen Batten 已提交
475
		@IViewDescriptorService viewDescriptorService: IViewDescriptorService,
476
		@IStorageService storageService: IStorageService,
477
	) {
S
Sandeep Somavarapu 已提交
478 479
		const globalViewsStateStorageId = `${viewletStateStorageId}.hidden`;
		const viewStates = PersistentContributableViewsModel.loadViewsStates(viewletStateStorageId, globalViewsStateStorageId, storageService);
480

S
SteVen Batten 已提交
481
		super(container, viewDescriptorService, viewStates);
482

S
Sandeep Somavarapu 已提交
483 484
		this.workspaceViewsStateStorageId = viewletStateStorageId;
		this.globalViewsStateStorageId = globalViewsStateStorageId;
485
		this.storageService = storageService;
486

S
Sandeep Somavarapu 已提交
487 488 489 490 491 492
		this._register(Event.any(
			this.onDidAdd,
			this.onDidRemove,
			Event.map(this.onDidMove, ({ from, to }) => [from, to]),
			Event.map(this.onDidChangeViewState, viewDescriptorRef => [viewDescriptorRef]))
			(viewDescriptorRefs => this.saveViewsStates(viewDescriptorRefs.map(r => r.viewDescriptor))));
493 494
	}

S
Sandeep Somavarapu 已提交
495
	private saveViewsStates(viewDescriptors: IViewDescriptor[]): void {
S
Sandeep Somavarapu 已提交
496 497 498 499 500
		this.saveWorkspaceViewsStates();
		this.saveGlobalViewsStates();
	}

	private saveWorkspaceViewsStates(): void {
501
		const storedViewsStates: { [id: string]: IStoredWorkspaceViewState; } = JSON.parse(this.storageService.get(this.workspaceViewsStateStorageId, StorageScope.WORKSPACE, '{}'));
502 503 504
		for (const viewDescriptor of this.viewDescriptors) {
			const viewState = this.viewStates.get(viewDescriptor.id);
			if (viewState) {
S
Sandeep Somavarapu 已提交
505 506 507 508 509 510
				storedViewsStates[viewDescriptor.id] = {
					collapsed: !!viewState.collapsed,
					isHidden: !viewState.visibleWorkspace,
					size: viewState.size,
					order: viewDescriptor.workspace && viewState ? viewState.order : undefined
				};
511 512
			}
		}
B
Benjamin Pasero 已提交
513

514
		if (Object.keys(storedViewsStates).length > 0) {
S
Sandeep Somavarapu 已提交
515
			this.storageService.store(this.workspaceViewsStateStorageId, JSON.stringify(storedViewsStates), StorageScope.WORKSPACE);
B
Benjamin Pasero 已提交
516
		} else {
S
Sandeep Somavarapu 已提交
517
			this.storageService.remove(this.workspaceViewsStateStorageId, StorageScope.WORKSPACE);
B
Benjamin Pasero 已提交
518
		}
519
	}
520

S
Sandeep Somavarapu 已提交
521 522 523 524 525 526 527 528 529
	private saveGlobalViewsStates(): void {
		const storedViewsVisibilityStates = PersistentContributableViewsModel.loadGlobalViewsState(this.globalViewsStateStorageId, this.storageService, StorageScope.GLOBAL);
		for (const viewDescriptor of this.viewDescriptors) {
			const viewState = this.viewStates.get(viewDescriptor.id);
			storedViewsVisibilityStates.set(viewDescriptor.id, {
				id: viewDescriptor.id,
				isHidden: viewState && viewDescriptor.canToggleVisibility ? !viewState.visibleGlobal : false,
				order: !viewDescriptor.workspace && viewState ? viewState.order : undefined
			});
S
Sandeep Somavarapu 已提交
530
		}
S
Sandeep Somavarapu 已提交
531
		this.storageService.store(this.globalViewsStateStorageId, JSON.stringify(values(storedViewsVisibilityStates)), StorageScope.GLOBAL);
S
Sandeep Somavarapu 已提交
532 533
	}

534

S
Sandeep Somavarapu 已提交
535
	private static loadViewsStates(workspaceViewsStateStorageId: string, globalViewsStateStorageId: string, storageService: IStorageService): Map<string, IViewState> {
536
		const viewStates = new Map<string, IViewState>();
537
		const workspaceViewsStates = <{ [id: string]: IStoredWorkspaceViewState; }>JSON.parse(storageService.get(workspaceViewsStateStorageId, StorageScope.WORKSPACE, '{}'));
S
Sandeep Somavarapu 已提交
538 539 540 541 542 543
		for (const id of Object.keys(workspaceViewsStates)) {
			const workspaceViewState = workspaceViewsStates[id];
			viewStates.set(id, {
				visibleGlobal: undefined,
				visibleWorkspace: isUndefined(workspaceViewState.isHidden) ? undefined : !workspaceViewState.isHidden,
				collapsed: workspaceViewState.collapsed,
S
Sandeep Somavarapu 已提交
544 545
				order: workspaceViewState.order,
				size: workspaceViewState.size
S
Sandeep Somavarapu 已提交
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
			});
		}

		// Migrate to `viewletStateStorageId`
		const workspaceVisibilityStates = this.loadGlobalViewsState(globalViewsStateStorageId, storageService, StorageScope.WORKSPACE);
		if (workspaceVisibilityStates.size > 0) {
			for (const { id, isHidden } of values(workspaceVisibilityStates)) {
				let viewState = viewStates.get(id);
				// Not migrated to `viewletStateStorageId`
				if (viewState) {
					if (isUndefined(viewState.visibleWorkspace)) {
						viewState.visibleWorkspace = !isHidden;
					}
				} else {
					viewStates.set(id, {
						collapsed: undefined,
						visibleGlobal: undefined,
						visibleWorkspace: !isHidden,
					});
				}
S
Sandeep Somavarapu 已提交
566
			}
S
Sandeep Somavarapu 已提交
567
			storageService.remove(globalViewsStateStorageId, StorageScope.WORKSPACE);
S
Sandeep Somavarapu 已提交
568
		}
S
Sandeep Somavarapu 已提交
569 570 571 572

		const globalViewsStates = this.loadGlobalViewsState(globalViewsStateStorageId, storageService, StorageScope.GLOBAL);
		for (const { id, isHidden, order } of values(globalViewsStates)) {
			let viewState = viewStates.get(id);
573
			if (viewState) {
S
Sandeep Somavarapu 已提交
574 575 576 577
				viewState.visibleGlobal = !isHidden;
				if (!isUndefined(order)) {
					viewState.order = order;
				}
S
Sandeep Somavarapu 已提交
578
			} else {
S
Sandeep Somavarapu 已提交
579 580 581 582 583 584
				viewStates.set(id, {
					visibleGlobal: !isHidden,
					order,
					collapsed: undefined,
					visibleWorkspace: undefined,
				});
585 586 587
			}
		}
		return viewStates;
588 589
	}

S
Sandeep Somavarapu 已提交
590 591
	private static loadGlobalViewsState(globalViewsStateStorageId: string, storageService: IStorageService, scope: StorageScope): Map<string, IStoredGlobalViewState> {
		const storedValue = <Array<string | IStoredGlobalViewState>>JSON.parse(storageService.get(globalViewsStateStorageId, scope, '[]'));
592
		let hasDuplicates = false;
S
Sandeep Somavarapu 已提交
593
		const storedGlobalViewsState = storedValue.reduce((result, storedState) => {
B
Benjamin Pasero 已提交
594
			if (typeof storedState === 'string' /* migration */) {
595
				hasDuplicates = hasDuplicates || result.has(storedState);
B
Benjamin Pasero 已提交
596 597
				result.set(storedState, { id: storedState, isHidden: true });
			} else {
598
				hasDuplicates = hasDuplicates || result.has(storedState.id);
B
Benjamin Pasero 已提交
599 600 601
				result.set(storedState.id, storedState);
			}
			return result;
S
Sandeep Somavarapu 已提交
602
		}, new Map<string, IStoredGlobalViewState>());
603 604

		if (hasDuplicates) {
S
Sandeep Somavarapu 已提交
605
			storageService.store(globalViewsStateStorageId, JSON.stringify(values(storedGlobalViewsState)), scope);
606 607
		}

S
Sandeep Somavarapu 已提交
608
		return storedGlobalViewsState;
S
Sandeep Somavarapu 已提交
609
	}
610
}
S
Sandeep Somavarapu 已提交
611

S
SteVen Batten 已提交
612
export class ViewsService extends Disposable implements IViewsService {
S
Sandeep Somavarapu 已提交
613

614
	_serviceBrand: undefined;
S
Sandeep Somavarapu 已提交
615

S
SteVen Batten 已提交
616
	private readonly viewContainersRegistry: IViewContainersRegistry;
617
	private readonly viewDisposable: Map<IViewDescriptor, IDisposable>;
S
SteVen Batten 已提交
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633

	constructor(
		@IViewDescriptorService private readonly viewDescriptorService: IViewDescriptorService,
		@IPanelService private readonly panelService: IPanelService,
		@IViewletService private readonly viewletService: IViewletService
	) {
		super();

		this.viewContainersRegistry = Registry.as<IViewContainersRegistry>(ViewExtensions.ViewContainersRegistry);
		this.viewDisposable = new Map<IViewDescriptor, IDisposable>();

		this._register(toDisposable(() => {
			this.viewDisposable.forEach(disposable => disposable.dispose());
			this.viewDisposable.clear();
		}));

S
Sandeep Somavarapu 已提交
634 635 636 637 638 639 640 641 642 643 644
		this.viewContainersRegistry.all.forEach(viewContainer => this.onViewContainerRegistered(viewContainer));
		this._register(this.viewContainersRegistry.onDidRegister(({ viewContainer }) => this.onViewContainerRegistered(viewContainer)));
	}

	private onViewContainerRegistered(viewContainer: ViewContainer): void {
		const viewDescriptorCollection = this.viewDescriptorService.getViewDescriptors(viewContainer);
		this.onViewsRegistered(viewDescriptorCollection.allViewDescriptors, viewContainer);
		this._register(viewDescriptorCollection.onDidChangeViews(({ added, removed }) => {
			this.onViewsRegistered(added, viewContainer);
			this.onViewsDeregistered(removed, viewContainer);
		}));
S
SteVen Batten 已提交
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
	}

	private onViewsRegistered(views: IViewDescriptor[], container: ViewContainer): void {
		const location = this.viewContainersRegistry.getViewContainerLocation(container);
		if (location === undefined) {
			return;
		}

		const composite = this.getComposite(container.id, location);
		for (const viewDescriptor of views) {
			const disposables = new DisposableStore();
			const command: ICommandAction = {
				id: viewDescriptor.focusCommand ? viewDescriptor.focusCommand.id : `${viewDescriptor.id}.focus`,
				title: { original: `Focus on ${viewDescriptor.name} View`, value: localize('focus view', "Focus on {0} View", viewDescriptor.name) },
				category: composite ? composite.name : localize('view category', "View"),
			};
			const when = ContextKeyExpr.has(`${viewDescriptor.id}.active`);

			disposables.add(CommandsRegistry.registerCommand(command.id, () => this.openView(viewDescriptor.id, true)));

			disposables.add(MenuRegistry.appendMenuItem(MenuId.CommandPalette, {
				command,
				when
			}));

			if (viewDescriptor.focusCommand && viewDescriptor.focusCommand.keybindings) {
				KeybindingsRegistry.registerKeybindingRule({
					id: command.id,
					when,
					weight: KeybindingWeight.WorkbenchContrib,
					primary: viewDescriptor.focusCommand.keybindings.primary,
					secondary: viewDescriptor.focusCommand.keybindings.secondary,
					linux: viewDescriptor.focusCommand.keybindings.linux,
					mac: viewDescriptor.focusCommand.keybindings.mac,
					win: viewDescriptor.focusCommand.keybindings.win
				});
			}

			this.viewDisposable.set(viewDescriptor, disposables);
		}
	}

	private onViewsDeregistered(views: IViewDescriptor[], container: ViewContainer): void {
		for (const view of views) {
			const disposable = this.viewDisposable.get(view);
			if (disposable) {
				disposable.dispose();
				this.viewDisposable.delete(view);
			}
		}
	}

	private async openComposite(compositeId: string, location: ViewContainerLocation, focus?: boolean): Promise<IPaneComposite | undefined> {
		if (location === ViewContainerLocation.Sidebar) {
			return this.viewletService.openViewlet(compositeId, focus);
		} else if (location === ViewContainerLocation.Panel) {
			return this.panelService.openPanel(compositeId, focus) as IPaneComposite;
		}
		return undefined;
	}

	private getComposite(compositeId: string, location: ViewContainerLocation): { id: string, name: string } | undefined {
		if (location === ViewContainerLocation.Sidebar) {
			return this.viewletService.getViewlet(compositeId);
		} else if (location === ViewContainerLocation.Panel) {
			return this.panelService.getPanel(compositeId);
		}

		return undefined;
	}

	async openView(id: string, focus: boolean): Promise<IView | null> {
		const viewContainer = this.viewDescriptorService.getViewContainer(id);
		if (viewContainer) {
			const location = this.viewContainersRegistry.getViewContainerLocation(viewContainer);
			const compositeDescriptor = this.getComposite(viewContainer.id, location!);
			if (compositeDescriptor) {
				const paneComposite = await this.openComposite(compositeDescriptor.id, location!, focus) as IPaneComposite | undefined;
				if (paneComposite && paneComposite.openView) {
					return paneComposite.openView(id, focus);
				}
			}
		}

		return null;
	}
}

export class ViewDescriptorService extends Disposable implements IViewDescriptorService {

	_serviceBrand: undefined;

	private readonly _onViewsRegistered: Emitter<{ views: IViewDescriptor[], viewContainer: ViewContainer }> = this._register(new Emitter<{ views: IViewDescriptor[], viewContainer: ViewContainer }>());
	readonly onViewsRegistered: Event<{ views: IViewDescriptor[], viewContainer: ViewContainer }> = this._onViewsRegistered.event;

	private readonly _onViewsDeregistered: Emitter<{ views: IViewDescriptor[], viewContainer: ViewContainer }> = this._register(new Emitter<{ views: IViewDescriptor[], viewContainer: ViewContainer }>());
	readonly onViewsDeregistered: Event<{ views: IViewDescriptor[], viewContainer: ViewContainer }> = this._onViewsDeregistered.event;

	private readonly _onDidChangeContainer: Emitter<{ views: IViewDescriptor[], from: ViewContainer, to: ViewContainer }> = this._register(new Emitter<{ views: IViewDescriptor[], from: ViewContainer, to: ViewContainer }>());
	readonly onDidChangeContainer: Event<{ views: IViewDescriptor[], from: ViewContainer, to: ViewContainer }> = this._onDidChangeContainer.event;

	private readonly viewDescriptorCollections: Map<ViewContainer, { viewDescriptorCollection: IViewDescriptorCollection, disposable: IDisposable; }>;
	private readonly viewContainers: Map<string, ViewContainer>;
S
Sandeep Somavarapu 已提交
748
	private readonly activeViewContextKeys: Map<string, IContextKey<boolean>>;
749

S
SteVen Batten 已提交
750 751 752
	private readonly viewsRegistry: IViewsRegistry;
	private readonly viewContainersRegistry: IViewContainersRegistry;

S
Sandeep Somavarapu 已提交
753
	constructor(
754
		@IContextKeyService private readonly contextKeyService: IContextKeyService
S
Sandeep Somavarapu 已提交
755
	) {
756
		super();
S
Sandeep Somavarapu 已提交
757

758
		this.viewDescriptorCollections = new Map<ViewContainer, { viewDescriptorCollection: IViewDescriptorCollection, disposable: IDisposable; }>();
S
SteVen Batten 已提交
759
		this.viewContainers = new Map<string, ViewContainer>();
S
Sandeep Somavarapu 已提交
760 761
		this.activeViewContextKeys = new Map<string, IContextKey<boolean>>();

S
SteVen Batten 已提交
762 763 764 765
		this.viewContainersRegistry = Registry.as<IViewContainersRegistry>(ViewExtensions.ViewContainersRegistry);
		this.viewsRegistry = Registry.as<IViewsRegistry>(ViewExtensions.ViewsRegistry);
		this.viewContainersRegistry.all.forEach(viewContainer => {
			this.onDidRegisterViews(viewContainer, this.viewsRegistry.getViews(viewContainer));
766 767
			this.onDidRegisterViewContainer(viewContainer);
		});
S
SteVen Batten 已提交
768 769 770 771 772 773
		this._register(this.viewsRegistry.onViewsRegistered(({ views, viewContainer }) => this.onDidRegisterViews(viewContainer, views)));
		this._register(this.viewsRegistry.onViewsDeregistered(({ views, viewContainer }) => this.onDidDeregisterViews(viewContainer, views)));
		this._register(this.viewsRegistry.onDidChangeContainer(({ views, from, to }) => { this.onDidDeregisterViews(from, views); this.onDidRegisterViews(to, views); this._onDidChangeContainer.fire({ views, from, to }); }));

		this._register(this.viewContainersRegistry.onDidRegister(({ viewContainer }) => this.onDidRegisterViewContainer(viewContainer)));
		this._register(this.viewContainersRegistry.onDidDeregister(({ viewContainer }) => this.onDidDeregisterViewContainer(viewContainer)));
S
Sandeep Somavarapu 已提交
774 775 776 777
		this._register(toDisposable(() => {
			this.viewDescriptorCollections.forEach(({ disposable }) => disposable.dispose());
			this.viewDescriptorCollections.clear();
		}));
S
Sandeep Somavarapu 已提交
778 779
	}

S
SteVen Batten 已提交
780 781 782 783
	getViewContainer(viewId: string): ViewContainer | null {
		return this.viewContainers.get(viewId) ?? null;
	}

S
Sandeep Somavarapu 已提交
784 785 786 787 788 789
	getViewDescriptors(container: ViewContainer): IViewDescriptorCollection {
		let viewDescriptorCollectionItem = this.viewDescriptorCollections.get(container);
		if (!viewDescriptorCollectionItem) {
			// Create and register the collection if does not exist
			this.onDidRegisterViewContainer(container);
			viewDescriptorCollectionItem = this.viewDescriptorCollections.get(container);
S
Sandeep Somavarapu 已提交
790
		}
S
Sandeep Somavarapu 已提交
791
		return viewDescriptorCollectionItem!.viewDescriptorCollection;
792 793
	}

S
SteVen Batten 已提交
794 795 796
	moveViews(views: IViewDescriptor[], viewContainer: ViewContainer): void {
		if (!views.length) {
			return;
S
Sandeep Somavarapu 已提交
797
		}
798

S
SteVen Batten 已提交
799 800 801 802 803 804 805 806 807 808
		const from = this.viewContainers.get(views[0].id);
		const to = viewContainer;

		if (from && to && from !== to) {
			this.onDidDeregisterViews(from, views);
			this.onDidRegisterViews(viewContainer, views);
			this._onDidChangeContainer.fire({ views, from, to });
		}
	}

S
Sandeep Somavarapu 已提交
809
	private onDidRegisterViewContainer(viewContainer: ViewContainer): void {
810
		const disposables = new DisposableStore();
S
Sandeep Somavarapu 已提交
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
		const viewDescriptorCollection = disposables.add(new ViewDescriptorCollection(this.contextKeyService));
		viewDescriptorCollection.addViews(this.viewsRegistry.getViews(viewContainer));

		const onRelevantViewsRegistered = filterViewRegisterEvent(viewContainer, this.onViewsRegistered);
		onRelevantViewsRegistered(viewDescriptors => viewDescriptorCollection.addViews(viewDescriptors), this, disposables);

		const onRelevantViewsMoved = filterViewMoveEvent(viewContainer, this.onDidChangeContainer);
		onRelevantViewsMoved(({ added, removed }) => {
			if (isNonEmptyArray(added)) {
				viewDescriptorCollection.addViews(added);
			}
			if (isNonEmptyArray(removed)) {
				viewDescriptorCollection.removeViews(removed);
			}
		}, this, disposables);

		const onRelevantViewsDeregistered = filterViewRegisterEvent(viewContainer, this.onViewsDeregistered);
		onRelevantViewsDeregistered(viewDescriptors => viewDescriptorCollection.removeViews(viewDescriptors), this, disposables);
S
Sandeep Somavarapu 已提交
829 830

		this.onDidChangeActiveViews({ added: viewDescriptorCollection.activeViewDescriptors, removed: [] });
S
Sandeep Somavarapu 已提交
831
		viewDescriptorCollection.onDidChangeActiveViews(changed => this.onDidChangeActiveViews(changed), this, disposables);
S
Sandeep Somavarapu 已提交
832

833
		this.viewDescriptorCollections.set(viewContainer, { viewDescriptorCollection, disposable: disposables });
S
Sandeep Somavarapu 已提交
834 835 836 837 838 839 840 841
	}

	private onDidDeregisterViewContainer(viewContainer: ViewContainer): void {
		const viewDescriptorCollectionItem = this.viewDescriptorCollections.get(viewContainer);
		if (viewDescriptorCollectionItem) {
			viewDescriptorCollectionItem.disposable.dispose();
			this.viewDescriptorCollections.delete(viewContainer);
		}
S
Sandeep Somavarapu 已提交
842 843
	}

844
	private onDidChangeActiveViews({ added, removed }: { added: IViewDescriptor[], removed: IViewDescriptor[]; }): void {
S
Sandeep Somavarapu 已提交
845 846 847 848
		added.forEach(viewDescriptor => this.getOrCreateActiveViewContextKey(viewDescriptor).set(true));
		removed.forEach(viewDescriptor => this.getOrCreateActiveViewContextKey(viewDescriptor).set(false));
	}

849
	private onDidRegisterViews(container: ViewContainer, views: IViewDescriptor[]): void {
S
SteVen Batten 已提交
850 851 852 853
		const location = this.viewContainersRegistry.getViewContainerLocation(container);
		if (location === undefined) {
			return;
		}
854

S
SteVen Batten 已提交
855 856
		for (const viewDescriptor of views) {
			this.viewContainers.set(viewDescriptor.id, container);
857
		}
S
SteVen Batten 已提交
858 859

		this._onViewsRegistered.fire({ views, viewContainer: container });
860 861
	}

S
SteVen Batten 已提交
862
	private onDidDeregisterViews(container: ViewContainer, views: IViewDescriptor[]): void {
863
		for (const view of views) {
S
SteVen Batten 已提交
864
			this.viewContainers.delete(view.id);
S
Sandeep Somavarapu 已提交
865
		}
S
SteVen Batten 已提交
866 867

		this._onViewsDeregistered.fire({ views, viewContainer: container });
S
Sandeep Somavarapu 已提交
868 869 870 871 872 873 874 875 876 877 878
	}

	private getOrCreateActiveViewContextKey(viewDescriptor: IViewDescriptor): IContextKey<boolean> {
		const activeContextKeyId = `${viewDescriptor.id}.active`;
		let contextKey = this.activeViewContextKeys.get(activeContextKeyId);
		if (!contextKey) {
			contextKey = new RawContextKey(activeContextKeyId, false).bindTo(this.contextKeyService);
			this.activeViewContextKeys.set(activeContextKeyId, contextKey);
		}
		return contextKey;
	}
879
}
J
Joao Moreno 已提交
880 881 882 883 884 885 886 887 888 889 890 891

export function createFileIconThemableTreeContainerScope(container: HTMLElement, themeService: IWorkbenchThemeService): IDisposable {
	addClass(container, 'file-icon-themable-tree');
	addClass(container, 'show-file-icons');

	const onDidChangeFileIconTheme = (theme: IFileIconTheme) => {
		toggleClass(container, 'align-icons-and-twisties', theme.hasFileIcons && !theme.hasFolderIcons);
		toggleClass(container, 'hide-arrows', theme.hidesExplorerArrows === true);
	};

	onDidChangeFileIconTheme(themeService.getFileIconTheme());
	return themeService.onDidFileIconThemeChange(onDidChangeFileIconTheme);
892 893
}

S
SteVen Batten 已提交
894
registerSingleton(IViewDescriptorService, ViewDescriptorService);
S
SteVen Batten 已提交
895
registerSingleton(IViewsService, ViewsService);