viewDescriptorService.ts 26.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import { ViewContainerLocation, IViewDescriptorService, ViewContainer, IViewsRegistry, IViewContainersRegistry, IViewDescriptor, Extensions as ViewExtensions, IViewDescriptorCollection } from 'vs/workbench/common/views';
import { IContextKey, RawContextKey, IContextKeyService, IReadableSet, IContextKeyChangeEvent } from 'vs/platform/contextkey/common/contextkey';
import { IStorageService, StorageScope, IWorkspaceStorageChangeEvent } from 'vs/platform/storage/common/storage';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { Registry } from 'vs/platform/registry/common/platform';
import { toDisposable, DisposableStore, Disposable, IDisposable } from 'vs/base/common/lifecycle';
import { ViewPaneContainer } from 'vs/workbench/browser/parts/views/viewPaneContainer';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { Event, Emitter } from 'vs/base/common/event';
import { firstIndex } from 'vs/base/common/arrays';
S
Sandeep Somavarapu 已提交
17
import { IStorageKeysSyncRegistryService } from 'vs/platform/userDataSync/common/storageKeys';
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 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 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184

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;
}

class ViewDescriptorCollection extends Disposable implements IViewDescriptorCollection {

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

	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;

	get activeViewDescriptors(): IViewDescriptor[] {
		return this.items
			.filter(i => i.active)
			.map(i => i.viewDescriptor);
	}

	get allViewDescriptors(): IViewDescriptor[] {
		return this.items.map(i => i.viewDescriptor);
	}

	constructor(
		@IContextKeyService private readonly contextKeyService: IContextKeyService,
	) {
		super();
		this._register(Event.filter(contextKeyService.onDidChangeContext, e => e.affectsSome(this.contextKeys))(this.onContextChanged, this));
	}

	addViews(viewDescriptors: IViewDescriptor[]): void {
		const added: IViewDescriptor[] = [];

		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) {
				added.push(viewDescriptor);
			}
		}

		this._onDidChangeViews.fire({ added: viewDescriptors, removed: [] });

		if (added.length) {
			this._onDidChangeActiveViews.fire({ added, removed: [] });
		}
	}

	removeViews(viewDescriptors: IViewDescriptor[]): void {
		const removed: IViewDescriptor[] = [];

		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) {
				removed.push(viewDescriptor);
			}
		}

		this._onDidChangeViews.fire({ added: [], removed: viewDescriptors });

		if (removed.length) {
			this._onDidChangeActiveViews.fire({ added: [], removed });
		}
	}

	private onContextChanged(event: IContextKeyChangeEvent): void {
		const removed: IViewDescriptor[] = [];
		const added: IViewDescriptor[] = [];

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

			if (item.active !== active) {
				if (active) {
					added.push(item.viewDescriptor);
				} else {
					removed.push(item.viewDescriptor);
				}
			}

			item.active = active;
		}

		if (added.length || removed.length) {
			this._onDidChangeActiveViews.fire({ added, removed });
		}
	}

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

interface ICachedViewContainerInfo {
	containerId: string;
	location?: ViewContainerLocation;
	sourceViewId?: string;
}

export class ViewDescriptorService extends Disposable implements IViewDescriptorService {

	_serviceBrand: undefined;

	private static readonly CACHED_VIEW_POSITIONS = 'views.cachedViewPositions';
	private static readonly COMMON_CONTAINER_ID_PREFIX = 'workbench.views.service';

S
SteVen Batten 已提交
185 186 187
	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;

188 189 190
	private readonly _onDidChangeLocation: Emitter<{ views: IViewDescriptor[], from: ViewContainerLocation, to: ViewContainerLocation }> = this._register(new Emitter<{ views: IViewDescriptor[], from: ViewContainerLocation, to: ViewContainerLocation }>());
	readonly onDidChangeLocation: Event<{ views: IViewDescriptor[], from: ViewContainerLocation, to: ViewContainerLocation }> = this._onDidChangeLocation.event;

191 192
	private readonly viewDescriptorCollections: Map<ViewContainer, { viewDescriptorCollection: ViewDescriptorCollection, disposable: IDisposable; }>;
	private readonly activeViewContextKeys: Map<string, IContextKey<boolean>>;
193
	private readonly movableViewContextKeys: Map<string, IContextKey<boolean>>;
S
SteVen Batten 已提交
194
	private readonly defaultViewLocationContextKeys: Map<string, IContextKey<boolean>>;
195 196 197 198 199

	private readonly viewsRegistry: IViewsRegistry;
	private readonly viewContainersRegistry: IViewContainersRegistry;

	private cachedViewInfo: Map<string, ICachedViewContainerInfo>;
200
	private generatedContainerSourceViewIds: Map<string, string>;
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220

	private _cachedViewPositionsValue: string | undefined;
	private get cachedViewPositionsValue(): string {
		if (!this._cachedViewPositionsValue) {
			this._cachedViewPositionsValue = this.getStoredCachedViewPositionsValue();
		}

		return this._cachedViewPositionsValue;
	}

	private set cachedViewPositionsValue(value: string) {
		if (this.cachedViewPositionsValue !== value) {
			this._cachedViewPositionsValue = value;
			this.setStoredCachedViewPositionsValue(value);
		}
	}

	constructor(
		@IContextKeyService private readonly contextKeyService: IContextKeyService,
		@IStorageService private readonly storageService: IStorageService,
S
Sandeep Somavarapu 已提交
221 222
		@IExtensionService private readonly extensionService: IExtensionService,
		@IStorageKeysSyncRegistryService storageKeysSyncRegistryService: IStorageKeysSyncRegistryService
223 224 225
	) {
		super();

S
Sandeep Somavarapu 已提交
226
		storageKeysSyncRegistryService.registerStorageKey({ key: ViewDescriptorService.CACHED_VIEW_POSITIONS, version: 1 });
227 228
		this.viewDescriptorCollections = new Map<ViewContainer, { viewDescriptorCollection: ViewDescriptorCollection, disposable: IDisposable; }>();
		this.activeViewContextKeys = new Map<string, IContextKey<boolean>>();
229
		this.movableViewContextKeys = new Map<string, IContextKey<boolean>>();
S
SteVen Batten 已提交
230
		this.defaultViewLocationContextKeys = new Map<string, IContextKey<boolean>>();
231 232 233

		this.viewContainersRegistry = Registry.as<IViewContainersRegistry>(ViewExtensions.ViewContainersRegistry);
		this.viewsRegistry = Registry.as<IViewsRegistry>(ViewExtensions.ViewsRegistry);
234
		this.generatedContainerSourceViewIds = new Map<string, string>();
235 236 237 238 239 240

		this.cachedViewInfo = this.getCachedViewPositions();

		// Register all containers that were registered before this ctor
		this.viewContainersRegistry.all.forEach(viewContainer => this.onDidRegisterViewContainer(viewContainer));

S
SteVen Batten 已提交
241 242 243
		// Try generating all generated containers that don't need extensions
		this.tryGenerateContainers();

244 245 246
		this._register(this.viewsRegistry.onViewsRegistered(({ views, viewContainer }) => this.onDidRegisterViews(views, viewContainer)));
		this._register(this.viewsRegistry.onViewsDeregistered(({ views, viewContainer }) => this.onDidDeregisterViews(views, viewContainer)));

S
Sandeep Somavarapu 已提交
247
		this._register(this.viewsRegistry.onDidChangeContainer(({ views, from, to }) => this.moveViews(views, from, to)));
248 249 250 251 252 253 254 255 256 257 258 259 260

		this._register(this.viewContainersRegistry.onDidRegister(({ viewContainer }) => this.onDidRegisterViewContainer(viewContainer)));
		this._register(this.viewContainersRegistry.onDidDeregister(({ viewContainer }) => this.onDidDeregisterViewContainer(viewContainer)));
		this._register(toDisposable(() => {
			this.viewDescriptorCollections.forEach(({ disposable }) => disposable.dispose());
			this.viewDescriptorCollections.clear();
		}));

		this._register(this.storageService.onDidChangeStorage((e) => { this.onDidStorageChange(e); }));

		this._register(this.extensionService.onDidRegisterExtensions(() => this.onDidRegisterExtensions()));
	}

S
SteVen Batten 已提交
261
	private registerGroupedViews(groupedViews: Map<string, { cachedContainerInfo?: ICachedViewContainerInfo, views: IViewDescriptor[] }>): void {
262
		// Register views that have already been registered to their correct view containers
S
SteVen Batten 已提交
263 264 265
		for (const containerId of groupedViews.keys()) {
			const viewContainer = this.viewContainersRegistry.get(containerId);
			const containerData = groupedViews.get(containerId)!;
266 267 268

			// The container has not been registered yet
			if (!viewContainer || !this.viewDescriptorCollections.has(viewContainer)) {
S
SteVen Batten 已提交
269 270 271 272 273 274 275 276 277
				if (containerData.cachedContainerInfo && this.shouldGenerateContainer(containerData.cachedContainerInfo)) {
					const containerInfo = containerData.cachedContainerInfo;

					const sourceViewDescriptor = this.viewsRegistry.getView(containerInfo.sourceViewId!);
					if (sourceViewDescriptor && !this.viewContainersRegistry.get(containerId)) {
						this.registerViewContainerForSingleView(sourceViewDescriptor, containerInfo.location!);
					}
				}

278 279 280
				continue;
			}

S
SteVen Batten 已提交
281
			this.addViews(viewContainer, containerData.views);
282 283 284
		}
	}

S
SteVen Batten 已提交
285
	private deregisterGroupedViews(groupedViews: Map<string, { cachedContainerInfo?: ICachedViewContainerInfo, views: IViewDescriptor[] }>): void {
286 287 288 289 290 291 292 293 294
		// Register views that have already been registered to their correct view containers
		for (const viewContainerId of groupedViews.keys()) {
			const viewContainer = this.viewContainersRegistry.get(viewContainerId);

			// The container has not been registered yet
			if (!viewContainer || !this.viewDescriptorCollections.has(viewContainer)) {
				continue;
			}

S
SteVen Batten 已提交
295
			this.removeViews(viewContainer, groupedViews.get(viewContainerId)!.views);
296 297 298
		}
	}

S
SteVen Batten 已提交
299
	private tryGenerateContainers(fallbackToDefault?: boolean): void {
300 301
		for (const [viewId, containerInfo] of this.cachedViewInfo.entries()) {
			const containerId = containerInfo.containerId;
S
SteVen Batten 已提交
302

303 304 305 306 307 308
			// check if cached view container is registered
			if (this.viewContainersRegistry.get(containerId)) {
				continue;
			}

			// check if we should generate this container
S
SteVen Batten 已提交
309 310
			if (this.shouldGenerateContainer(containerInfo)) {
				const sourceView = this.getViewDescriptor(containerInfo.sourceViewId!);
311 312

				if (sourceView) {
S
SteVen Batten 已提交
313
					this.registerViewContainerForSingleView(sourceView, containerInfo.location!);
314 315 316 317
					continue;
				}
			}

S
SteVen Batten 已提交
318 319 320 321 322 323
			if (fallbackToDefault) {
				// check if view has been registered to default location
				const viewContainer = this.viewsRegistry.getViewContainer(viewId);
				const viewDescriptor = this.getViewDescriptor(viewId);
				if (viewContainer && viewDescriptor) {
					this.addViews(viewContainer, [viewDescriptor]);
324

S
SteVen Batten 已提交
325 326 327 328
					const newLocation = this.getViewContainerLocation(viewContainer);
					if (containerInfo.location && containerInfo.location !== newLocation) {
						this._onDidChangeLocation.fire({ views: [viewDescriptor], from: containerInfo.location, to: newLocation });
					}
329
				}
330 331 332
			}
		}

S
SteVen Batten 已提交
333 334 335 336 337 338 339
		if (fallbackToDefault) {
			this.saveViewPositionsToCache();
		}
	}

	private onDidRegisterExtensions(): void {
		this.tryGenerateContainers(true);
340 341 342 343 344 345 346 347
	}

	private onDidRegisterViews(views: IViewDescriptor[], viewContainer: ViewContainer): void {
		// When views are registered, we need to regroup them based on the cache
		const regroupedViews = this.regroupViews(viewContainer.id, views);

		// Once they are grouped, try registering them which occurs
		// if the container has already been registered within this service
S
SteVen Batten 已提交
348
		// or we can generate the container from the source view id
349
		this.registerGroupedViews(regroupedViews);
350 351

		views.forEach(viewDescriptor => this.getOrCreateMovableViewContextKey(viewDescriptor).set(!!viewDescriptor.canMoveView));
352 353
	}

S
SteVen Batten 已提交
354
	private shouldGenerateContainer(containerInfo: ICachedViewContainerInfo): boolean {
S
SteVen Batten 已提交
355
		return !!containerInfo.sourceViewId && containerInfo.location !== undefined;
S
SteVen Batten 已提交
356 357
	}

358 359 360 361
	private onDidDeregisterViews(views: IViewDescriptor[], viewContainer: ViewContainer): void {
		// When views are registered, we need to regroup them based on the cache
		const regroupedViews = this.regroupViews(viewContainer.id, views);
		this.deregisterGroupedViews(regroupedViews);
362
		views.forEach(viewDescriptor => this.getOrCreateMovableViewContextKey(viewDescriptor).set(false));
363 364
	}

S
SteVen Batten 已提交
365 366
	private regroupViews(containerId: string, views: IViewDescriptor[]): Map<string, { cachedContainerInfo?: ICachedViewContainerInfo, views: IViewDescriptor[] }> {
		const ret = new Map<string, { cachedContainerInfo?: ICachedViewContainerInfo, views: IViewDescriptor[] }>();
367 368

		views.forEach(viewDescriptor => {
S
SteVen Batten 已提交
369 370
			const containerInfo = this.cachedViewInfo.get(viewDescriptor.id);
			const correctContainerId = containerInfo?.containerId || containerId;
371

S
SteVen Batten 已提交
372 373 374
			const containerData = ret.get(correctContainerId) || { cachedContainerInfo: containerInfo, views: [] };
			containerData.views.push(viewDescriptor);
			ret.set(correctContainerId, containerData);
375 376 377 378 379
		});

		return ret;
	}

380 381 382 383
	getViewDescriptor(viewId: string): IViewDescriptor | null {
		return this.viewsRegistry.getView(viewId);
	}

384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
	getViewLocation(viewId: string): ViewContainerLocation | null {
		const cachedInfo = this.cachedViewInfo.get(viewId);

		if (cachedInfo && cachedInfo.location) {
			return cachedInfo.location;
		}

		const container = cachedInfo?.containerId ?
			this.viewContainersRegistry.get(cachedInfo.containerId) ?? null :
			this.viewsRegistry.getViewContainer(viewId);

		if (!container) {
			return null;
		}

S
Sandeep Somavarapu 已提交
399
		return this.getViewContainerLocation(container);
400 401
	}

402 403
	getViewContainer(viewId: string): ViewContainer | null {
		const containerId = this.cachedViewInfo.get(viewId)?.containerId;
S
SteVen Batten 已提交
404

405 406 407 408 409
		return containerId ?
			this.viewContainersRegistry.get(containerId) ?? null :
			this.viewsRegistry.getViewContainer(viewId);
	}

S
Sandeep Somavarapu 已提交
410 411 412 413
	getViewContainerLocation(viewContainer: ViewContainer): ViewContainerLocation {
		return this.viewContainersRegistry.getViewContainerLocation(viewContainer);
	}

414 415 416 417 418 419 420 421
	getDefaultContainer(viewId: string): ViewContainer | null {
		return this.viewsRegistry.getViewContainer(viewId) ?? null;
	}

	getViewDescriptors(container: ViewContainer): ViewDescriptorCollection {
		return this.getOrRegisterViewDescriptorCollection(container);
	}

S
SteVen Batten 已提交
422
	moveViewToLocation(view: IViewDescriptor, location: ViewContainerLocation): void {
S
SteVen Batten 已提交
423
		let container = this.registerViewContainerForSingleView(view, location);
S
SteVen Batten 已提交
424
		this.moveViewsToContainer([view], container);
425 426
	}

S
SteVen Batten 已提交
427
	moveViewsToContainer(views: IViewDescriptor[], viewContainer: ViewContainer): void {
428 429 430 431 432 433 434 435
		if (!views.length) {
			return;
		}

		const from = this.getViewContainer(views[0].id);
		const to = viewContainer;

		if (from && to && from !== to) {
S
Sandeep Somavarapu 已提交
436 437 438
			this.moveViews(views, from, to);
		}
	}
439

S
SteVen Batten 已提交
440
	private moveViews(views: IViewDescriptor[], from: ViewContainer, to: ViewContainer, skipCacheUpdate?: boolean): void {
S
Sandeep Somavarapu 已提交
441 442
		this.removeViews(from, views);
		this.addViews(to, views);
443

S
Sandeep Somavarapu 已提交
444 445
		const oldLocation = this.getViewContainerLocation(from);
		const newLocation = this.getViewContainerLocation(to);
446

S
Sandeep Somavarapu 已提交
447 448
		if (oldLocation !== newLocation) {
			this._onDidChangeLocation.fire({ views, from: oldLocation, to: newLocation });
449
		}
S
Sandeep Somavarapu 已提交
450 451

		this._onDidChangeContainer.fire({ views, from, to });
S
SteVen Batten 已提交
452 453 454 455

		if (!skipCacheUpdate) {
			this.saveViewPositionsToCache();
		}
456 457 458 459 460 461 462
	}

	private registerViewContainerForSingleView(sourceView: IViewDescriptor, location: ViewContainerLocation): ViewContainer {
		const id = this.generateContainerIdFromSourceViewId(sourceView.id, location);

		return this.viewContainersRegistry.registerViewContainer({
			id,
S
SteVen Batten 已提交
463
			ctorDescriptor: new SyncDescriptor(ViewPaneContainer, [id, `${id}.state`, { mergeViewWithContainerWhenSingleView: true }]),
464
			name: sourceView.name,
S
SteVen Batten 已提交
465
			icon: location === ViewContainerLocation.Sidebar ? sourceView.containerIcon || 'codicon-window' : undefined,
466 467 468 469 470
			hideIfEmpty: true
		}, location);
	}

	private getCachedViewPositions(): Map<string, ICachedViewContainerInfo> {
S
SteVen Batten 已提交
471 472 473 474 475 476 477 478 479 480
		const result = new Map<string, ICachedViewContainerInfo>(JSON.parse(this.cachedViewPositionsValue));

		// Sanitize cache
		for (const [viewId, containerInfo] of result.entries()) {
			if (!containerInfo) {
				result.delete(viewId);
			}
		}

		return result;
481 482 483 484 485 486 487 488 489 490
	}

	private onDidStorageChange(e: IWorkspaceStorageChangeEvent): void {
		if (e.key === ViewDescriptorService.CACHED_VIEW_POSITIONS && e.scope === StorageScope.GLOBAL
			&& this.cachedViewPositionsValue !== this.getStoredCachedViewPositionsValue() /* This checks if current window changed the value or not */) {
			this._cachedViewPositionsValue = this.getStoredCachedViewPositionsValue();

			const newCachedPositions = this.getCachedViewPositions();

			for (let viewId of newCachedPositions.keys()) {
S
SteVen Batten 已提交
491 492 493 494 495
				const viewDescriptor = this.getViewDescriptor(viewId);
				if (!viewDescriptor) {
					continue;
				}

496
				const prevViewContainer = this.getViewContainer(viewId);
S
SteVen Batten 已提交
497 498 499 500 501 502 503 504 505 506 507 508
				const newViewContainerInfo = newCachedPositions.get(viewId)!;
				// Verify if we need to create the destination container
				if (newViewContainerInfo.sourceViewId) {
					const sourceViewDescriptor = this.getViewDescriptor(newViewContainerInfo.sourceViewId);

					if (!this.viewContainersRegistry.get(newViewContainerInfo.containerId) && sourceViewDescriptor) {
						this.registerViewContainerForSingleView(sourceViewDescriptor, newViewContainerInfo.location!);
					}
				}

				// Try moving to the new container
				const newViewContainer = this.viewContainersRegistry.get(newViewContainerInfo.containerId);
509
				if (prevViewContainer && newViewContainer && newViewContainer !== prevViewContainer) {
510
					const viewDescriptor = this.getViewDescriptor(viewId);
511
					if (viewDescriptor) {
S
SteVen Batten 已提交
512
						this.moveViews([viewDescriptor], prevViewContainer, newViewContainer);
513 514 515 516
					}
				}
			}

517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
			// If a value is not present in the cache, it must be reset to default
			this.viewContainersRegistry.all.forEach(viewContainer => {
				const viewDescriptorCollection = this.getViewDescriptors(viewContainer);
				viewDescriptorCollection.allViewDescriptors.forEach(viewDescriptor => {
					if (!newCachedPositions.has(viewDescriptor.id)) {
						const currentContainer = this.getViewContainer(viewDescriptor.id);
						const defaultContainer = this.getDefaultContainer(viewDescriptor.id);
						if (currentContainer && defaultContainer && currentContainer !== defaultContainer) {
							this.moveViews([viewDescriptor], currentContainer, defaultContainer);
						}

						this.cachedViewInfo.delete(viewDescriptor.id);
					}
				});
			});

533 534 535 536 537 538 539
			this.cachedViewInfo = this.getCachedViewPositions();
		}
	}

	// Generated Container Id Format
	// {Common Prefix}.{Uniqueness Id}.{Source View Id}
	private generateContainerIdFromSourceViewId(viewId: string, location: ViewContainerLocation): string {
540 541 542
		const result = `${ViewDescriptorService.COMMON_CONTAINER_ID_PREFIX}.${location === ViewContainerLocation.Panel ? 'panel' : 'sidebar'}.${viewId}`;
		this.generatedContainerSourceViewIds.set(result, viewId);
		return result;
543 544 545 546 547 548 549 550 551 552 553 554 555 556
	}

	private getStoredCachedViewPositionsValue(): string {
		return this.storageService.get(ViewDescriptorService.CACHED_VIEW_POSITIONS, StorageScope.GLOBAL, '[]');
	}

	private setStoredCachedViewPositionsValue(value: string): void {
		this.storageService.store(ViewDescriptorService.CACHED_VIEW_POSITIONS, value, StorageScope.GLOBAL);
	}

	private saveViewPositionsToCache(): void {
		this.viewContainersRegistry.all.forEach(viewContainer => {
			const viewDescriptorCollection = this.getViewDescriptors(viewContainer);
			viewDescriptorCollection.allViewDescriptors.forEach(viewDescriptor => {
557
				const sourceViewId = this.generatedContainerSourceViewIds.get(viewContainer.id);
S
Sandeep Somavarapu 已提交
558
				const containerLocation = this.getViewContainerLocation(viewContainer);
559 560 561 562 563 564 565 566
				this.cachedViewInfo.set(viewDescriptor.id, {
					containerId: viewContainer.id,
					location: containerLocation,
					sourceViewId: sourceViewId
				});
			});
		});

567 568 569 570 571 572 573 574 575 576
		// Do no save default positions to the cache
		// so that default changes can be recognized
		// https://github.com/microsoft/vscode/issues/90414
		for (const [viewId, containerInfo] of this.cachedViewInfo) {
			const defaultContainer = this.getDefaultContainer(viewId);
			if (defaultContainer?.id === containerInfo.containerId) {
				this.cachedViewInfo.delete(viewId);
			}
		}

577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
		this.cachedViewPositionsValue = JSON.stringify([...this.cachedViewInfo]);
	}

	private getViewsByContainer(viewContainer: ViewContainer): IViewDescriptor[] {
		const result = this.viewsRegistry.getViews(viewContainer).filter(viewDescriptor => {
			const cachedContainer = this.cachedViewInfo.get(viewDescriptor.id)?.containerId || viewContainer.id;
			return cachedContainer === viewContainer.id;
		});

		for (const [viewId, containerInfo] of this.cachedViewInfo.entries()) {
			if (!containerInfo || containerInfo.containerId !== viewContainer.id) {
				continue;
			}

			if (this.viewsRegistry.getViewContainer(viewId) === viewContainer) {
				continue;
			}

595
			const viewDescriptor = this.getViewDescriptor(viewId);
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 622
			if (viewDescriptor) {
				result.push(viewDescriptor);
			}
		}

		return result;
	}

	private onDidRegisterViewContainer(viewContainer: ViewContainer): void {
		this.getOrRegisterViewDescriptorCollection(viewContainer);
	}

	private getOrRegisterViewDescriptorCollection(viewContainer: ViewContainer): ViewDescriptorCollection {
		let viewDescriptorCollection = this.viewDescriptorCollections.get(viewContainer)?.viewDescriptorCollection;

		if (!viewDescriptorCollection) {
			const disposables = new DisposableStore();
			viewDescriptorCollection = disposables.add(new ViewDescriptorCollection(this.contextKeyService));

			this.onDidChangeActiveViews({ added: viewDescriptorCollection.activeViewDescriptors, removed: [] });
			viewDescriptorCollection.onDidChangeActiveViews(changed => this.onDidChangeActiveViews(changed), this, disposables);

			this.viewDescriptorCollections.set(viewContainer, { viewDescriptorCollection, disposable: disposables });

			const viewsToRegister = this.getViewsByContainer(viewContainer);
			if (viewsToRegister.length) {
				this.addViews(viewContainer, viewsToRegister);
623
				viewsToRegister.forEach(viewDescriptor => this.getOrCreateMovableViewContextKey(viewDescriptor).set(!!viewDescriptor.canMoveView));
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
			}
		}

		return viewDescriptorCollection;
	}

	private onDidDeregisterViewContainer(viewContainer: ViewContainer): void {
		const viewDescriptorCollectionItem = this.viewDescriptorCollections.get(viewContainer);
		if (viewDescriptorCollectionItem) {
			viewDescriptorCollectionItem.disposable.dispose();
			this.viewDescriptorCollections.delete(viewContainer);
		}
	}

	private onDidChangeActiveViews({ added, removed }: { added: IViewDescriptor[], removed: IViewDescriptor[]; }): void {
		added.forEach(viewDescriptor => this.getOrCreateActiveViewContextKey(viewDescriptor).set(true));
		removed.forEach(viewDescriptor => this.getOrCreateActiveViewContextKey(viewDescriptor).set(false));
	}

	private addViews(container: ViewContainer, views: IViewDescriptor[]): void {
644
		// Update in memory cache
S
Sandeep Somavarapu 已提交
645
		const location = this.getViewContainerLocation(container);
646 647 648
		const sourceViewId = this.generatedContainerSourceViewIds.get(container.id);
		views.forEach(view => {
			this.cachedViewInfo.set(view.id, { containerId: container.id, location, sourceViewId });
S
SteVen Batten 已提交
649
			this.getOrCreateDefaultViewLocationContextKey(view).set(this.getDefaultContainer(view.id) === container);
650 651
		});

652 653 654 655
		this.getViewDescriptors(container).addViews(views);
	}

	private removeViews(container: ViewContainer, views: IViewDescriptor[]): void {
S
SteVen Batten 已提交
656 657 658 659
		// Set view default location keys to false
		views.forEach(view => this.getOrCreateDefaultViewLocationContextKey(view).set(false));

		// Remove the views
660
		this.getViewDescriptors(container).removeViews(views);
661 662 663 664 665 666 667 668 669 670 671
	}

	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;
	}
672 673 674 675 676 677 678 679 680 681

	private getOrCreateMovableViewContextKey(viewDescriptor: IViewDescriptor): IContextKey<boolean> {
		const movableViewContextKeyId = `${viewDescriptor.id}.canMove`;
		let contextKey = this.movableViewContextKeys.get(movableViewContextKeyId);
		if (!contextKey) {
			contextKey = new RawContextKey(movableViewContextKeyId, false).bindTo(this.contextKeyService);
			this.movableViewContextKeys.set(movableViewContextKeyId, contextKey);
		}
		return contextKey;
	}
S
SteVen Batten 已提交
682 683 684 685 686 687 688 689 690 691

	private getOrCreateDefaultViewLocationContextKey(viewDescriptor: IViewDescriptor): IContextKey<boolean> {
		const defaultViewLocationContextKeyId = `${viewDescriptor.id}.defaultViewLocation`;
		let contextKey = this.defaultViewLocationContextKeys.get(defaultViewLocationContextKeyId);
		if (!contextKey) {
			contextKey = new RawContextKey(defaultViewLocationContextKeyId, false).bindTo(this.contextKeyService);
			this.defaultViewLocationContextKeys.set(defaultViewLocationContextKeyId, contextKey);
		}
		return contextKey;
	}
692 693 694
}

registerSingleton(IViewDescriptorService, ViewDescriptorService);