contextKeyService.ts 14.4 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.
 *--------------------------------------------------------------------------------------------*/

6
import { Emitter, Event, PauseableEmitter } from 'vs/base/common/event';
7
import { IDisposable, DisposableStore } from 'vs/base/common/lifecycle';
8
import { distinct } from 'vs/base/common/objects';
J
Johannes Rieken 已提交
9
import { CommandsRegistry } from 'vs/platform/commands/common/commands';
A
Alex Dima 已提交
10
import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration';
11
import { IContext, IContextKey, IContextKeyChangeEvent, IContextKeyService, IContextKeyServiceTarget, IReadableSet, SET_CONTEXT_COMMAND_ID, ContextKeyExpression } from 'vs/platform/contextkey/common/contextkey';
J
Johannes Rieken 已提交
12
import { KeybindingResolver } from 'vs/platform/keybinding/common/keybindingResolver';
13

A
Alex Dima 已提交
14 15
const KEYBINDING_CONTEXT_ATTR = 'data-keybinding-context';

J
Joao Moreno 已提交
16 17
export class Context implements IContext {

A
Alex Dima 已提交
18
	protected _parent: Context | null;
J
Johannes Rieken 已提交
19
	protected _value: { [key: string]: any; };
20 21
	protected _id: number;

A
Alex Dima 已提交
22
	constructor(id: number, parent: Context | null) {
23 24 25 26 27 28 29 30 31 32 33 34
		this._id = id;
		this._parent = parent;
		this._value = Object.create(null);
		this._value['_contextId'] = id;
	}

	public setValue(key: string, value: any): boolean {
		// console.log('SET ' + key + ' = ' + value + ' ON ' + this._id);
		if (this._value[key] !== value) {
			this._value[key] = value;
			return true;
		}
35
		return false;
36 37 38 39
	}

	public removeValue(key: string): boolean {
		// console.log('REMOVE ' + key + ' FROM ' + this._id);
40 41 42 43 44
		if (key in this._value) {
			delete this._value[key];
			return true;
		}
		return false;
45 46
	}

A
Alex Dima 已提交
47
	public getValue<T>(key: string): T | undefined {
48 49 50 51 52 53
		const ret = this._value[key];
		if (typeof ret === 'undefined' && this._parent) {
			return this._parent.getValue<T>(key);
		}
		return ret;
	}
J
Joao Moreno 已提交
54

55 56 57 58 59
	public updateParent(parent: Context): void {
		this._parent = parent;
	}

	public collectAllValues(): { [key: string]: any; } {
J
Joao Moreno 已提交
60 61 62 63 64
		let result = this._parent ? this._parent.collectAllValues() : Object.create(null);
		result = { ...result, ...this._value };
		delete result['_contextId'];
		return result;
	}
65 66
}

A
Alex Dima 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
class NullContext extends Context {

	static readonly INSTANCE = new NullContext();

	constructor() {
		super(-1, null);
	}

	public setValue(key: string, value: any): boolean {
		return false;
	}

	public removeValue(key: string): boolean {
		return false;
	}

	public getValue<T>(key: string): T | undefined {
		return undefined;
	}

	collectAllValues(): { [key: string]: any; } {
		return Object.create(null);
	}
}

92 93
const configContextObject = Object.freeze({});

J
Joao Moreno 已提交
94
class ConfigAwareContextValuesContainer extends Context {
95

96
	private static readonly _keyPrefix = 'config.';
97

98 99 100 101 102 103
	private readonly _values = new Map<string, any>();
	private readonly _listener: IDisposable;

	constructor(
		id: number,
		private readonly _configurationService: IConfigurationService,
104
		emitter: Emitter<IContextKeyChangeEvent>
105
	) {
106 107
		super(id, null);

108 109 110
		this._listener = this._configurationService.onDidChangeConfiguration(event => {
			if (event.source === ConfigurationTarget.DEFAULT) {
				// new setting, reset everything
A
Alex Dima 已提交
111
				const allKeys = Array.from(this._values.keys());
112
				this._values.clear();
113
				emitter.fire(new ArrayContextKeyChangeEvent(allKeys));
114 115 116
			} else {
				const changedKeys: string[] = [];
				for (const configKey of event.affectedKeys) {
117
					let contextKey = `config.${configKey}`;
118
					if (this._values.has(contextKey)) {
119 120
						const value = this._values.get(contextKey);

121 122
						this._values.delete(contextKey);
						changedKeys.push(contextKey);
123 124 125 126 127 128 129 130 131 132 133

						if (value === configContextObject) {
							contextKey += '.';

							for (const key of this._values.keys()) {
								if (key.startsWith(contextKey)) {
									this._values.delete(key);
									changedKeys.push(key);
								}
							}
						}
134 135
					}
				}
136
				emitter.fire(new ArrayContextKeyChangeEvent(changedKeys));
137 138
			}
		});
139 140
	}

141 142
	dispose(): void {
		this._listener.dispose();
143 144
	}

145 146 147 148
	getValue(key: string): any {

		if (key.indexOf(ConfigAwareContextValuesContainer._keyPrefix) !== 0) {
			return super.getValue(key);
149
		}
150

151 152 153 154 155 156 157 158 159 160 161 162 163
		if (this._values.has(key)) {
			return this._values.get(key);
		}

		const configKey = key.substr(ConfigAwareContextValuesContainer._keyPrefix.length);
		const configValue = this._configurationService.getValue(configKey);
		let value: any = undefined;
		switch (typeof configValue) {
			case 'number':
			case 'boolean':
			case 'string':
				value = configValue;
				break;
164
			default:
165 166
				if (Array.isArray(configValue)) {
					value = JSON.stringify(configValue);
167 168
				} else {
					value = configContextObject;
169
				}
170 171
		}

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
		this._values.set(key, value);
		return value;
	}

	setValue(key: string, value: any): boolean {
		return super.setValue(key, value);
	}

	removeValue(key: string): boolean {
		return super.removeValue(key);
	}

	collectAllValues(): { [key: string]: any; } {
		const result: { [key: string]: any } = Object.create(null);
		this._values.forEach((value, index) => result[index] = value);
		return { ...result, ...super.collectAllValues() };
188 189 190
	}
}

A
Alex Dima 已提交
191
class ContextKey<T> implements IContextKey<T> {
192

193
	private _service: AbstractContextKeyService;
194
	private _key: string;
A
Alex Dima 已提交
195
	private _defaultValue: T | undefined;
196

197 198
	constructor(service: AbstractContextKeyService, key: string, defaultValue: T | undefined) {
		this._service = service;
199 200 201 202 203 204
		this._key = key;
		this._defaultValue = defaultValue;
		this.reset();
	}

	public set(value: T): void {
205
		this._service.setContext(this._key, value);
206 207 208 209
	}

	public reset(): void {
		if (typeof this._defaultValue === 'undefined') {
210
			this._service.removeContext(this._key);
211
		} else {
212
			this._service.setContext(this._key, this._defaultValue);
213 214 215
		}
	}

A
Alex Dima 已提交
216
	public get(): T | undefined {
217
		return this._service.getContextKeyValue<T>(this._key);
218 219 220
	}
}

221
class SimpleContextKeyChangeEvent implements IContextKeyChangeEvent {
222
	constructor(readonly key: string) { }
223
	affectsSome(keys: IReadableSet<string>): boolean {
224
		return keys.has(this.key);
J
Johannes Rieken 已提交
225
	}
226
}
227

228
class ArrayContextKeyChangeEvent implements IContextKeyChangeEvent {
229
	constructor(readonly keys: string[]) { }
J
Joao Moreno 已提交
230
	affectsSome(keys: IReadableSet<string>): boolean {
231 232 233 234 235 236
		for (const key of this.keys) {
			if (keys.has(key)) {
				return true;
			}
		}
		return false;
J
Johannes Rieken 已提交
237 238 239
	}
}

240 241 242
class CompositeContextKeyChangeEvent implements IContextKeyChangeEvent {
	constructor(readonly events: IContextKeyChangeEvent[]) { }
	affectsSome(keys: IReadableSet<string>): boolean {
243 244 245 246 247 248
		for (const e of this.events) {
			if (e.affectsSome(keys)) {
				return true;
			}
		}
		return false;
249 250 251
	}
}

252
export abstract class AbstractContextKeyService implements IContextKeyService {
253
	public _serviceBrand: undefined;
254

A
Alex Dima 已提交
255
	protected _isDisposed: boolean;
256
	protected _onDidChangeContext = new PauseableEmitter<IContextKeyChangeEvent>({ merge: input => new CompositeContextKeyChangeEvent(input) });
257 258 259
	protected _myContextId: number;

	constructor(myContextId: number) {
A
Alex Dima 已提交
260
		this._isDisposed = false;
261 262 263
		this._myContextId = myContextId;
	}

264 265 266 267
	public get contextId(): number {
		return this._myContextId;
	}

268 269
	abstract dispose(): void;

A
Alex Dima 已提交
270
	public createKey<T>(key: string, defaultValue: T | undefined): IContextKey<T> {
A
Alex Dima 已提交
271 272 273
		if (this._isDisposed) {
			throw new Error(`AbstractContextKeyService has been disposed`);
		}
A
Alex Dima 已提交
274
		return new ContextKey(this, key, defaultValue);
275 276
	}

J
Johannes Rieken 已提交
277
	public get onDidChangeContext(): Event<IContextKeyChangeEvent> {
278
		return this._onDidChangeContext.event;
279
	}
280 281 282 283 284 285 286 287 288 289

	bufferChangeEvents(callback: Function): void {
		this._onDidChangeContext.pause();
		try {
			callback();
		} finally {
			this._onDidChangeContext.resume();
		}
	}

A
Alex Dima 已提交
290
	public createScoped(domNode: IContextKeyServiceTarget): IContextKeyService {
A
Alex Dima 已提交
291 292 293
		if (this._isDisposed) {
			throw new Error(`AbstractContextKeyService has been disposed`);
		}
294
		return new ScopedContextKeyService(this, domNode);
295 296
	}

297
	public contextMatchesRules(rules: ContextKeyExpression | undefined): boolean {
A
Alex Dima 已提交
298 299 300
		if (this._isDisposed) {
			throw new Error(`AbstractContextKeyService has been disposed`);
		}
J
Joao Moreno 已提交
301 302
		const context = this.getContextValuesContainer(this._myContextId);
		const result = KeybindingResolver.contextMatchesRules(context, rules);
303 304 305 306 307 308
		// console.group(rules.serialize() + ' -> ' + result);
		// rules.keys().forEach(key => { console.log(key, ctx[key]); });
		// console.groupEnd();
		return result;
	}

A
Alex Dima 已提交
309 310 311 312
	public getContextKeyValue<T>(key: string): T | undefined {
		if (this._isDisposed) {
			return undefined;
		}
A
Alex Dima 已提交
313
		return this.getContextValuesContainer(this._myContextId).getValue<T>(key);
314 315 316
	}

	public setContext(key: string, value: any): void {
A
Alex Dima 已提交
317 318 319
		if (this._isDisposed) {
			return;
		}
A
Alex Dima 已提交
320 321 322 323 324
		const myContext = this.getContextValuesContainer(this._myContextId);
		if (!myContext) {
			return;
		}
		if (myContext.setValue(key, value)) {
325
			this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key));
326 327 328 329
		}
	}

	public removeContext(key: string): void {
A
Alex Dima 已提交
330 331 332
		if (this._isDisposed) {
			return;
		}
J
Johannes Rieken 已提交
333
		if (this.getContextValuesContainer(this._myContextId).removeValue(key)) {
334
			this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key));
335 336 337
		}
	}

M
Matt Bierner 已提交
338
	public getContext(target: IContextKeyServiceTarget | null): IContext {
A
Alex Dima 已提交
339 340 341
		if (this._isDisposed) {
			return NullContext.INSTANCE;
		}
J
Joao Moreno 已提交
342
		return this.getContextValuesContainer(findContextAttr(target));
A
Alex Dima 已提交
343 344
	}

J
Joao Moreno 已提交
345
	public abstract getContextValuesContainer(contextId: number): Context;
346 347
	public abstract createChildContext(parentContextId?: number): number;
	public abstract disposeContext(contextId: number): void;
348
	public abstract updateParent(parentContextKeyService?: IContextKeyService): void;
349 350
}

A
Alex Dima 已提交
351
export class ContextKeyService extends AbstractContextKeyService implements IContextKeyService {
352 353

	private _lastContextId: number;
354
	private readonly _contexts = new Map<number, Context>();
355

356
	private readonly _toDispose = new DisposableStore();
357

M
Matt Bierner 已提交
358
	constructor(@IConfigurationService configurationService: IConfigurationService) {
359 360
		super(0);
		this._lastContextId = 0;
361

362

363
		const myContext = new ConfigAwareContextValuesContainer(this._myContextId, configurationService, this._onDidChangeContext);
364
		this._contexts.set(this._myContextId, myContext);
365
		this._toDispose.add(myContext);
366 367

		// Uncomment this to see the contexts continuously logged
368
		// let lastLoggedValue: string | null = null;
369 370 371 372 373 374 375 376 377 378 379
		// setInterval(() => {
		// 	let values = Object.keys(this._contexts).map((key) => this._contexts[key]);
		// 	let logValue = values.map(v => JSON.stringify(v._value, null, '\t')).join('\n');
		// 	if (lastLoggedValue !== logValue) {
		// 		lastLoggedValue = logValue;
		// 		console.log(lastLoggedValue);
		// 	}
		// }, 2000);
	}

	public dispose(): void {
A
Alex Dima 已提交
380
		this._isDisposed = true;
381
		this._toDispose.dispose();
382 383
	}

J
Joao Moreno 已提交
384
	public getContextValuesContainer(contextId: number): Context {
A
Alex Dima 已提交
385 386
		if (this._isDisposed) {
			return NullContext.INSTANCE;
387
		}
388
		return this._contexts.get(contextId) || NullContext.INSTANCE;
389 390 391
	}

	public createChildContext(parentContextId: number = this._myContextId): number {
A
Alex Dima 已提交
392 393 394
		if (this._isDisposed) {
			throw new Error(`ContextKeyService has been disposed`);
		}
395
		let id = (++this._lastContextId);
396
		this._contexts.set(id, new Context(id, this.getContextValuesContainer(parentContextId)));
397 398 399 400
		return id;
	}

	public disposeContext(contextId: number): void {
401 402
		if (!this._isDisposed) {
			this._contexts.delete(contextId);
A
Alex Dima 已提交
403
		}
404
	}
405 406 407 408

	public updateParent(_parentContextKeyService: IContextKeyService): void {
		throw new Error('Cannot update parent of root ContextKeyService');
	}
409 410
}

A
Alex Dima 已提交
411
class ScopedContextKeyService extends AbstractContextKeyService {
412

A
Alex Dima 已提交
413
	private _parent: AbstractContextKeyService;
A
Alex Dima 已提交
414
	private _domNode: IContextKeyServiceTarget | undefined;
415

416 417
	private _parentChangeListener: IDisposable | undefined;

418
	constructor(parent: AbstractContextKeyService, domNode?: IContextKeyServiceTarget) {
419 420
		super(parent.createChildContext());
		this._parent = parent;
421
		this.updateParentChangeListener();
J
Joao Moreno 已提交
422 423 424 425 426

		if (domNode) {
			this._domNode = domNode;
			this._domNode.setAttribute(KEYBINDING_CONTEXT_ATTR, String(this._myContextId));
		}
427 428
	}

429 430 431 432 433 434 435 436 437 438 439
	private updateParentChangeListener(): void {
		if (this._parentChangeListener) {
			this._parentChangeListener.dispose();
		}

		this._parentChangeListener = this._parent.onDidChangeContext(e => {
			// Forward parent events to this listener. Parent will change.
			this._onDidChangeContext.fire(e);
		});
	}

440
	public dispose(): void {
A
Alex Dima 已提交
441
		this._isDisposed = true;
442
		this._parent.disposeContext(this._myContextId);
443
		this._parentChangeListener?.dispose();
J
Joao Moreno 已提交
444 445
		if (this._domNode) {
			this._domNode.removeAttribute(KEYBINDING_CONTEXT_ATTR);
446
			this._domNode = undefined;
J
Joao Moreno 已提交
447
		}
448 449
	}

J
Johannes Rieken 已提交
450
	public get onDidChangeContext(): Event<IContextKeyChangeEvent> {
451
		return this._onDidChangeContext.event;
452 453
	}

J
Joao Moreno 已提交
454
	public getContextValuesContainer(contextId: number): Context {
A
Alex Dima 已提交
455 456 457
		if (this._isDisposed) {
			return NullContext.INSTANCE;
		}
A
Alex Dima 已提交
458
		return this._parent.getContextValuesContainer(contextId);
459 460 461
	}

	public createChildContext(parentContextId: number = this._myContextId): number {
A
Alex Dima 已提交
462 463 464
		if (this._isDisposed) {
			throw new Error(`ScopedContextKeyService has been disposed`);
		}
465 466 467 468
		return this._parent.createChildContext(parentContextId);
	}

	public disposeContext(contextId: number): void {
A
Alex Dima 已提交
469 470 471
		if (this._isDisposed) {
			return;
		}
472 473
		this._parent.disposeContext(contextId);
	}
474

475
	public updateParent(parentContextKeyService: AbstractContextKeyService): void {
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
		const thisContainer = this._parent.getContextValuesContainer(this._myContextId);
		const oldAllValues = thisContainer.collectAllValues();
		this._parent = parentContextKeyService;
		this.updateParentChangeListener();
		const newParentContainer = this._parent.getContextValuesContainer(this._parent.contextId);
		thisContainer.updateParent(newParentContainer);

		const newAllValues = thisContainer.collectAllValues();
		const allValuesDiff = {
			...distinct(oldAllValues, newAllValues),
			...distinct(newAllValues, oldAllValues)
		};
		const changedKeys = Object.keys(allValuesDiff);

		this._onDidChangeContext.fire(new ArrayContextKeyChangeEvent(changedKeys));
	}
492
}
A
Alex Dima 已提交
493

A
Alex Dima 已提交
494
function findContextAttr(domNode: IContextKeyServiceTarget | null): number {
A
Alex Dima 已提交
495 496
	while (domNode) {
		if (domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) {
A
Alex Dima 已提交
497 498 499 500 501
			const attr = domNode.getAttribute(KEYBINDING_CONTEXT_ATTR);
			if (attr) {
				return parseInt(attr, 10);
			}
			return NaN;
A
Alex Dima 已提交
502 503 504 505 506 507
		}
		domNode = domNode.parentElement;
	}
	return 0;
}

A
Alex Dima 已提交
508 509 510
CommandsRegistry.registerCommand(SET_CONTEXT_COMMAND_ID, function (accessor, contextKey: any, contextValue: any) {
	accessor.get(IContextKeyService).createKey(String(contextKey), contextValue);
});