viewDescriptorService.ts 24.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.
 *--------------------------------------------------------------------------------------------*/

S
Sandeep Somavarapu 已提交
6 7
import { ViewContainerLocation, IViewDescriptorService, ViewContainer, IViewsRegistry, IViewContainersRegistry, IViewDescriptor, Extensions as ViewExtensions } from 'vs/workbench/common/views';
import { IContextKey, RawContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
8 9 10 11 12 13 14 15
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';
S
Sandeep Somavarapu 已提交
16
import { IStorageKeysSyncRegistryService } from 'vs/platform/userDataSync/common/storageKeys';
S
SteVen Batten 已提交
17
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
18
import { generateUuid } from 'vs/base/common/uuid';
19
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
S
Sandeep Somavarapu 已提交
20
import { ViewContainerModel } from 'vs/workbench/services/views/common/viewContainerModel';
21 22 23 24 25 26 27 28 29 30 31 32 33

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

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 已提交
34 35 36
	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;

37 38 39
	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;

40
	private readonly viewContainerModels: Map<ViewContainer, { viewContainerModel: ViewContainerModel, disposable: IDisposable; }>;
41
	private readonly activeViewContextKeys: Map<string, IContextKey<boolean>>;
42
	private readonly movableViewContextKeys: Map<string, IContextKey<boolean>>;
S
SteVen Batten 已提交
43
	private readonly defaultViewLocationContextKeys: Map<string, IContextKey<boolean>>;
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

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

	private cachedViewInfo: Map<string, ICachedViewContainerInfo>;

	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(
67
		@IInstantiationService private readonly instantiationService: IInstantiationService,
68 69
		@IContextKeyService private readonly contextKeyService: IContextKeyService,
		@IStorageService private readonly storageService: IStorageService,
S
Sandeep Somavarapu 已提交
70
		@IExtensionService private readonly extensionService: IExtensionService,
S
SteVen Batten 已提交
71 72
		@ITelemetryService private readonly telemetryService: ITelemetryService,
		@IStorageKeysSyncRegistryService storageKeysSyncRegistryService: IStorageKeysSyncRegistryService,
73 74 75
	) {
		super();

S
Sandeep Somavarapu 已提交
76
		storageKeysSyncRegistryService.registerStorageKey({ key: ViewDescriptorService.CACHED_VIEW_POSITIONS, version: 1 });
77
		this.viewContainerModels = new Map<ViewContainer, { viewContainerModel: ViewContainerModel, disposable: IDisposable; }>();
78
		this.activeViewContextKeys = new Map<string, IContextKey<boolean>>();
79
		this.movableViewContextKeys = new Map<string, IContextKey<boolean>>();
S
SteVen Batten 已提交
80
		this.defaultViewLocationContextKeys = new Map<string, IContextKey<boolean>>();
81 82 83 84 85 86 87 88 89

		this.viewContainersRegistry = Registry.as<IViewContainersRegistry>(ViewExtensions.ViewContainersRegistry);
		this.viewsRegistry = Registry.as<IViewsRegistry>(ViewExtensions.ViewsRegistry);

		this.cachedViewInfo = this.getCachedViewPositions();

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

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

93 94 95
		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 已提交
96
		this._register(this.viewsRegistry.onDidChangeContainer(({ views, from, to }) => this.moveViews(views, from, to)));
97 98 99 100

		this._register(this.viewContainersRegistry.onDidRegister(({ viewContainer }) => this.onDidRegisterViewContainer(viewContainer)));
		this._register(this.viewContainersRegistry.onDidDeregister(({ viewContainer }) => this.onDidDeregisterViewContainer(viewContainer)));
		this._register(toDisposable(() => {
101 102
			this.viewContainerModels.forEach(({ disposable }) => disposable.dispose());
			this.viewContainerModels.clear();
103 104 105 106 107 108 109
		}));

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

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

S
SteVen Batten 已提交
110
	private registerGroupedViews(groupedViews: Map<string, { cachedContainerInfo?: ICachedViewContainerInfo, views: IViewDescriptor[] }>): void {
111
		// Register views that have already been registered to their correct view containers
S
SteVen Batten 已提交
112 113 114
		for (const containerId of groupedViews.keys()) {
			const viewContainer = this.viewContainersRegistry.get(containerId);
			const containerData = groupedViews.get(containerId)!;
115 116

			// The container has not been registered yet
117
			if (!viewContainer || !this.viewContainerModels.has(viewContainer)) {
S
SteVen Batten 已提交
118 119 120
				if (containerData.cachedContainerInfo && this.shouldGenerateContainer(containerData.cachedContainerInfo)) {
					const containerInfo = containerData.cachedContainerInfo;

121 122
					if (!this.viewContainersRegistry.get(containerId)) {
						this.registerGeneratedViewContainer(containerInfo.location!, containerId);
S
SteVen Batten 已提交
123 124 125
					}
				}

126 127 128
				continue;
			}

S
SteVen Batten 已提交
129
			this.addViews(viewContainer, containerData.views);
130 131 132
		}
	}

S
SteVen Batten 已提交
133
	private deregisterGroupedViews(groupedViews: Map<string, { cachedContainerInfo?: ICachedViewContainerInfo, views: IViewDescriptor[] }>): void {
134 135 136 137 138
		// 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
139
			if (!viewContainer || !this.viewContainerModels.has(viewContainer)) {
140 141 142
				continue;
			}

S
SteVen Batten 已提交
143
			this.removeViews(viewContainer, groupedViews.get(viewContainerId)!.views);
144 145 146
		}
	}

S
SteVen Batten 已提交
147
	private tryGenerateContainers(fallbackToDefault?: boolean): void {
148 149
		for (const [viewId, containerInfo] of this.cachedViewInfo.entries()) {
			const containerId = containerInfo.containerId;
S
SteVen Batten 已提交
150

151 152 153 154 155 156
			// check if cached view container is registered
			if (this.viewContainersRegistry.get(containerId)) {
				continue;
			}

			// check if we should generate this container
S
SteVen Batten 已提交
157
			if (this.shouldGenerateContainer(containerInfo)) {
158 159
				this.registerGeneratedViewContainer(containerInfo.location!, containerId);
				continue;
160 161
			}

S
SteVen Batten 已提交
162 163 164
			if (fallbackToDefault) {
				// check if view has been registered to default location
				const viewContainer = this.viewsRegistry.getViewContainer(viewId);
165
				const viewDescriptor = this.getViewDescriptorById(viewId);
S
SteVen Batten 已提交
166 167
				if (viewContainer && viewDescriptor) {
					this.addViews(viewContainer, [viewDescriptor]);
168

S
SteVen Batten 已提交
169 170 171 172
					const newLocation = this.getViewContainerLocation(viewContainer);
					if (containerInfo.location && containerInfo.location !== newLocation) {
						this._onDidChangeLocation.fire({ views: [viewDescriptor], from: containerInfo.location, to: newLocation });
					}
173
				}
174 175 176
			}
		}

S
SteVen Batten 已提交
177 178 179 180 181 182 183
		if (fallbackToDefault) {
			this.saveViewPositionsToCache();
		}
	}

	private onDidRegisterExtensions(): void {
		this.tryGenerateContainers(true);
184 185 186 187 188 189 190 191
	}

	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 已提交
192
		// or we can generate the container from the source view id
193
		this.registerGroupedViews(regroupedViews);
194 195

		views.forEach(viewDescriptor => this.getOrCreateMovableViewContextKey(viewDescriptor).set(!!viewDescriptor.canMoveView));
196 197
	}

S
SteVen Batten 已提交
198
	private shouldGenerateContainer(containerInfo: ICachedViewContainerInfo): boolean {
199
		return containerInfo.containerId.startsWith(ViewDescriptorService.COMMON_CONTAINER_ID_PREFIX) && containerInfo.location !== undefined;
S
SteVen Batten 已提交
200 201
	}

202 203 204 205
	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);
206
		views.forEach(viewDescriptor => this.getOrCreateMovableViewContextKey(viewDescriptor).set(false));
207 208
	}

S
SteVen Batten 已提交
209 210
	private regroupViews(containerId: string, views: IViewDescriptor[]): Map<string, { cachedContainerInfo?: ICachedViewContainerInfo, views: IViewDescriptor[] }> {
		const ret = new Map<string, { cachedContainerInfo?: ICachedViewContainerInfo, views: IViewDescriptor[] }>();
211 212

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

S
SteVen Batten 已提交
216 217 218
			const containerData = ret.get(correctContainerId) || { cachedContainerInfo: containerInfo, views: [] };
			containerData.views.push(viewDescriptor);
			ret.set(correctContainerId, containerData);
219 220 221 222 223
		});

		return ret;
	}

224
	getViewDescriptorById(viewId: string): IViewDescriptor | null {
225 226 227
		return this.viewsRegistry.getView(viewId);
	}

228
	getViewLocationById(viewId: string): ViewContainerLocation | null {
229 230 231 232 233 234 235 236 237 238 239 240 241 242
		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 已提交
243
		return this.getViewContainerLocation(container);
244 245
	}

246
	getViewContainerByViewId(viewId: string): ViewContainer | null {
247
		const containerId = this.cachedViewInfo.get(viewId)?.containerId;
S
SteVen Batten 已提交
248

249 250 251 252 253
		return containerId ?
			this.viewContainersRegistry.get(containerId) ?? null :
			this.viewsRegistry.getViewContainer(viewId);
	}

S
Sandeep Somavarapu 已提交
254 255 256 257
	getViewContainerLocation(viewContainer: ViewContainer): ViewContainerLocation {
		return this.viewContainersRegistry.getViewContainerLocation(viewContainer);
	}

258
	getDefaultContainerById(viewId: string): ViewContainer | null {
259 260 261
		return this.viewsRegistry.getViewContainer(viewId) ?? null;
	}

262 263
	getViewContainerModel(container: ViewContainer): ViewContainerModel {
		return this.getOrRegisterViewContainerModel(container);
264 265
	}

266 267 268 269 270 271 272 273 274 275 276 277 278 279
	getViewContainerById(id: string): ViewContainer | null {
		return this.viewContainersRegistry.get(id) || null;
	}
	getViewContainersByLocation(location: ViewContainerLocation): ViewContainer[] {
		return this.viewContainersRegistry.getViewContainers(location);
	}
	getViewContainers(): ViewContainer[] {
		return this.viewContainersRegistry.all;
	}

	moveViewContainerToLocation(viewContainer: ViewContainer, location: ViewContainerLocation): void {
		// to be implemented
	}

S
SteVen Batten 已提交
280
	moveViewToLocation(view: IViewDescriptor, location: ViewContainerLocation): void {
281
		let container = this.registerGeneratedViewContainer(location);
S
SteVen Batten 已提交
282
		this.moveViewsToContainer([view], container);
283 284
	}

S
SteVen Batten 已提交
285
	moveViewsToContainer(views: IViewDescriptor[], viewContainer: ViewContainer): void {
286 287 288 289
		if (!views.length) {
			return;
		}

290
		const from = this.getViewContainerByViewId(views[0].id);
291 292 293
		const to = viewContainer;

		if (from && to && from !== to) {
S
Sandeep Somavarapu 已提交
294 295 296
			this.moveViews(views, from, to);
		}
	}
297

S
SteVen Batten 已提交
298
	private moveViews(views: IViewDescriptor[], from: ViewContainer, to: ViewContainer, skipCacheUpdate?: boolean): void {
S
Sandeep Somavarapu 已提交
299 300
		this.removeViews(from, views);
		this.addViews(to, views);
301

S
Sandeep Somavarapu 已提交
302 303
		const oldLocation = this.getViewContainerLocation(from);
		const newLocation = this.getViewContainerLocation(to);
304

S
Sandeep Somavarapu 已提交
305 306
		if (oldLocation !== newLocation) {
			this._onDidChangeLocation.fire({ views, from: oldLocation, to: newLocation });
307
		}
S
Sandeep Somavarapu 已提交
308 309

		this._onDidChangeContainer.fire({ views, from, to });
S
SteVen Batten 已提交
310 311 312

		if (!skipCacheUpdate) {
			this.saveViewPositionsToCache();
S
SteVen Batten 已提交
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349

			const containerToString = (container: ViewContainer): string => {
				if (container.id.startsWith(ViewDescriptorService.COMMON_CONTAINER_ID_PREFIX)) {
					return 'custom';
				}

				if (!container.extensionId) {
					return container.id;
				}

				return 'extension';
			};

			// Log on cache update to avoid duplicate events in other windows
			const viewCount = views.length;
			const fromContainer = containerToString(from);
			const toContainer = containerToString(to);
			const fromLocation = oldLocation === ViewContainerLocation.Panel ? 'panel' : 'sidebar';
			const toLocation = newLocation === ViewContainerLocation.Panel ? 'panel' : 'sidebar';

			interface ViewDescriptorServiceMoveViewsEvent {
				viewCount: number;
				fromContainer: string;
				toContainer: string;
				fromLocation: string;
				toLocation: string;
			}

			type ViewDescriptorServiceMoveViewsClassification = {
				viewCount: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
				fromContainer: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
				toContainer: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
				fromLocation: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
				toLocation: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
			};

			this.telemetryService.publicLog2<ViewDescriptorServiceMoveViewsEvent, ViewDescriptorServiceMoveViewsClassification>('viewDescriptorService.moveViews', { viewCount, fromContainer, toContainer, fromLocation, toLocation });
S
SteVen Batten 已提交
350
		}
351 352
	}

353 354
	private registerGeneratedViewContainer(location: ViewContainerLocation, existingId?: string): ViewContainer {
		const id = existingId || this.generateContainerId(location);
355 356 357

		return this.viewContainersRegistry.registerViewContainer({
			id,
358
			ctorDescriptor: new SyncDescriptor(ViewPaneContainer, [id, { mergeViewWithContainerWhenSingleView: true, donotShowContainerTitleWhenMergedWithContainer: true }]),
359
			name: 'Custom Views', // we don't want to see this, so no need to localize
360
			icon: location === ViewContainerLocation.Sidebar ? 'codicon-window' : undefined,
361
			storageId: `${id}.state`,
362 363 364 365 366
			hideIfEmpty: true
		}, location);
	}

	private getCachedViewPositions(): Map<string, ICachedViewContainerInfo> {
S
SteVen Batten 已提交
367 368 369 370 371 372 373 374 375 376
		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;
377 378 379 380 381 382 383 384 385 386
	}

	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()) {
387
				const viewDescriptor = this.getViewDescriptorById(viewId);
S
SteVen Batten 已提交
388 389 390 391
				if (!viewDescriptor) {
					continue;
				}

392
				const prevViewContainer = this.getViewContainerByViewId(viewId);
S
SteVen Batten 已提交
393 394
				const newViewContainerInfo = newCachedPositions.get(viewId)!;
				// Verify if we need to create the destination container
395 396
				if (!this.viewContainersRegistry.get(newViewContainerInfo.containerId)) {
					this.registerGeneratedViewContainer(newViewContainerInfo.location!, newViewContainerInfo.containerId);
S
SteVen Batten 已提交
397 398 399 400
				}

				// Try moving to the new container
				const newViewContainer = this.viewContainersRegistry.get(newViewContainerInfo.containerId);
401
				if (prevViewContainer && newViewContainer && newViewContainer !== prevViewContainer) {
402
					const viewDescriptor = this.getViewDescriptorById(viewId);
403
					if (viewDescriptor) {
S
SteVen Batten 已提交
404
						this.moveViews([viewDescriptor], prevViewContainer, newViewContainer);
405 406 407 408
					}
				}
			}

409 410
			// If a value is not present in the cache, it must be reset to default
			this.viewContainersRegistry.all.forEach(viewContainer => {
411 412
				const viewContainerModel = this.getViewContainerModel(viewContainer);
				viewContainerModel.allViewDescriptors.forEach(viewDescriptor => {
413
					if (!newCachedPositions.has(viewDescriptor.id)) {
414 415
						const currentContainer = this.getViewContainerByViewId(viewDescriptor.id);
						const defaultContainer = this.getDefaultContainerById(viewDescriptor.id);
416 417 418 419 420 421 422 423 424
						if (currentContainer && defaultContainer && currentContainer !== defaultContainer) {
							this.moveViews([viewDescriptor], currentContainer, defaultContainer);
						}

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

425 426 427 428 429
			this.cachedViewInfo = this.getCachedViewPositions();
		}
	}

	// Generated Container Id Format
430 431
	// {Common Prefix}.{Location}.{Uniqueness Id}
	// Old Format (deprecated)
432
	// {Common Prefix}.{Uniqueness Id}.{Source View Id}
433 434
	private generateContainerId(location: ViewContainerLocation): string {
		return `${ViewDescriptorService.COMMON_CONTAINER_ID_PREFIX}.${location === ViewContainerLocation.Panel ? 'panel' : 'sidebar'}.${generateUuid()}`;
435 436 437 438 439 440 441 442 443 444 445 446
	}

	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 => {
447 448
			const viewContainerModel = this.getViewContainerModel(viewContainer);
			viewContainerModel.allViewDescriptors.forEach(viewDescriptor => {
S
Sandeep Somavarapu 已提交
449
				const containerLocation = this.getViewContainerLocation(viewContainer);
450 451
				this.cachedViewInfo.set(viewDescriptor.id, {
					containerId: viewContainer.id,
452
					location: containerLocation
453 454 455 456
				});
			});
		});

457 458 459 460
		// 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) {
461
			const defaultContainer = this.getDefaultContainerById(viewId);
462 463 464 465 466
			if (defaultContainer?.id === containerInfo.containerId) {
				this.cachedViewInfo.delete(viewId);
			}
		}

467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
		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;
			}

485
			const viewDescriptor = this.getViewDescriptorById(viewId);
486 487 488 489 490 491 492 493 494
			if (viewDescriptor) {
				result.push(viewDescriptor);
			}
		}

		return result;
	}

	private onDidRegisterViewContainer(viewContainer: ViewContainer): void {
495
		this.getOrRegisterViewContainerModel(viewContainer);
496 497
	}

498 499
	private getOrRegisterViewContainerModel(viewContainer: ViewContainer): ViewContainerModel {
		let viewContainerModel = this.viewContainerModels.get(viewContainer)?.viewContainerModel;
500

501
		if (!viewContainerModel) {
502
			const disposables = new DisposableStore();
503
			viewContainerModel = disposables.add(this.instantiationService.createInstance(ViewContainerModel, viewContainer));
504

505 506
			this.onDidChangeActiveViews({ added: viewContainerModel.activeViewDescriptors, removed: [] });
			viewContainerModel.onDidChangeActiveViewDescriptors(changed => this.onDidChangeActiveViews(changed), this, disposables);
507

508
			this.viewContainerModels.set(viewContainer, { viewContainerModel: viewContainerModel, disposable: disposables });
509 510 511 512

			const viewsToRegister = this.getViewsByContainer(viewContainer);
			if (viewsToRegister.length) {
				this.addViews(viewContainer, viewsToRegister);
513
				viewsToRegister.forEach(viewDescriptor => this.getOrCreateMovableViewContextKey(viewDescriptor).set(!!viewDescriptor.canMoveView));
514 515 516
			}
		}

517
		return viewContainerModel;
518 519 520
	}

	private onDidDeregisterViewContainer(viewContainer: ViewContainer): void {
521 522 523 524
		const viewContainerModelItem = this.viewContainerModels.get(viewContainer);
		if (viewContainerModelItem) {
			viewContainerModelItem.disposable.dispose();
			this.viewContainerModels.delete(viewContainer);
525 526 527
		}
	}

528
	private onDidChangeActiveViews({ added, removed }: { added: ReadonlyArray<IViewDescriptor>, removed: ReadonlyArray<IViewDescriptor>; }): void {
529 530 531 532 533
		added.forEach(viewDescriptor => this.getOrCreateActiveViewContextKey(viewDescriptor).set(true));
		removed.forEach(viewDescriptor => this.getOrCreateActiveViewContextKey(viewDescriptor).set(false));
	}

	private addViews(container: ViewContainer, views: IViewDescriptor[]): void {
534
		// Update in memory cache
S
Sandeep Somavarapu 已提交
535
		const location = this.getViewContainerLocation(container);
536
		views.forEach(view => {
537
			this.cachedViewInfo.set(view.id, { containerId: container.id, location });
538
			this.getOrCreateDefaultViewLocationContextKey(view).set(this.getDefaultContainerById(view.id) === container);
539 540
		});

541
		this.getViewContainerModel(container).add(views);
542 543 544
	}

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

		// Remove the views
549
		this.getViewContainerModel(container).remove(views);
550 551 552 553 554 555 556 557 558 559 560
	}

	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;
	}
561 562 563 564 565 566 567 568 569 570

	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 已提交
571 572 573 574 575 576 577 578 579 580

	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;
	}
581 582 583
}

registerSingleton(IViewDescriptorService, ViewDescriptorService);