UNPKG

@theia/core

Version:

Theia is a cloud & desktop IDE framework implemented in TypeScript.

343 lines • 17.5 kB
// ***************************************************************************** // Copyright (C) 2018 Ericsson and others. // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License v. 2.0 which is available at // http://www.eclipse.org/legal/epl-2.0. // // This Source Code may also be made available under the following Secondary // Licenses when the conditions for such availability set forth in the Eclipse // Public License v. 2.0 are satisfied: GNU General Public License, version 2 // with the GNU Classpath Exception which is available at // https://www.gnu.org/software/classpath/license.html. // // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0 // ***************************************************************************** import { __decorate } from "tslib"; import { inject, injectable, postConstruct, named } from 'inversify'; import { Disposable, DisposableCollection } from '../disposable.js'; import { Emitter } from '../event.js'; import { Deferred } from '../promise-util.js'; import URI from '../uri.js'; import { PreferenceLanguageOverrideService } from './preference-language-override-service.js'; import { PreferenceUtils } from './preference-provider.js'; import { PreferenceSchemaService } from './preference-schema.js'; import { PreferenceScope } from './preference-scope.js'; import { PreferenceConfigurations } from './preference-configurations.js'; import { deepFreeze } from '../objects.js'; import { unreachable } from '../types.js'; import { ILogger } from '../logger.js'; export class PreferenceChangeImpl { constructor(change, affectedOverrides) { this.affectedOverrides = affectedOverrides; this.change = deepFreeze(change); } get preferenceName() { return this.change.preferenceName; } get scope() { return this.change.scope; } get domain() { return this.change.domain; } affects(resourceUri, overrideIdentifier) { const resourcePath = resourceUri && new URI(resourceUri).path; const domain = this.change.domain; const affectsResource = !resourcePath || !domain || domain.some(uri => new URI(uri).path.relativity(resourcePath) >= 0); const affectsOverride = !overrideIdentifier || this.affectedOverrides.includes(overrideIdentifier); return affectsResource && affectsOverride; } } export const PreferenceService = Symbol('PreferenceService'); /** * We cannot load providers directly in the case if they depend on `PreferenceService` somehow. * It allows to load them lazily after DI is configured. */ export const PreferenceProviderProvider = Symbol('PreferenceProviderProvider'); let PreferenceServiceImpl = class PreferenceServiceImpl { constructor() { this.onPreferenceChangedEmitter = new Emitter(); this.onPreferenceChanged = this.onPreferenceChangedEmitter.event; this.onPreferencesChangedEmitter = new Emitter(); this.onPreferencesChanged = this.onPreferencesChangedEmitter.event; this.toDispose = new DisposableCollection(this.onPreferenceChangedEmitter, this.onPreferencesChangedEmitter); this.preferenceProviders = new Map(); this._ready = new Deferred(); this._isReady = false; } async initializeProviders() { try { for (const scope of this.schemaService.validScopes) { const provider = this.providerProvider(scope); if (provider) { this.preferenceProviders.set(scope, provider); this.toDispose.push(provider.onDidPreferencesChanged(changes => this.reconcilePreferences(changes))); await provider.ready; } else { this.logger.warn(`No preference provider bound for ${PreferenceScope[scope]}`); } } this._ready.resolve(); this._isReady = true; } catch (e) { this._ready.reject(e); } } init() { this.toDispose.push(Disposable.create(() => this._ready.reject(new Error('preference service is disposed')))); this.initializeProviders(); } dispose() { this.toDispose.dispose(); } get ready() { return this._ready.promise; } get isReady() { return this._isReady; } getAffectedOverrides(change) { if (change.overrideIdentifier) { // changes to overrides never affect other overrides return [change.overrideIdentifier]; } const preference = this.schemaService.getSchemaProperty(change.preferenceName); // Non-overridable preferences apply in every language context. if (preference && !preference.overridable) { return [...this.schemaService.overrideIdentifiers]; } const affectedOverrides = []; for (const overrideId of this.schemaService.overrideIdentifiers) { if (!this.doHas(change.preferenceName, undefined, overrideId)) { affectedOverrides.push(overrideId); } } return affectedOverrides; } reconcilePreferences(changes) { const changesToEmit = []; for (const change of changes) { for (const scope of [...this.schemaService.validScopes].reverse()) { const provider = this.getProvider(scope); if (provider) { const scopeValue = provider.get(change.preferenceName, undefined, change.overrideIdentifier); if (scope > change.scope && scopeValue !== undefined) { const preference = this.schemaService.getSchemaProperty(change.preferenceName); if (!preference?.type || preference.type === 'object' || preference.type === 'array' || Array.isArray(preference.type) && preference.type.some(candidate => candidate === 'object' || candidate === 'array')) { // Merge object/array preferences changesToEmit.push(new PreferenceChangeImpl({ ...change }, this.getAffectedOverrides(change))); } break; } // Handle changes in the same scope if (scope === change.scope) { const hasNewValue = change.newValue !== undefined || scope === PreferenceScope.Default; const isResetToUndefined = change.newValue === undefined && scopeValue === undefined; // is reset to undefined (no default value) if (hasNewValue || isResetToUndefined) { changesToEmit.push(new PreferenceChangeImpl({ ...change }, this.getAffectedOverrides(change))); break; } } // Handle fallback to more general scope when preference is reset if (scope < change.scope && change.newValue === undefined && scopeValue !== undefined) { // preference is changed to `undefined`, use the value from a more general scope changesToEmit.push(new PreferenceChangeImpl({ ...change, scope }, this.getAffectedOverrides(change))); break; } } } } // emit the changes if (changesToEmit.length > 0) { this.onPreferencesChangedEmitter.fire(changesToEmit); } changesToEmit.forEach(change => this.onPreferenceChangedEmitter.fire(change)); } getProvider(scope) { return this.preferenceProviders.get(scope); } has(preferenceName, resourceUri, overrideIdentifier) { return this.get(preferenceName, { resource: resourceUri, override: overrideIdentifier }) !== undefined; } get(preferenceName, optionsOrFallback) { let fallback; let resource; let override; if (typeof optionsOrFallback === 'string' || typeof optionsOrFallback === 'number' || typeof optionsOrFallback === 'boolean' || Array.isArray(optionsOrFallback)) { fallback = optionsOrFallback; } else if (optionsOrFallback) { ({ fallback, resource, override } = optionsOrFallback); } return this.resolve(preferenceName, fallback, resource, override).value; } resolve(preferenceName, defaultValue, resourceUri, overrideIdentifier) { const { value, configUri } = this.doResolve(preferenceName, defaultValue, resourceUri, overrideIdentifier); if (value === undefined && overrideIdentifier && this.schemaService.overrideIdentifiers.has(overrideIdentifier)) { return this.doResolve(preferenceName, defaultValue, resourceUri, undefined); } return { value, configUri }; } async set(preferenceName, value, scope, resourceUri, overrideIdentifier) { const resolvedScope = scope ?? (!resourceUri ? PreferenceScope.Workspace : PreferenceScope.Folder); if (resolvedScope === PreferenceScope.Folder && !resourceUri) { throw new Error('Unable to write to Folder Settings because no resource is provided.'); } const provider = this.getProvider(resolvedScope); if (provider && await provider.setPreference(preferenceName, value, resourceUri, overrideIdentifier)) { await this.evictSessionOverride(preferenceName, resolvedScope, overrideIdentifier); return; } throw new Error(`Unable to write to ${PreferenceScope[resolvedScope]} Settings.`); } /** * When a preference is written to a persistent scope, drop any in-memory session * override (set via `--session-preference`) for the same key so that the explicit * change takes effect for the remainder of the session. Without this, the session * scope would keep shadowing the user's change because it has higher precedence. * * Note: this fires for any write to a persistent scope, including programmatic * writes from extensions. Extensions that race with startup CLI overrides will * therefore clear them. This is intentional: a programmatic write is "explicit" * from the preference system's point of view, but consumers should be aware. * * Session preferences are global (no per-resource scoping), so `resourceUri` is * not threaded through. */ async evictSessionOverride(preferenceName, writtenScope, overrideIdentifier) { if (writtenScope === PreferenceScope.Session || writtenScope === PreferenceScope.Default) { return; } const sessionProvider = this.getProvider(PreferenceScope.Session); if (sessionProvider && sessionProvider.get(preferenceName, undefined, overrideIdentifier) !== undefined) { // Passing `undefined` clears the value in the session provider. await sessionProvider.setPreference(preferenceName, undefined, undefined, overrideIdentifier); } } inspect(preferenceName, resourceUri, overrideIdentifier) { const defaultValue = this.inspectInScope(preferenceName, PreferenceScope.Default, resourceUri, overrideIdentifier); const globalValue = this.inspectInScope(preferenceName, PreferenceScope.User, resourceUri, overrideIdentifier); const workspaceValue = this.inspectInScope(preferenceName, PreferenceScope.Workspace, resourceUri, overrideIdentifier); const workspaceFolderValue = this.inspectInScope(preferenceName, PreferenceScope.Folder, resourceUri, overrideIdentifier); const sessionValue = this.inspectInScope(preferenceName, PreferenceScope.Session, resourceUri, overrideIdentifier); const valueApplied = sessionValue ?? workspaceFolderValue ?? workspaceValue ?? globalValue ?? defaultValue; return { preferenceName, defaultValue, globalValue, workspaceValue, workspaceFolderValue, sessionValue, value: valueApplied }; } inspectInScope(preferenceName, scope, resourceUri, overrideIdentifier) { const value = this.doInspectInScope(preferenceName, scope, resourceUri, overrideIdentifier); if (value === undefined && overrideIdentifier && this.schemaService.overrideIdentifiers.has(overrideIdentifier)) { return this.doInspectInScope(preferenceName, scope, resourceUri, undefined); } return value; } getScopedValueFromInspection(inspection, scope) { switch (scope) { case PreferenceScope.Default: return inspection.defaultValue; case PreferenceScope.User: return inspection.globalValue; case PreferenceScope.Workspace: return inspection.workspaceValue; case PreferenceScope.Folder: return inspection.workspaceFolderValue; case PreferenceScope.Session: return inspection.sessionValue; } unreachable(scope, 'Not all PreferenceScope enum variants handled.'); } async updateValue(preferenceName, value, resourceUri, overrideIdentifier) { const inspection = this.inspect(preferenceName, resourceUri, overrideIdentifier); if (inspection) { const scopesToChange = this.getScopesToChange(inspection, value); const isDeletion = value === undefined || (scopesToChange.length === 1 && scopesToChange[0] === PreferenceScope.User && PreferenceUtils.deepEqual(value, inspection.defaultValue)); const effectiveValue = isDeletion ? undefined : value; await Promise.all(scopesToChange.map(scope => this.set(preferenceName, effectiveValue, scope, resourceUri, overrideIdentifier))); } } getScopesToChange(inspection, intendedValue) { if (PreferenceUtils.deepEqual(inspection.value, intendedValue)) { return []; } // Scopes in ascending order of scope breadth. const allScopes = [...this.schemaService.validScopes].reverse() // Default is read-only, and Session is populated only by `--session-preference`, // so neither is a valid target for a regular user edit. .filter(scope => scope !== PreferenceScope.Default && scope !== PreferenceScope.Session); const isScopeDefined = (scope) => this.getScopedValueFromInspection(inspection, scope) !== undefined; if (intendedValue === undefined) { return allScopes.filter(isScopeDefined); } return [allScopes.find(isScopeDefined) ?? PreferenceScope.User]; } doHas(preferenceName, resourceUri, overrideIdentifier) { return this.doGet(preferenceName, undefined, resourceUri, overrideIdentifier) !== undefined; } doInspectInScope(preferenceName, scope, resourceUri, overrideIdentifier) { const provider = this.getProvider(scope); return provider && provider.get(preferenceName, resourceUri, overrideIdentifier); } doGet(preferenceName, defaultValue, resourceUri, overrideIdentifier) { return this.doResolve(preferenceName, defaultValue, resourceUri, overrideIdentifier).value; } doResolve(preferenceName, defaultValue, resourceUri, overrideIdentifier) { const result = {}; for (const scope of this.schemaService.validScopes) { const provider = this.getProvider(scope); if (provider?.canHandleScope(scope)) { const { configUri, value } = provider.resolve(preferenceName, resourceUri, overrideIdentifier); if (value !== undefined) { result.configUri = configUri; result.value = PreferenceUtils.merge(result.value, value); } } } return { configUri: result.configUri, value: result.value !== undefined ? deepFreeze(result.value) : defaultValue }; } getConfigUri(scope, resourceUri, sectionName = this.configurations.getConfigName()) { const provider = this.getProvider(scope); if (!provider || !this.configurations.isAnyConfig(sectionName)) { return undefined; } const configUri = provider.getConfigUri && provider.getConfigUri(resourceUri, sectionName); if (configUri) { return configUri; } return provider.getContainingConfigUri && provider.getContainingConfigUri(resourceUri, sectionName); } }; __decorate([ inject(PreferenceSchemaService) ], PreferenceServiceImpl.prototype, "schemaService", void 0); __decorate([ inject(PreferenceProviderProvider) ], PreferenceServiceImpl.prototype, "providerProvider", void 0); __decorate([ inject(PreferenceConfigurations) ], PreferenceServiceImpl.prototype, "configurations", void 0); __decorate([ inject(PreferenceLanguageOverrideService) ], PreferenceServiceImpl.prototype, "preferenceOverrideService", void 0); __decorate([ inject(ILogger), named('core:PreferenceServiceImpl') ], PreferenceServiceImpl.prototype, "logger", void 0); __decorate([ postConstruct() ], PreferenceServiceImpl.prototype, "init", null); PreferenceServiceImpl = __decorate([ injectable() ], PreferenceServiceImpl); export { PreferenceServiceImpl }; //# sourceMappingURL=preference-service.js.map