viewDescriptorService.ts 29.8 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 });
S
Sandeep Somavarapu 已提交
101
		storageKeysSyncRegistryService.registerStorageKey({ key: ViewDescriptorService.CACHED_VIEW_CONTAINER_LOCATIONS, version: 1 });
102
		this.viewContainerModels = new Map<ViewContainer, { viewContainerModel: ViewContainerModel, disposable: IDisposable; }>();
103
		this.activeViewContextKeys = new Map<string, IContextKey<boolean>>();
104
		this.movableViewContextKeys = new Map<string, IContextKey<boolean>>();
S
SteVen Batten 已提交
105
		this.defaultViewLocationContextKeys = new Map<string, IContextKey<boolean>>();
106 107 108 109 110

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

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

		// Register all containers that were registered before this ctor
114 115 116 117 118
		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 }] }))
		);
119

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

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

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

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

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

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

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

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

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

156 157 158
				continue;
			}

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

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

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

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

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

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

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

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

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

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

S
Sandeep Somavarapu 已提交
216 217 218 219
	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);
220

S
Sandeep Somavarapu 已提交
221 222 223 224
			// 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);
225

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

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

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

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

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

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

		return ret;
	}

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

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

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

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

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

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

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

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

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

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

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

	moveViewContainerToLocation(viewContainer: ViewContainer, location: ViewContainerLocation): void {
316 317 318 319 320 321 322 323 324 325 326
		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 });

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

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

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

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

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

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

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

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

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

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

		if (!skipCacheUpdate) {
			this.saveViewPositionsToCache();
S
SteVen Batten 已提交
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 403

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

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

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

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

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

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

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

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

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

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

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


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

501
			this.viewContainers.forEach(viewContainer => {
502 503 504 505 506 507 508 509 510 511 512 513
				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();
		}
514 515 516
	}

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

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

532 533 534 535 536 537 538 539
	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);
	}

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

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

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

565 566 567 568 569 570 571 572 573 574 575
	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]);
	}

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

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

		return result;
	}

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

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

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

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

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

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

623
		return viewContainerModel;
624 625 626
	}

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

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

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

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

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

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

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

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

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

registerSingleton(IViewDescriptorService, ViewDescriptorService);