viewDescriptorService.ts 29.7 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

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

export class ViewDescriptorService extends Disposable implements IViewDescriptorService {

	_serviceBrand: undefined;

	private static readonly CACHED_VIEW_POSITIONS = 'views.cachedViewPositions';
32
	private static readonly CACHED_VIEW_CONTAINER_LOCATIONS = 'views.cachedViewContainerLocations';
33 34
	private static readonly COMMON_CONTAINER_ID_PREFIX = 'workbench.views.service';

S
SteVen Batten 已提交
35 36 37
	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;

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

41 42 43
	private readonly _onDidChangeContainerLocation: Emitter<{ viewContainer: ViewContainer, from: ViewContainerLocation, to: ViewContainerLocation }> = this._register(new Emitter<{ viewContainer: ViewContainer, from: ViewContainerLocation, to: ViewContainerLocation }>());
	readonly onDidChangeContainerLocation: Event<{ viewContainer: ViewContainer, from: ViewContainerLocation, to: ViewContainerLocation }> = this._onDidChangeContainerLocation.event;

44
	private readonly viewContainerModels: Map<ViewContainer, { viewContainerModel: ViewContainerModel, disposable: IDisposable; }>;
45
	private readonly activeViewContextKeys: Map<string, IContextKey<boolean>>;
46
	private readonly movableViewContextKeys: Map<string, IContextKey<boolean>>;
S
SteVen Batten 已提交
47
	private readonly defaultViewLocationContextKeys: Map<string, IContextKey<boolean>>;
48 49 50 51 52

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

	private cachedViewInfo: Map<string, ICachedViewContainerInfo>;
53
	private cachedViewContainerInfo: Map<string, ViewContainerLocation>;
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

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

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
	private _cachedViewContainerLocationsValue: string | undefined;
	private get cachedViewContainerLocationsValue(): string {
		if (!this._cachedViewContainerLocationsValue) {
			this._cachedViewContainerLocationsValue = this.getStoredCachedViewContainerLocationsValue();
		}

		return this._cachedViewContainerLocationsValue;
	}

	private set cachedViewContainerLocationsValue(value: string) {
		if (this._cachedViewContainerLocationsValue !== value) {
			this._cachedViewContainerLocationsValue = value;
			this.setStoredCachedViewContainerLocationsValue(value);
		}
	}

87 88 89
	readonly onDidChangeViewContainers: Event<{ added: ReadonlyArray<{ container: ViewContainer, location: ViewContainerLocation }>, removed: ReadonlyArray<{ container: ViewContainer, location: ViewContainerLocation }> }>;
	get viewContainers(): ReadonlyArray<ViewContainer> { return this.viewContainersRegistry.all; }

90
	constructor(
91
		@IInstantiationService private readonly instantiationService: IInstantiationService,
92 93
		@IContextKeyService private readonly contextKeyService: IContextKeyService,
		@IStorageService private readonly storageService: IStorageService,
S
Sandeep Somavarapu 已提交
94
		@IExtensionService private readonly extensionService: IExtensionService,
S
SteVen Batten 已提交
95 96
		@ITelemetryService private readonly telemetryService: ITelemetryService,
		@IStorageKeysSyncRegistryService storageKeysSyncRegistryService: IStorageKeysSyncRegistryService,
97 98 99
	) {
		super();

S
Sandeep Somavarapu 已提交
100
		storageKeysSyncRegistryService.registerStorageKey({ key: ViewDescriptorService.CACHED_VIEW_POSITIONS, version: 1 });
101
		this.viewContainerModels = new Map<ViewContainer, { viewContainerModel: ViewContainerModel, disposable: IDisposable; }>();
102
		this.activeViewContextKeys = new Map<string, IContextKey<boolean>>();
103
		this.movableViewContextKeys = new Map<string, IContextKey<boolean>>();
S
SteVen Batten 已提交
104
		this.defaultViewLocationContextKeys = new Map<string, IContextKey<boolean>>();
105 106 107 108 109

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

		this.cachedViewInfo = this.getCachedViewPositions();
110
		this.cachedViewContainerInfo = this.getCachedViewContainerLocations();
111 112

		// Register all containers that were registered before this ctor
113 114 115 116 117
		this.viewContainers.forEach(viewContainer => this.onDidRegisterViewContainer(viewContainer));
		this.onDidChangeViewContainers = Event.any<{ added: ReadonlyArray<{ container: ViewContainer, location: ViewContainerLocation }>, removed: ReadonlyArray<{ container: ViewContainer, location: ViewContainerLocation }> }>(
			Event.map(this.viewContainersRegistry.onDidRegister, e => ({ added: [{ container: e.viewContainer, location: e.viewContainerLocation }], removed: [] })),
			Event.map(this.viewContainersRegistry.onDidDeregister, e => ({ added: [], removed: [{ container: e.viewContainer, location: e.viewContainerLocation }] }))
		);
118

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

S
Sandeep Somavarapu 已提交
122
		this._register(this.viewsRegistry.onViewsRegistered(views => this.onDidRegisterViews(views)));
123 124
		this._register(this.viewsRegistry.onViewsDeregistered(({ views, viewContainer }) => this.onDidDeregisterViews(views, viewContainer)));

S
Sandeep Somavarapu 已提交
125
		this._register(this.viewsRegistry.onDidChangeContainer(({ views, from, to }) => this.moveViews(views, from, to)));
126 127 128 129

		this._register(this.viewContainersRegistry.onDidRegister(({ viewContainer }) => this.onDidRegisterViewContainer(viewContainer)));
		this._register(this.viewContainersRegistry.onDidDeregister(({ viewContainer }) => this.onDidDeregisterViewContainer(viewContainer)));
		this._register(toDisposable(() => {
130 131
			this.viewContainerModels.forEach(({ disposable }) => disposable.dispose());
			this.viewContainerModels.clear();
132 133 134 135 136 137 138
		}));

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

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

S
SteVen Batten 已提交
139
	private registerGroupedViews(groupedViews: Map<string, { cachedContainerInfo?: ICachedViewContainerInfo, views: IViewDescriptor[] }>): void {
140
		// Register views that have already been registered to their correct view containers
S
SteVen Batten 已提交
141 142 143
		for (const containerId of groupedViews.keys()) {
			const viewContainer = this.viewContainersRegistry.get(containerId);
			const containerData = groupedViews.get(containerId)!;
144 145

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

150 151
					if (!this.viewContainersRegistry.get(containerId)) {
						this.registerGeneratedViewContainer(containerInfo.location!, containerId);
S
SteVen Batten 已提交
152 153 154
					}
				}

155 156 157
				continue;
			}

S
SteVen Batten 已提交
158
			this.addViews(viewContainer, containerData.views);
159 160 161
		}
	}

S
SteVen Batten 已提交
162
	private deregisterGroupedViews(groupedViews: Map<string, { cachedContainerInfo?: ICachedViewContainerInfo, views: IViewDescriptor[] }>): void {
163 164 165 166 167
		// 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
168
			if (!viewContainer || !this.viewContainerModels.has(viewContainer)) {
169 170 171
				continue;
			}

S
SteVen Batten 已提交
172
			this.removeViews(viewContainer, groupedViews.get(viewContainerId)!.views);
173 174 175
		}
	}

S
SteVen Batten 已提交
176
	private tryGenerateContainers(fallbackToDefault?: boolean): void {
177 178
		for (const [viewId, containerInfo] of this.cachedViewInfo.entries()) {
			const containerId = containerInfo.containerId;
S
SteVen Batten 已提交
179

180 181 182 183 184 185
			// check if cached view container is registered
			if (this.viewContainersRegistry.get(containerId)) {
				continue;
			}

			// check if we should generate this container
S
SteVen Batten 已提交
186
			if (this.shouldGenerateContainer(containerInfo)) {
187 188
				this.registerGeneratedViewContainer(containerInfo.location!, containerId);
				continue;
189 190
			}

S
SteVen Batten 已提交
191 192 193
			if (fallbackToDefault) {
				// check if view has been registered to default location
				const viewContainer = this.viewsRegistry.getViewContainer(viewId);
194
				const viewDescriptor = this.getViewDescriptorById(viewId);
S
SteVen Batten 已提交
195 196
				if (viewContainer && viewDescriptor) {
					this.addViews(viewContainer, [viewDescriptor]);
197

S
SteVen Batten 已提交
198 199 200 201
					const newLocation = this.getViewContainerLocation(viewContainer);
					if (containerInfo.location && containerInfo.location !== newLocation) {
						this._onDidChangeLocation.fire({ views: [viewDescriptor], from: containerInfo.location, to: newLocation });
					}
202
				}
203 204 205
			}
		}

S
SteVen Batten 已提交
206 207 208 209 210 211 212
		if (fallbackToDefault) {
			this.saveViewPositionsToCache();
		}
	}

	private onDidRegisterExtensions(): void {
		this.tryGenerateContainers(true);
213 214
	}

S
Sandeep Somavarapu 已提交
215 216 217 218
	private onDidRegisterViews(views: { views: IViewDescriptor[], viewContainer: ViewContainer }[]): void {
		views.forEach(({ views, viewContainer }) => {
			// When views are registered, we need to regroup them based on the cache
			const regroupedViews = this.regroupViews(viewContainer.id, views);
219

S
Sandeep Somavarapu 已提交
220 221 222 223
			// Once they are grouped, try registering them which occurs
			// if the container has already been registered within this service
			// or we can generate the container from the source view id
			this.registerGroupedViews(regroupedViews);
224

S
Sandeep Somavarapu 已提交
225 226
			views.forEach(viewDescriptor => this.getOrCreateMovableViewContextKey(viewDescriptor).set(!!viewDescriptor.canMoveView));
		});
227 228
	}

S
SteVen Batten 已提交
229
	private shouldGenerateContainer(containerInfo: ICachedViewContainerInfo): boolean {
230
		return containerInfo.containerId.startsWith(ViewDescriptorService.COMMON_CONTAINER_ID_PREFIX) && containerInfo.location !== undefined;
S
SteVen Batten 已提交
231 232
	}

233 234 235 236
	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);
237
		views.forEach(viewDescriptor => this.getOrCreateMovableViewContextKey(viewDescriptor).set(false));
238 239
	}

S
SteVen Batten 已提交
240 241
	private regroupViews(containerId: string, views: IViewDescriptor[]): Map<string, { cachedContainerInfo?: ICachedViewContainerInfo, views: IViewDescriptor[] }> {
		const ret = new Map<string, { cachedContainerInfo?: ICachedViewContainerInfo, views: IViewDescriptor[] }>();
242 243

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

S
SteVen Batten 已提交
247 248 249
			const containerData = ret.get(correctContainerId) || { cachedContainerInfo: containerInfo, views: [] };
			containerData.views.push(viewDescriptor);
			ret.set(correctContainerId, containerData);
250 251 252 253 254
		});

		return ret;
	}

255
	getViewDescriptorById(viewId: string): IViewDescriptor | null {
256 257 258
		return this.viewsRegistry.getView(viewId);
	}

259
	getViewLocationById(viewId: string): ViewContainerLocation | null {
260 261 262 263 264 265 266 267 268 269 270 271 272 273
		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 已提交
274
		return this.getViewContainerLocation(container);
275 276
	}

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

280 281 282 283 284
		return containerId ?
			this.viewContainersRegistry.get(containerId) ?? null :
			this.viewsRegistry.getViewContainer(viewId);
	}

S
Sandeep Somavarapu 已提交
285
	getViewContainerLocation(viewContainer: ViewContainer): ViewContainerLocation {
286 287 288 289 290
		const location = this.cachedViewContainerInfo.get(viewContainer.id);
		return location !== undefined ? location : this.getDefaultViewContainerLocation(viewContainer);
	}

	getDefaultViewContainerLocation(viewContainer: ViewContainer): ViewContainerLocation {
S
Sandeep Somavarapu 已提交
291 292 293
		return this.viewContainersRegistry.getViewContainerLocation(viewContainer);
	}

294
	getDefaultContainerById(viewId: string): ViewContainer | null {
295 296 297
		return this.viewsRegistry.getViewContainer(viewId) ?? null;
	}

298 299
	getViewContainerModel(container: ViewContainer): ViewContainerModel {
		return this.getOrRegisterViewContainerModel(container);
300 301
	}

302 303 304
	getViewContainerById(id: string): ViewContainer | null {
		return this.viewContainersRegistry.get(id) || null;
	}
305

306
	getViewContainersByLocation(location: ViewContainerLocation): ViewContainer[] {
307
		return this.viewContainers.filter(v => this.getViewContainerLocation(v) === location);
308
	}
309 310 311

	getDefaultViewContainer(location: ViewContainerLocation): ViewContainer | undefined {
		return this.viewContainersRegistry.getDefaultViewContainer(location);
312 313 314
	}

	moveViewContainerToLocation(viewContainer: ViewContainer, location: ViewContainerLocation): void {
315 316 317 318 319 320 321 322 323 324 325
		const from = this.getViewContainerLocation(viewContainer);
		const to = location;
		if (from !== to) {
			if (this.getDefaultViewContainerLocation(viewContainer) === to) {
				this.cachedViewContainerInfo.delete(viewContainer.id);
			} else {
				this.cachedViewContainerInfo.set(viewContainer.id, to);
			}

			this._onDidChangeContainerLocation.fire({ viewContainer, from, to });

326 327 328
			const views = this.getViewsByContainer(viewContainer);
			this._onDidChangeLocation.fire({ views, from, to });

329 330
			this.saveViewContainerLocationsToCache();
		}
331 332
	}

S
SteVen Batten 已提交
333
	moveViewToLocation(view: IViewDescriptor, location: ViewContainerLocation): void {
334
		let container = this.registerGeneratedViewContainer(location);
S
SteVen Batten 已提交
335
		this.moveViewsToContainer([view], container);
336 337
	}

S
SteVen Batten 已提交
338
	moveViewsToContainer(views: IViewDescriptor[], viewContainer: ViewContainer): void {
339 340 341 342
		if (!views.length) {
			return;
		}

343
		const from = this.getViewContainerByViewId(views[0].id);
344 345 346
		const to = viewContainer;

		if (from && to && from !== to) {
S
Sandeep Somavarapu 已提交
347 348 349
			this.moveViews(views, from, to);
		}
	}
350

S
SteVen Batten 已提交
351
	private moveViews(views: IViewDescriptor[], from: ViewContainer, to: ViewContainer, skipCacheUpdate?: boolean): void {
S
Sandeep Somavarapu 已提交
352 353
		this.removeViews(from, views);
		this.addViews(to, views);
354

S
Sandeep Somavarapu 已提交
355 356
		const oldLocation = this.getViewContainerLocation(from);
		const newLocation = this.getViewContainerLocation(to);
357

S
Sandeep Somavarapu 已提交
358 359
		if (oldLocation !== newLocation) {
			this._onDidChangeLocation.fire({ views, from: oldLocation, to: newLocation });
360
		}
S
Sandeep Somavarapu 已提交
361 362

		this._onDidChangeContainer.fire({ views, from, to });
S
SteVen Batten 已提交
363 364 365

		if (!skipCacheUpdate) {
			this.saveViewPositionsToCache();
S
SteVen Batten 已提交
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402

			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 已提交
403
		}
404 405
	}

406 407
	private registerGeneratedViewContainer(location: ViewContainerLocation, existingId?: string): ViewContainer {
		const id = existingId || this.generateContainerId(location);
408 409 410

		return this.viewContainersRegistry.registerViewContainer({
			id,
411
			ctorDescriptor: new SyncDescriptor(ViewPaneContainer, [id, { mergeViewWithContainerWhenSingleView: true, donotShowContainerTitleWhenMergedWithContainer: true }]),
412
			name: 'Custom Views', // we don't want to see this, so no need to localize
413
			icon: location === ViewContainerLocation.Sidebar ? 'codicon-window' : undefined,
414
			storageId: `${id}.state`,
415 416 417 418 419
			hideIfEmpty: true
		}, location);
	}

	private getCachedViewPositions(): Map<string, ICachedViewContainerInfo> {
S
SteVen Batten 已提交
420 421 422 423 424 425 426 427 428 429
		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;
430 431
	}

432 433 434 435
	private getCachedViewContainerLocations(): Map<string, ViewContainerLocation> {
		return new Map<string, ViewContainerLocation>(JSON.parse(this.cachedViewContainerLocationsValue));
	}

436 437 438 439 440 441 442 443
	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()) {
444
				const viewDescriptor = this.getViewDescriptorById(viewId);
S
SteVen Batten 已提交
445 446 447 448
				if (!viewDescriptor) {
					continue;
				}

449
				const prevViewContainer = this.getViewContainerByViewId(viewId);
S
SteVen Batten 已提交
450 451
				const newViewContainerInfo = newCachedPositions.get(viewId)!;
				// Verify if we need to create the destination container
452 453
				if (!this.viewContainersRegistry.get(newViewContainerInfo.containerId)) {
					this.registerGeneratedViewContainer(newViewContainerInfo.location!, newViewContainerInfo.containerId);
S
SteVen Batten 已提交
454 455 456 457
				}

				// Try moving to the new container
				const newViewContainer = this.viewContainersRegistry.get(newViewContainerInfo.containerId);
458
				if (prevViewContainer && newViewContainer && newViewContainer !== prevViewContainer) {
459
					const viewDescriptor = this.getViewDescriptorById(viewId);
460
					if (viewDescriptor) {
S
SteVen Batten 已提交
461
						this.moveViews([viewDescriptor], prevViewContainer, newViewContainer);
462 463 464 465
					}
				}
			}

466
			// If a value is not present in the cache, it must be reset to default
467
			this.viewContainers.forEach(viewContainer => {
468 469
				const viewContainerModel = this.getViewContainerModel(viewContainer);
				viewContainerModel.allViewDescriptors.forEach(viewDescriptor => {
470
					if (!newCachedPositions.has(viewDescriptor.id)) {
471 472
						const currentContainer = this.getViewContainerByViewId(viewDescriptor.id);
						const defaultContainer = this.getDefaultContainerById(viewDescriptor.id);
473 474 475 476 477 478 479 480 481
						if (currentContainer && defaultContainer && currentContainer !== defaultContainer) {
							this.moveViews([viewDescriptor], currentContainer, defaultContainer);
						}

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

482 483
			this.cachedViewInfo = this.getCachedViewPositions();
		}
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499


		if (e.key === ViewDescriptorService.CACHED_VIEW_CONTAINER_LOCATIONS && e.scope === StorageScope.GLOBAL
			&& this.cachedViewContainerLocationsValue !== this.getStoredCachedViewContainerLocationsValue() /* This checks if current window changed the value or not */) {
			this._cachedViewContainerLocationsValue = this.getStoredCachedViewContainerLocationsValue();
			const newCachedLocations = this.getCachedViewContainerLocations();

			for (const [containerId, location] of newCachedLocations.entries()) {
				const container = this.getViewContainerById(containerId);
				if (container) {
					if (location !== this.getViewContainerLocation(container)) {
						this.moveViewContainerToLocation(container, location);
					}
				}
			}

500
			this.viewContainers.forEach(viewContainer => {
501 502 503 504 505 506 507 508 509 510 511 512
				if (!newCachedLocations.has(viewContainer.id)) {
					const currentLocation = this.getViewContainerLocation(viewContainer);
					const defaultLocation = this.getDefaultViewContainerLocation(viewContainer);

					if (currentLocation !== defaultLocation) {
						this.moveViewContainerToLocation(viewContainer, defaultLocation);
					}
				}
			});

			this.cachedViewContainerInfo = this.getCachedViewContainerLocations();
		}
513 514 515
	}

	// Generated Container Id Format
516 517
	// {Common Prefix}.{Location}.{Uniqueness Id}
	// Old Format (deprecated)
518
	// {Common Prefix}.{Uniqueness Id}.{Source View Id}
519 520
	private generateContainerId(location: ViewContainerLocation): string {
		return `${ViewDescriptorService.COMMON_CONTAINER_ID_PREFIX}.${location === ViewContainerLocation.Panel ? 'panel' : 'sidebar'}.${generateUuid()}`;
521 522 523 524 525 526 527 528 529 530
	}

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

531 532 533 534 535 536 537 538
	private getStoredCachedViewContainerLocationsValue(): string {
		return this.storageService.get(ViewDescriptorService.CACHED_VIEW_CONTAINER_LOCATIONS, StorageScope.GLOBAL, '[]');
	}

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

539
	private saveViewPositionsToCache(): void {
540
		this.viewContainers.forEach(viewContainer => {
541 542
			const viewContainerModel = this.getViewContainerModel(viewContainer);
			viewContainerModel.allViewDescriptors.forEach(viewDescriptor => {
S
Sandeep Somavarapu 已提交
543
				const containerLocation = this.getViewContainerLocation(viewContainer);
544 545
				this.cachedViewInfo.set(viewDescriptor.id, {
					containerId: viewContainer.id,
546
					location: containerLocation
547 548 549 550
				});
			});
		});

551 552 553 554
		// 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) {
555
			const defaultContainer = this.getDefaultContainerById(viewId);
556 557 558 559 560
			if (defaultContainer?.id === containerInfo.containerId) {
				this.cachedViewInfo.delete(viewId);
			}
		}

561 562 563
		this.cachedViewPositionsValue = JSON.stringify([...this.cachedViewInfo]);
	}

564 565 566 567 568 569 570 571 572 573 574
	private saveViewContainerLocationsToCache(): void {
		for (const [containerId, location] of this.cachedViewContainerInfo) {
			const container = this.getViewContainerById(containerId);
			if (container && location === this.getDefaultViewContainerLocation(container)) {
				this.cachedViewContainerInfo.delete(containerId);
			}
		}

		this.cachedViewContainerLocationsValue = JSON.stringify([...this.cachedViewContainerInfo]);
	}

575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
	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;
			}

590
			const viewDescriptor = this.getViewDescriptorById(viewId);
591 592 593 594 595 596 597 598 599
			if (viewDescriptor) {
				result.push(viewDescriptor);
			}
		}

		return result;
	}

	private onDidRegisterViewContainer(viewContainer: ViewContainer): void {
600
		this.getOrRegisterViewContainerModel(viewContainer);
601 602
	}

603 604
	private getOrRegisterViewContainerModel(viewContainer: ViewContainer): ViewContainerModel {
		let viewContainerModel = this.viewContainerModels.get(viewContainer)?.viewContainerModel;
605

606
		if (!viewContainerModel) {
607
			const disposables = new DisposableStore();
608
			viewContainerModel = disposables.add(this.instantiationService.createInstance(ViewContainerModel, viewContainer));
609

610 611
			this.onDidChangeActiveViews({ added: viewContainerModel.activeViewDescriptors, removed: [] });
			viewContainerModel.onDidChangeActiveViewDescriptors(changed => this.onDidChangeActiveViews(changed), this, disposables);
612

613
			this.viewContainerModels.set(viewContainer, { viewContainerModel: viewContainerModel, disposable: disposables });
614 615 616 617

			const viewsToRegister = this.getViewsByContainer(viewContainer);
			if (viewsToRegister.length) {
				this.addViews(viewContainer, viewsToRegister);
618
				viewsToRegister.forEach(viewDescriptor => this.getOrCreateMovableViewContextKey(viewDescriptor).set(!!viewDescriptor.canMoveView));
619 620 621
			}
		}

622
		return viewContainerModel;
623 624 625
	}

	private onDidDeregisterViewContainer(viewContainer: ViewContainer): void {
626 627 628 629
		const viewContainerModelItem = this.viewContainerModels.get(viewContainer);
		if (viewContainerModelItem) {
			viewContainerModelItem.disposable.dispose();
			this.viewContainerModels.delete(viewContainer);
630 631 632
		}
	}

633
	private onDidChangeActiveViews({ added, removed }: { added: ReadonlyArray<IViewDescriptor>, removed: ReadonlyArray<IViewDescriptor>; }): void {
634 635 636 637 638
		added.forEach(viewDescriptor => this.getOrCreateActiveViewContextKey(viewDescriptor).set(true));
		removed.forEach(viewDescriptor => this.getOrCreateActiveViewContextKey(viewDescriptor).set(false));
	}

	private addViews(container: ViewContainer, views: IViewDescriptor[]): void {
639
		// Update in memory cache
S
Sandeep Somavarapu 已提交
640
		const location = this.getViewContainerLocation(container);
641
		views.forEach(view => {
642
			this.cachedViewInfo.set(view.id, { containerId: container.id, location });
643
			this.getOrCreateDefaultViewLocationContextKey(view).set(this.getDefaultContainerById(view.id) === container);
644 645
		});

646
		this.getViewContainerModel(container).add(views);
647 648 649
	}

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

		// Remove the views
654
		this.getViewContainerModel(container).remove(views);
655 656 657 658 659 660 661 662 663 664 665
	}

	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;
	}
666 667 668 669 670 671 672 673 674 675

	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 已提交
676 677 678 679 680 681 682 683 684 685

	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;
	}
686 687 688
}

registerSingleton(IViewDescriptorService, ViewDescriptorService);