contextKeyService.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License. See License.txt in the project root for license information.
  4. *--------------------------------------------------------------------------------------------*/
  5. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  6. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  7. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  8. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  9. return c > 3 && r && Object.defineProperty(target, key, r), r;
  10. };
  11. var __param = (this && this.__param) || function (paramIndex, decorator) {
  12. return function (target, key) { decorator(target, key, paramIndex); }
  13. };
  14. import { PauseableEmitter } from '../../../base/common/event.js';
  15. import { Iterable } from '../../../base/common/iterator.js';
  16. import { DisposableStore, MutableDisposable } from '../../../base/common/lifecycle.js';
  17. import { TernarySearchTree } from '../../../base/common/map.js';
  18. import { localize } from '../../../nls.js';
  19. import { CommandsRegistry } from '../../commands/common/commands.js';
  20. import { IConfigurationService } from '../../configuration/common/configuration.js';
  21. import { IContextKeyService, RawContextKey, SET_CONTEXT_COMMAND_ID } from '../common/contextkey.js';
  22. import { KeybindingResolver } from '../../keybinding/common/keybindingResolver.js';
  23. const KEYBINDING_CONTEXT_ATTR = 'data-keybinding-context';
  24. export class Context {
  25. constructor(id, parent) {
  26. this._id = id;
  27. this._parent = parent;
  28. this._value = Object.create(null);
  29. this._value['_contextId'] = id;
  30. }
  31. setValue(key, value) {
  32. // console.log('SET ' + key + ' = ' + value + ' ON ' + this._id);
  33. if (this._value[key] !== value) {
  34. this._value[key] = value;
  35. return true;
  36. }
  37. return false;
  38. }
  39. removeValue(key) {
  40. // console.log('REMOVE ' + key + ' FROM ' + this._id);
  41. if (key in this._value) {
  42. delete this._value[key];
  43. return true;
  44. }
  45. return false;
  46. }
  47. getValue(key) {
  48. const ret = this._value[key];
  49. if (typeof ret === 'undefined' && this._parent) {
  50. return this._parent.getValue(key);
  51. }
  52. return ret;
  53. }
  54. }
  55. class NullContext extends Context {
  56. constructor() {
  57. super(-1, null);
  58. }
  59. setValue(key, value) {
  60. return false;
  61. }
  62. removeValue(key) {
  63. return false;
  64. }
  65. getValue(key) {
  66. return undefined;
  67. }
  68. }
  69. NullContext.INSTANCE = new NullContext();
  70. class ConfigAwareContextValuesContainer extends Context {
  71. constructor(id, _configurationService, emitter) {
  72. super(id, null);
  73. this._configurationService = _configurationService;
  74. this._values = TernarySearchTree.forConfigKeys();
  75. this._listener = this._configurationService.onDidChangeConfiguration(event => {
  76. if (event.source === 6 /* DEFAULT */) {
  77. // new setting, reset everything
  78. const allKeys = Array.from(Iterable.map(this._values, ([k]) => k));
  79. this._values.clear();
  80. emitter.fire(new ArrayContextKeyChangeEvent(allKeys));
  81. }
  82. else {
  83. const changedKeys = [];
  84. for (const configKey of event.affectedKeys) {
  85. const contextKey = `config.${configKey}`;
  86. const cachedItems = this._values.findSuperstr(contextKey);
  87. if (cachedItems !== undefined) {
  88. changedKeys.push(...Iterable.map(cachedItems, ([key]) => key));
  89. this._values.deleteSuperstr(contextKey);
  90. }
  91. if (this._values.has(contextKey)) {
  92. changedKeys.push(contextKey);
  93. this._values.delete(contextKey);
  94. }
  95. }
  96. emitter.fire(new ArrayContextKeyChangeEvent(changedKeys));
  97. }
  98. });
  99. }
  100. dispose() {
  101. this._listener.dispose();
  102. }
  103. getValue(key) {
  104. if (key.indexOf(ConfigAwareContextValuesContainer._keyPrefix) !== 0) {
  105. return super.getValue(key);
  106. }
  107. if (this._values.has(key)) {
  108. return this._values.get(key);
  109. }
  110. const configKey = key.substr(ConfigAwareContextValuesContainer._keyPrefix.length);
  111. const configValue = this._configurationService.getValue(configKey);
  112. let value = undefined;
  113. switch (typeof configValue) {
  114. case 'number':
  115. case 'boolean':
  116. case 'string':
  117. value = configValue;
  118. break;
  119. default:
  120. if (Array.isArray(configValue)) {
  121. value = JSON.stringify(configValue);
  122. }
  123. else {
  124. value = configValue;
  125. }
  126. }
  127. this._values.set(key, value);
  128. return value;
  129. }
  130. setValue(key, value) {
  131. return super.setValue(key, value);
  132. }
  133. removeValue(key) {
  134. return super.removeValue(key);
  135. }
  136. }
  137. ConfigAwareContextValuesContainer._keyPrefix = 'config.';
  138. class ContextKey {
  139. constructor(service, key, defaultValue) {
  140. this._service = service;
  141. this._key = key;
  142. this._defaultValue = defaultValue;
  143. this.reset();
  144. }
  145. set(value) {
  146. this._service.setContext(this._key, value);
  147. }
  148. reset() {
  149. if (typeof this._defaultValue === 'undefined') {
  150. this._service.removeContext(this._key);
  151. }
  152. else {
  153. this._service.setContext(this._key, this._defaultValue);
  154. }
  155. }
  156. get() {
  157. return this._service.getContextKeyValue(this._key);
  158. }
  159. }
  160. class SimpleContextKeyChangeEvent {
  161. constructor(key) {
  162. this.key = key;
  163. }
  164. affectsSome(keys) {
  165. return keys.has(this.key);
  166. }
  167. }
  168. class ArrayContextKeyChangeEvent {
  169. constructor(keys) {
  170. this.keys = keys;
  171. }
  172. affectsSome(keys) {
  173. for (const key of this.keys) {
  174. if (keys.has(key)) {
  175. return true;
  176. }
  177. }
  178. return false;
  179. }
  180. }
  181. class CompositeContextKeyChangeEvent {
  182. constructor(events) {
  183. this.events = events;
  184. }
  185. affectsSome(keys) {
  186. for (const e of this.events) {
  187. if (e.affectsSome(keys)) {
  188. return true;
  189. }
  190. }
  191. return false;
  192. }
  193. }
  194. export class AbstractContextKeyService {
  195. constructor(myContextId) {
  196. this._onDidChangeContext = new PauseableEmitter({ merge: input => new CompositeContextKeyChangeEvent(input) });
  197. this.onDidChangeContext = this._onDidChangeContext.event;
  198. this._isDisposed = false;
  199. this._myContextId = myContextId;
  200. }
  201. createKey(key, defaultValue) {
  202. if (this._isDisposed) {
  203. throw new Error(`AbstractContextKeyService has been disposed`);
  204. }
  205. return new ContextKey(this, key, defaultValue);
  206. }
  207. bufferChangeEvents(callback) {
  208. this._onDidChangeContext.pause();
  209. try {
  210. callback();
  211. }
  212. finally {
  213. this._onDidChangeContext.resume();
  214. }
  215. }
  216. createScoped(domNode) {
  217. if (this._isDisposed) {
  218. throw new Error(`AbstractContextKeyService has been disposed`);
  219. }
  220. return new ScopedContextKeyService(this, domNode);
  221. }
  222. contextMatchesRules(rules) {
  223. if (this._isDisposed) {
  224. throw new Error(`AbstractContextKeyService has been disposed`);
  225. }
  226. const context = this.getContextValuesContainer(this._myContextId);
  227. const result = KeybindingResolver.contextMatchesRules(context, rules);
  228. // console.group(rules.serialize() + ' -> ' + result);
  229. // rules.keys().forEach(key => { console.log(key, ctx[key]); });
  230. // console.groupEnd();
  231. return result;
  232. }
  233. getContextKeyValue(key) {
  234. if (this._isDisposed) {
  235. return undefined;
  236. }
  237. return this.getContextValuesContainer(this._myContextId).getValue(key);
  238. }
  239. setContext(key, value) {
  240. if (this._isDisposed) {
  241. return;
  242. }
  243. const myContext = this.getContextValuesContainer(this._myContextId);
  244. if (!myContext) {
  245. return;
  246. }
  247. if (myContext.setValue(key, value)) {
  248. this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key));
  249. }
  250. }
  251. removeContext(key) {
  252. if (this._isDisposed) {
  253. return;
  254. }
  255. if (this.getContextValuesContainer(this._myContextId).removeValue(key)) {
  256. this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key));
  257. }
  258. }
  259. getContext(target) {
  260. if (this._isDisposed) {
  261. return NullContext.INSTANCE;
  262. }
  263. return this.getContextValuesContainer(findContextAttr(target));
  264. }
  265. }
  266. let ContextKeyService = class ContextKeyService extends AbstractContextKeyService {
  267. constructor(configurationService) {
  268. super(0);
  269. this._contexts = new Map();
  270. this._toDispose = new DisposableStore();
  271. this._lastContextId = 0;
  272. const myContext = new ConfigAwareContextValuesContainer(this._myContextId, configurationService, this._onDidChangeContext);
  273. this._contexts.set(this._myContextId, myContext);
  274. this._toDispose.add(myContext);
  275. // Uncomment this to see the contexts continuously logged
  276. // let lastLoggedValue: string | null = null;
  277. // setInterval(() => {
  278. // let values = Object.keys(this._contexts).map((key) => this._contexts[key]);
  279. // let logValue = values.map(v => JSON.stringify(v._value, null, '\t')).join('\n');
  280. // if (lastLoggedValue !== logValue) {
  281. // lastLoggedValue = logValue;
  282. // console.log(lastLoggedValue);
  283. // }
  284. // }, 2000);
  285. }
  286. dispose() {
  287. this._onDidChangeContext.dispose();
  288. this._isDisposed = true;
  289. this._toDispose.dispose();
  290. }
  291. getContextValuesContainer(contextId) {
  292. if (this._isDisposed) {
  293. return NullContext.INSTANCE;
  294. }
  295. return this._contexts.get(contextId) || NullContext.INSTANCE;
  296. }
  297. createChildContext(parentContextId = this._myContextId) {
  298. if (this._isDisposed) {
  299. throw new Error(`ContextKeyService has been disposed`);
  300. }
  301. let id = (++this._lastContextId);
  302. this._contexts.set(id, new Context(id, this.getContextValuesContainer(parentContextId)));
  303. return id;
  304. }
  305. disposeContext(contextId) {
  306. if (!this._isDisposed) {
  307. this._contexts.delete(contextId);
  308. }
  309. }
  310. };
  311. ContextKeyService = __decorate([
  312. __param(0, IConfigurationService)
  313. ], ContextKeyService);
  314. export { ContextKeyService };
  315. class ScopedContextKeyService extends AbstractContextKeyService {
  316. constructor(parent, domNode) {
  317. super(parent.createChildContext());
  318. this._parentChangeListener = new MutableDisposable();
  319. this._parent = parent;
  320. this._updateParentChangeListener();
  321. this._domNode = domNode;
  322. if (this._domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) {
  323. let extraInfo = '';
  324. if (this._domNode.classList) {
  325. extraInfo = Array.from(this._domNode.classList.values()).join(', ');
  326. }
  327. console.error(`Element already has context attribute${extraInfo ? ': ' + extraInfo : ''}`);
  328. }
  329. this._domNode.setAttribute(KEYBINDING_CONTEXT_ATTR, String(this._myContextId));
  330. }
  331. _updateParentChangeListener() {
  332. // Forward parent events to this listener. Parent will change.
  333. this._parentChangeListener.value = this._parent.onDidChangeContext(this._onDidChangeContext.fire, this._onDidChangeContext);
  334. }
  335. dispose() {
  336. if (this._isDisposed) {
  337. return;
  338. }
  339. this._onDidChangeContext.dispose();
  340. this._parent.disposeContext(this._myContextId);
  341. this._parentChangeListener.dispose();
  342. this._domNode.removeAttribute(KEYBINDING_CONTEXT_ATTR);
  343. this._isDisposed = true;
  344. }
  345. getContextValuesContainer(contextId) {
  346. if (this._isDisposed) {
  347. return NullContext.INSTANCE;
  348. }
  349. return this._parent.getContextValuesContainer(contextId);
  350. }
  351. createChildContext(parentContextId = this._myContextId) {
  352. if (this._isDisposed) {
  353. throw new Error(`ScopedContextKeyService has been disposed`);
  354. }
  355. return this._parent.createChildContext(parentContextId);
  356. }
  357. disposeContext(contextId) {
  358. if (this._isDisposed) {
  359. return;
  360. }
  361. this._parent.disposeContext(contextId);
  362. }
  363. }
  364. function findContextAttr(domNode) {
  365. while (domNode) {
  366. if (domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) {
  367. const attr = domNode.getAttribute(KEYBINDING_CONTEXT_ATTR);
  368. if (attr) {
  369. return parseInt(attr, 10);
  370. }
  371. return NaN;
  372. }
  373. domNode = domNode.parentElement;
  374. }
  375. return 0;
  376. }
  377. CommandsRegistry.registerCommand(SET_CONTEXT_COMMAND_ID, function (accessor, contextKey, contextValue) {
  378. accessor.get(IContextKeyService).createKey(String(contextKey), contextValue);
  379. });
  380. CommandsRegistry.registerCommand({
  381. id: 'getContextKeyInfo',
  382. handler() {
  383. return [...RawContextKey.all()].sort((a, b) => a.key.localeCompare(b.key));
  384. },
  385. description: {
  386. description: localize('getContextKeyInfo', "A command that returns information about context keys"),
  387. args: []
  388. }
  389. });
  390. CommandsRegistry.registerCommand('_generateContextKeyInfo', function () {
  391. const result = [];
  392. const seen = new Set();
  393. for (let info of RawContextKey.all()) {
  394. if (!seen.has(info.key)) {
  395. seen.add(info.key);
  396. result.push(info);
  397. }
  398. }
  399. result.sort((a, b) => a.key.localeCompare(b.key));
  400. console.log(JSON.stringify(result, undefined, 2));
  401. });