workbenchThemeService.ts 28.6 KB
Newer Older
E
Erich Gamma 已提交
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 * as nls from 'vs/nls';
M
Martin Aeschlimann 已提交
7
import * as types from 'vs/base/common/types';
8
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
9
import { IWorkbenchThemeService, IColorTheme, ITokenColorCustomizations, IFileIconTheme, ExtensionData, VS_LIGHT_THEME, VS_DARK_THEME, VS_HC_THEME, COLOR_THEME_SETTING, ICON_THEME_SETTING, CUSTOM_WORKBENCH_COLORS_SETTING, CUSTOM_EDITOR_COLORS_SETTING, DETECT_HC_SETTING, HC_THEME_ID, IColorCustomizations } from 'vs/workbench/services/themes/common/workbenchThemeService';
B
Benjamin Pasero 已提交
10
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
J
Johannes Rieken 已提交
11
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
12
import { Registry } from 'vs/platform/registry/common/platform';
13
import * as errors from 'vs/base/common/errors';
14
import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
15
import { IConfigurationRegistry, Extensions as ConfigurationExtensions, IConfigurationPropertySchema, IConfigurationNode } from 'vs/platform/configuration/common/configurationRegistry';
16
import { ColorThemeData } from 'vs/workbench/services/themes/common/colorThemeData';
17
import { ITheme, Extensions as ThemingExtensions, IThemingRegistry } from 'vs/platform/theme/common/themeService';
M
Matt Bierner 已提交
18
import { Event, Emitter } from 'vs/base/common/event';
19
import { registerFileIconThemeSchemas } from 'vs/workbench/services/themes/common/fileIconThemeSchema';
20
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
21
import { ColorThemeStore } from 'vs/workbench/services/themes/common/colorThemeStore';
22 23
import { FileIconThemeStore } from 'vs/workbench/services/themes/common/fileIconThemeStore';
import { FileIconThemeData } from 'vs/workbench/services/themes/common/fileIconThemeData';
24
import { removeClasses, addClasses } from 'vs/base/browser/dom';
25
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
26
import { IFileService, FileChangeType } from 'vs/platform/files/common/files';
M
Martin Aeschlimann 已提交
27 28
import { URI } from 'vs/base/common/uri';
import * as resources from 'vs/base/common/resources';
29 30 31
import { IJSONSchema } from 'vs/base/common/jsonSchema';
import { textmateColorsSchemaId, registerColorThemeSchemas, textmateColorSettingsSchemaId } from 'vs/workbench/services/themes/common/colorThemeSchema';
import { workbenchColorsSchemaId } from 'vs/platform/theme/common/colorRegistry';
32
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
33
import { getRemoteAuthority } from 'vs/platform/remote/common/remoteHosts';
34

E
Erich Gamma 已提交
35 36
// implementation

M
Martin Aeschlimann 已提交
37
const DEFAULT_THEME_ID = 'vs-dark vscode-theme-defaults-themes-dark_plus-json';
38
const DEFAULT_THEME_SETTING_VALUE = 'Default Dark+';
M
Martin Aeschlimann 已提交
39

40
const PERSISTED_THEME_STORAGE_KEY = 'colorThemeData';
41
const PERSISTED_ICON_THEME_STORAGE_KEY = 'iconThemeData';
42

43 44 45
const defaultThemeExtensionId = 'vscode-theme-defaults';
const oldDefaultThemeExtensionId = 'vscode-theme-colorful-defaults';

46
const DEFAULT_ICON_THEME_SETTING_VALUE = 'vs-seti';
47
const DEFAULT_ICON_THEME_ID = 'vscode.vscode-theme-seti-vs-seti';
48 49
const fileIconsEnabledClass = 'file-icons-enabled';

50 51 52
const colorThemeRulesClassName = 'contributedColorTheme';
const iconThemeRulesClassName = 'contributedIconTheme';

53 54
const themingRegistry = Registry.as<IThemingRegistry>(ThemingExtensions.ThemingContribution);

J
Johannes Rieken 已提交
55
function validateThemeId(theme: string): string {
56 57
	// migrations
	switch (theme) {
58 59 60
		case VS_LIGHT_THEME: return `vs ${defaultThemeExtensionId}-themes-light_vs-json`;
		case VS_DARK_THEME: return `vs-dark ${defaultThemeExtensionId}-themes-dark_vs-json`;
		case VS_HC_THEME: return `hc-black ${defaultThemeExtensionId}-themes-hc_black-json`;
61 62 63 64 65 66
		case `vs ${oldDefaultThemeExtensionId}-themes-light_plus-tmTheme`: return `vs ${defaultThemeExtensionId}-themes-light_plus-json`;
		case `vs-dark ${oldDefaultThemeExtensionId}-themes-dark_plus-tmTheme`: return `vs-dark ${defaultThemeExtensionId}-themes-dark_plus-json`;
	}
	return theme;
}

67
export class WorkbenchThemeService implements IWorkbenchThemeService {
68
	_serviceBrand: any;
E
Erich Gamma 已提交
69

70
	private colorThemeStore: ColorThemeStore;
71
	private currentColorTheme: ColorThemeData;
M
Martin Aeschlimann 已提交
72
	private container: HTMLElement;
M
Matt Bierner 已提交
73
	private readonly onColorThemeChange: Emitter<IColorTheme>;
74
	private watchedColorThemeLocation: URI | undefined;
75
	private watchedColorThemeDisposable: IDisposable;
M
Martin Aeschlimann 已提交
76

77
	private iconThemeStore: FileIconThemeStore;
M
Martin Aeschlimann 已提交
78
	private currentIconTheme: FileIconThemeData;
M
Matt Bierner 已提交
79
	private readonly onFileIconThemeChange: Emitter<IFileIconTheme>;
80
	private watchedIconThemeLocation: URI | undefined;
81
	private watchedIconThemeDisposable: IDisposable;
E
Erich Gamma 已提交
82

83
	private themingParticipantChangeListener: IDisposable;
84

85
	private get colorCustomizations(): IColorCustomizations {
86
		return this.configurationService.getValue<IColorCustomizations>(CUSTOM_WORKBENCH_COLORS_SETTING) || {};
87 88 89
	}

	private get tokenColorCustomizations(): ITokenColorCustomizations {
90
		return this.configurationService.getValue<ITokenColorCustomizations>(CUSTOM_EDITOR_COLORS_SETTING) || {};
91 92
	}

M
Martin Aeschlimann 已提交
93
	constructor(
94
		@IExtensionService extensionService: IExtensionService,
95 96 97
		@IStorageService private readonly storageService: IStorageService,
		@IConfigurationService private readonly configurationService: IConfigurationService,
		@ITelemetryService private readonly telemetryService: ITelemetryService,
98
		@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
B
Benjamin Pasero 已提交
99
		@IFileService private readonly fileService: IFileService
100
	) {
101

102
		this.container = document.body;
103
		this.colorThemeStore = new ColorThemeStore(extensionService, ColorThemeData.createLoadedEmptyTheme(DEFAULT_THEME_ID, DEFAULT_THEME_SETTING_VALUE));
104
		this.onFileIconThemeChange = new Emitter<IFileIconTheme>();
105
		this.iconThemeStore = new FileIconThemeStore(extensionService);
106
		this.onColorThemeChange = new Emitter<IColorTheme>({ leakWarningThreshold: 400 });
107

M
Martin Aeschlimann 已提交
108
		this.currentIconTheme = FileIconThemeData.createUnloadedTheme('');
109

110 111 112
		// In order to avoid paint flashing for tokens, because
		// themes are loaded asynchronously, we need to initialize
		// a color theme document with good defaults until the theme is loaded
113
		let themeData: ColorThemeData | undefined = undefined;
114
		let persistedThemeData = this.storageService.get(PERSISTED_THEME_STORAGE_KEY, StorageScope.GLOBAL);
115
		if (persistedThemeData) {
116
			themeData = ColorThemeData.fromStorageData(persistedThemeData);
117
		}
118
		let containerBaseTheme = this.getBaseThemeFromContainer();
M
Martin Aeschlimann 已提交
119
		if (!themeData || themeData.baseTheme !== containerBaseTheme) {
120
			themeData = ColorThemeData.createUnloadedTheme(containerBaseTheme);
121
		}
122
		themeData.setCustomColors(this.colorCustomizations);
123
		themeData.setCustomTokenColors(this.tokenColorCustomizations);
124
		this.updateDynamicCSSRules(themeData);
125
		this.applyTheme(themeData, undefined, true);
E
Erich Gamma 已提交
126

127
		let persistedIconThemeData = this.storageService.get(PERSISTED_ICON_THEME_STORAGE_KEY, StorageScope.GLOBAL);
128
		if (persistedIconThemeData) {
129
			const iconData = FileIconThemeData.fromStorageData(persistedIconThemeData);
130 131 132
			if (iconData) {
				_applyIconTheme(iconData, () => {
					this.doSetFileIconTheme(iconData);
M
Martin Aeschlimann 已提交
133
					return Promise.resolve(iconData);
134 135 136 137
				});
			}
		}

R
Rob Lourens 已提交
138
		this.initialize().then(undefined, errors.onUnexpectedError).then(_ => {
139
			this.installConfigurationListener();
M
Martin Aeschlimann 已提交
140
		});
141

142 143
		let prevColorId: string | undefined = undefined;

144
		// update settings schema setting for theme specific settings
145
		this.colorThemeStore.onDidChange(async event => {
146 147 148 149
			// updates enum for the 'workbench.colorTheme` setting
			colorThemeSettingSchema.enum = event.themes.map(t => t.settingsId);
			colorThemeSettingSchema.enumDescriptions = event.themes.map(t => t.description || '');

150 151
			const themeSpecificWorkbenchColors: IJSONSchema = { properties: {} };
			const themeSpecificTokenColors: IJSONSchema = { properties: {} };
A
Alex 已提交
152

153 154
			const workbenchColors = { $ref: workbenchColorsSchemaId, additionalProperties: false };
			const tokenColors = { properties: tokenColorSchema.properties, additionalProperties: false };
155
			for (let t of event.themes) {
156
				// add theme specific color customization ("[Abyss]":{ ... })
157
				const themeId = `[${t.settingsId}]`;
158 159
				themeSpecificWorkbenchColors.properties![themeId] = workbenchColors;
				themeSpecificTokenColors.properties![themeId] = tokenColors;
160
			}
A
Alex 已提交
161

162 163
			colorCustomizationsSchema.allOf![1] = themeSpecificWorkbenchColors;
			tokenColorCustomizationSchema.allOf![1] = themeSpecificTokenColors;
164

165
			configurationRegistry.notifyConfigurationSchemaUpdated(themeSettingsConfiguration, tokenColorCustomizationConfiguration);
166

167
			if (this.currentColorTheme.isLoaded) {
168 169 170
				const themeData = await this.colorThemeStore.findThemeData(this.currentColorTheme.id);
				if (!themeData) {
					// current theme is no longer available
171
					prevColorId = this.currentColorTheme.id;
172
					this.setColorTheme(DEFAULT_THEME_ID, 'auto');
173
				} else {
174 175 176 177
					if (this.currentColorTheme.id === DEFAULT_THEME_ID && !types.isUndefined(prevColorId) && await this.colorThemeStore.findThemeData(prevColorId)) {
						// restore color
						this.setColorTheme(prevColorId, 'auto');
						prevColorId = undefined;
178
					}
179
				}
180
			}
181
		});
182 183 184 185 186

		let prevFileIconId: string | undefined = undefined;
		this.iconThemeStore.onDidChange(async event => {
			iconThemeSettingSchema.enum = [null, ...event.themes.map(t => t.settingsId)];
			iconThemeSettingSchema.enumDescriptions = [iconThemeSettingSchema.enumDescriptions![0], ...event.themes.map(t => t.description || '')];
187
			configurationRegistry.notifyConfigurationSchemaUpdated(themeSettingsConfiguration);
188 189

			if (this.currentIconTheme.isLoaded) {
190 191 192
				const theme = await this.iconThemeStore.findThemeData(this.currentIconTheme.id);
				if (!theme) {
					// current theme is no longer available
193
					prevFileIconId = this.currentIconTheme.id;
194
					this.setFileIconTheme(DEFAULT_ICON_THEME_ID, 'auto');
195
				} else {
196
					// restore color
197
					if (this.currentIconTheme.id === DEFAULT_ICON_THEME_ID && !types.isUndefined(prevFileIconId) && await this.iconThemeStore.findThemeData(prevFileIconId)) {
198 199
						this.setFileIconTheme(prevFileIconId, 'auto');
						prevFileIconId = undefined;
200
					}
201
				}
202
			}
203
		});
M
Martin Aeschlimann 已提交
204 205 206 207 208 209 210

		this.fileService.onFileChanges(async e => {
			if (this.watchedColorThemeLocation && this.currentColorTheme && e.contains(this.watchedColorThemeLocation, FileChangeType.UPDATED)) {
				await this.currentColorTheme.reload(this.fileService);
				this.currentColorTheme.setCustomColors(this.colorCustomizations);
				this.currentColorTheme.setCustomTokenColors(this.tokenColorCustomizations);
				this.updateDynamicCSSRules(this.currentColorTheme);
211
				this.applyTheme(this.currentColorTheme, undefined, false);
M
Martin Aeschlimann 已提交
212 213 214
			}
			if (this.watchedIconThemeLocation && this.currentIconTheme && e.contains(this.watchedIconThemeLocation, FileChangeType.UPDATED)) {
				await this.currentIconTheme.reload(this.fileService);
215 216 217 218
				_applyIconTheme(this.currentIconTheme, () => {
					this.doSetFileIconTheme(this.currentIconTheme);
					return Promise.resolve(this.currentIconTheme);
				});
M
Martin Aeschlimann 已提交
219 220
			}
		});
A
Alex Dima 已提交
221 222
	}

M
Martin Aeschlimann 已提交
223
	public get onDidColorThemeChange(): Event<IColorTheme> {
M
Martin Aeschlimann 已提交
224
		return this.onColorThemeChange.event;
E
Erich Gamma 已提交
225 226
	}

M
Martin Aeschlimann 已提交
227 228 229 230
	public get onDidFileIconThemeChange(): Event<IFileIconTheme> {
		return this.onFileIconThemeChange.event;
	}

231 232 233 234
	public get onIconThemeChange(): Event<IFileIconTheme> {
		return this.onFileIconThemeChange.event;
	}

235 236
	public get onThemeChange(): Event<ITheme> {
		return this.onColorThemeChange.event;
237 238
	}

239
	private initialize(): Promise<[IColorTheme | null, IFileIconTheme | null]> {
B
Benjamin Pasero 已提交
240 241 242
		let detectHCThemeSetting = this.configurationService.getValue<boolean>(DETECT_HC_SETTING);

		let colorThemeSetting: string;
243
		if (this.environmentService.configuration.highContrast && detectHCThemeSetting) {
B
Benjamin Pasero 已提交
244 245 246 247
			colorThemeSetting = HC_THEME_ID;
		} else {
			colorThemeSetting = this.configurationService.getValue<string>(COLOR_THEME_SETTING);
		}
248

249
		let iconThemeSetting = this.configurationService.getValue<string | null>(ICON_THEME_SETTING);
M
Martin Aeschlimann 已提交
250

251
		const extDevLocs = this.environmentService.extensionDevelopmentLocationURI;
252
		let uri: URI | undefined;
253
		if (extDevLocs && extDevLocs.length > 0) {
254
			// if there are more than one ext dev paths, use first
255
			uri = extDevLocs[0];
256 257
		}

M
Martin Aeschlimann 已提交
258
		return Promise.all([
259
			this.colorThemeStore.findThemeDataBySettingsId(colorThemeSetting, DEFAULT_THEME_ID).then(theme => {
260
				return this.colorThemeStore.findThemeDataByParentLocation(uri).then(devThemes => {
261 262 263 264 265 266
					if (devThemes.length) {
						return this.setColorTheme(devThemes[0].id, ConfigurationTarget.MEMORY);
					} else {
						return this.setColorTheme(theme && theme.id, undefined);
					}
				});
M
Martin Aeschlimann 已提交
267
			}),
268
			this.iconThemeStore.findThemeBySettingsId(iconThemeSetting).then(theme => {
269
				return this.iconThemeStore.findThemeDataByParentLocation(uri).then(devThemes => {
270 271 272
					if (devThemes.length) {
						return this.setFileIconTheme(devThemes[0].id, ConfigurationTarget.MEMORY);
					} else {
273
						return this.setFileIconTheme(theme ? theme.id : DEFAULT_ICON_THEME_ID, undefined);
274 275
					}
				});
M
Martin Aeschlimann 已提交
276
			}),
277
		]);
M
Martin Aeschlimann 已提交
278 279
	}

280
	private installConfigurationListener() {
281
		this.configurationService.onDidChangeConfiguration(e => {
282 283 284
			if (e.affectsConfiguration(COLOR_THEME_SETTING)) {
				let colorThemeSetting = this.configurationService.getValue<string>(COLOR_THEME_SETTING);
				if (colorThemeSetting !== this.currentColorTheme.settingsId) {
285
					this.colorThemeStore.findThemeDataBySettingsId(colorThemeSetting, undefined).then(theme => {
286
						if (theme) {
287
							this.setColorTheme(theme.id, undefined);
288 289 290
						}
					});
				}
291
			}
292
			if (e.affectsConfiguration(ICON_THEME_SETTING)) {
293
				let iconThemeSetting = this.configurationService.getValue<string | null>(ICON_THEME_SETTING);
294 295
				if (iconThemeSetting !== this.currentIconTheme.settingsId) {
					this.iconThemeStore.findThemeBySettingsId(iconThemeSetting).then(theme => {
296
						this.setFileIconTheme(theme ? theme.id : DEFAULT_ICON_THEME_ID, undefined);
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
					});
				}
			}
			if (this.currentColorTheme) {
				let hasColorChanges = false;
				if (e.affectsConfiguration(CUSTOM_WORKBENCH_COLORS_SETTING)) {
					this.currentColorTheme.setCustomColors(this.colorCustomizations);
					hasColorChanges = true;
				}
				if (e.affectsConfiguration(CUSTOM_EDITOR_COLORS_SETTING)) {
					this.currentColorTheme.setCustomTokenColors(this.tokenColorCustomizations);
					hasColorChanges = true;
				}
				if (hasColorChanges) {
					this.updateDynamicCSSRules(this.currentColorTheme);
					this.onColorThemeChange.fire(this.currentColorTheme);
				}
314 315 316 317
			}
		});
	}

318 319 320 321
	public getColorTheme(): IColorTheme {
		return this.currentColorTheme;
	}

322 323
	public getColorThemes(): Promise<IColorTheme[]> {
		return this.colorThemeStore.getColorThemes();
324 325
	}

326 327 328 329
	public getTheme(): ITheme {
		return this.getColorTheme();
	}

330
	public setColorTheme(themeId: string | undefined, settingsTarget: ConfigurationTarget | undefined | 'auto'): Promise<IColorTheme | null> {
M
Martin Aeschlimann 已提交
331
		if (!themeId) {
M
Martin Aeschlimann 已提交
332
			return Promise.resolve(null);
M
Martin Aeschlimann 已提交
333
		}
M
Martin Aeschlimann 已提交
334
		if (themeId === this.currentColorTheme.id && this.currentColorTheme.isLoaded) {
335
			return this.writeColorThemeConfiguration(settingsTarget);
M
Martin Aeschlimann 已提交
336 337 338 339
		}

		themeId = validateThemeId(themeId); // migrate theme ids

340 341
		return this.colorThemeStore.findThemeData(themeId, DEFAULT_THEME_ID).then(data => {
			if (!data) {
342 343
				return null;
			}
344
			const themeData = data;
345 346 347 348
			return themeData.ensureLoaded(this.fileService).then(_ => {
				if (themeId === this.currentColorTheme.id && !this.currentColorTheme.isLoaded && this.currentColorTheme.hasEqualData(themeData)) {
					// the loaded theme is identical to the perisisted theme. Don't need to send an event.
					this.currentColorTheme = themeData;
349
					themeData.setCustomColors(this.colorCustomizations);
C
Cody Hoover 已提交
350
					themeData.setCustomTokenColors(this.tokenColorCustomizations);
351 352 353 354 355 356 357
					return Promise.resolve(themeData);
				}
				themeData.setCustomColors(this.colorCustomizations);
				themeData.setCustomTokenColors(this.tokenColorCustomizations);
				this.updateDynamicCSSRules(themeData);
				return this.applyTheme(themeData, settingsTarget);
			}, error => {
358
				return Promise.reject(new Error(nls.localize('error.cannotloadtheme', "Unable to load {0}: {1}", themeData.location!.toString(), error.message)));
359
			});
M
Martin Aeschlimann 已提交
360 361 362
		});
	}

363 364 365
	public restoreColorTheme() {
		let colorThemeSetting = this.configurationService.getValue<string>(COLOR_THEME_SETTING);
		if (colorThemeSetting !== this.currentColorTheme.settingsId) {
366
			this.colorThemeStore.findThemeDataBySettingsId(colorThemeSetting, undefined).then(theme => {
367
				if (theme) {
368
					this.setColorTheme(theme.id, undefined);
369 370 371 372 373
				}
			});
		}
	}

374
	private updateDynamicCSSRules(themeData: ITheme) {
375 376
		const cssRules = new Set<string>();
		const ruleCollector = {
377
			addRule: (rule: string) => {
378 379
				if (!cssRules.has(rule)) {
					cssRules.add(rule);
380 381 382
				}
			}
		};
383
		themingRegistry.getThemingParticipants().forEach(p => p(themeData, ruleCollector, this.environmentService));
384
		_applyRules([...cssRules].join('\n'), colorThemeRulesClassName);
385 386
	}

387
	private applyTheme(newTheme: ColorThemeData, settingsTarget: ConfigurationTarget | undefined | 'auto', silent = false): Promise<IColorTheme | null> {
388 389
		if (this.container) {
			if (this.currentColorTheme) {
390
				removeClasses(this.container, this.currentColorTheme.id);
391
			} else {
392
				removeClasses(this.container, VS_DARK_THEME, VS_LIGHT_THEME, VS_HC_THEME);
393
			}
394
			addClasses(this.container, newTheme.id);
395 396
		}
		this.currentColorTheme = newTheme;
397
		if (!this.themingParticipantChangeListener) {
M
Martin Aeschlimann 已提交
398 399 400 401
			this.themingParticipantChangeListener = themingRegistry.onThemingParticipantAdded(_ => this.updateDynamicCSSRules(this.currentColorTheme));
		}

		if (this.fileService && !resources.isEqual(newTheme.location, this.watchedColorThemeLocation)) {
B
Benjamin Pasero 已提交
402
			dispose(this.watchedColorThemeDisposable);
403 404
			this.watchedColorThemeLocation = undefined;

405 406
			if (newTheme.location && (newTheme.watch || !!this.environmentService.extensionDevelopmentLocationURI)) {
				this.watchedColorThemeLocation = newTheme.location;
407
				this.watchedColorThemeDisposable = this.fileService.watch(newTheme.location);
M
Martin Aeschlimann 已提交
408
			}
409
		}
410

411 412
		this.sendTelemetry(newTheme.id, newTheme.extensionData, 'color');

413
		if (silent) {
M
Martin Aeschlimann 已提交
414
			return Promise.resolve(null);
415 416 417 418 419
		}

		this.onColorThemeChange.fire(this.currentColorTheme);

		// remember theme data for a quick restore
420 421 422
		if (newTheme.isLoaded) {
			this.storageService.store(PERSISTED_THEME_STORAGE_KEY, newTheme.toStorageData(), StorageScope.GLOBAL);
		}
423 424

		return this.writeColorThemeConfiguration(settingsTarget);
425
	}
426

427
	private writeColorThemeConfiguration(settingsTarget: ConfigurationTarget | undefined | 'auto'): Promise<IColorTheme> {
428
		if (!types.isUndefinedOrNull(settingsTarget)) {
429
			return this.writeConfiguration(COLOR_THEME_SETTING, this.currentColorTheme.settingsId, settingsTarget).then(_ => this.currentColorTheme);
M
Martin Aeschlimann 已提交
430
		}
M
Martin Aeschlimann 已提交
431
		return Promise.resolve(this.currentColorTheme);
M
Martin Aeschlimann 已提交
432 433
	}

K
katainaka0503 已提交
434
	private themeExtensionsActivated = new Map<string, boolean>();
435
	private sendTelemetry(themeId: string, themeData: ExtensionData | undefined, themeType: string) {
436 437 438
		if (themeData) {
			let key = themeType + themeData.extensionId;
			if (!this.themeExtensionsActivated.get(key)) {
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
				type ActivatePluginClassification = {
					id: { classification: 'PublicNonPersonalData', purpose: 'FeatureInsight' };
					name: { classification: 'PublicNonPersonalData', purpose: 'FeatureInsight' };
					isBuiltin: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
					publisherDisplayName: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
					themeId: { classification: 'PublicNonPersonalData', purpose: 'FeatureInsight' };
				};
				type ActivatePluginEvent = {
					id: string;
					name: string;
					isBuiltin: boolean;
					publisherDisplayName: string;
					themeId: string;
				};
				this.telemetryService.publicLog2<ActivatePluginEvent, ActivatePluginClassification>('activatePlugin', {
454 455 456
					id: themeData.extensionId,
					name: themeData.extensionName,
					isBuiltin: themeData.extensionIsBuiltin,
457
					publisherDisplayName: themeData.extensionPublisher,
458 459 460 461
					themeId: themeId
				});
				this.themeExtensionsActivated.set(key, true);
			}
462 463
		}
	}
M
Martin Aeschlimann 已提交
464

465 466
	public getFileIconThemes(): Promise<IFileIconTheme[]> {
		return this.iconThemeStore.getFileIconThemes();
M
Martin Aeschlimann 已提交
467 468
	}

469
	public getFileIconTheme() {
M
Martin Aeschlimann 已提交
470
		return this.currentIconTheme;
471 472
	}

473 474 475 476
	public getIconTheme() {
		return this.currentIconTheme;
	}

477
	public setFileIconTheme(iconTheme: string | undefined, settingsTarget: ConfigurationTarget | undefined | 'auto'): Promise<IFileIconTheme> {
478
		iconTheme = iconTheme || '';
M
Martin Aeschlimann 已提交
479
		if (iconTheme === this.currentIconTheme.id && this.currentIconTheme.isLoaded) {
M
Martin Aeschlimann 已提交
480
			return this.writeFileIconConfiguration(settingsTarget);
481
		}
482
		let onApply = (newIconTheme: FileIconThemeData) => {
483 484 485
			this.doSetFileIconTheme(newIconTheme);

			// remember theme data for a quick restore
B
Benjamin Pasero 已提交
486
			if (newIconTheme.isLoaded && (!newIconTheme.location || !getRemoteAuthority(newIconTheme.location))) {
487 488
				this.storageService.store(PERSISTED_ICON_THEME_STORAGE_KEY, newIconTheme.toStorageData(), StorageScope.GLOBAL);
			}
M
Martin Aeschlimann 已提交
489 490

			return this.writeFileIconConfiguration(settingsTarget);
491 492
		};

493 494
		return this.iconThemeStore.findThemeData(iconTheme).then(data => {
			const iconThemeData = data || FileIconThemeData.noIconTheme();
A
Alex Dima 已提交
495
			return iconThemeData.ensureLoaded(this.fileService).then(_ => {
496 497
				return _applyIconTheme(iconThemeData, onApply);
			});
M
Martin Aeschlimann 已提交
498 499
		});
	}
M
Martin Aeschlimann 已提交
500

501 502 503 504 505 506 507 508 509 510 511
	public restoreFileIconTheme() {
		let fileIconThemeSetting = this.configurationService.getValue<string | null>(ICON_THEME_SETTING);
		if (fileIconThemeSetting !== this.currentIconTheme.settingsId) {
			this.iconThemeStore.findThemeBySettingsId(fileIconThemeSetting).then(theme => {
				if (theme) {
					this.setFileIconTheme(theme.id, undefined);
				}
			});
		}
	}

512
	private doSetFileIconTheme(iconThemeData: FileIconThemeData): void {
513
		this.currentIconTheme = iconThemeData;
514 515

		if (this.container) {
516
			if (iconThemeData.id) {
517
				addClasses(this.container, fileIconsEnabledClass);
518
			} else {
519
				removeClasses(this.container, fileIconsEnabledClass);
520 521
			}
		}
M
Martin Aeschlimann 已提交
522 523

		if (this.fileService && !resources.isEqual(iconThemeData.location, this.watchedIconThemeLocation)) {
B
Benjamin Pasero 已提交
524
			dispose(this.watchedIconThemeDisposable);
525 526
			this.watchedIconThemeLocation = undefined;

527 528
			if (iconThemeData.location && (iconThemeData.watch || !!this.environmentService.extensionDevelopmentLocationURI)) {
				this.watchedIconThemeLocation = iconThemeData.location;
529
				this.watchedIconThemeDisposable = this.fileService.watch(iconThemeData.location);
M
Martin Aeschlimann 已提交
530 531 532
			}
		}

533
		if (iconThemeData.id) {
534 535 536 537 538 539
			this.sendTelemetry(iconThemeData.id, iconThemeData.extensionData, 'fileIcon');
		}
		this.onFileIconThemeChange.fire(this.currentIconTheme);

	}

540
	private writeFileIconConfiguration(settingsTarget: ConfigurationTarget | undefined | 'auto'): Promise<IFileIconTheme> {
541
		if (!types.isUndefinedOrNull(settingsTarget)) {
542
			return this.writeConfiguration(ICON_THEME_SETTING, this.currentIconTheme.settingsId, settingsTarget).then(_ => this.currentIconTheme);
M
Martin Aeschlimann 已提交
543
		}
M
Martin Aeschlimann 已提交
544
		return Promise.resolve(this.currentIconTheme);
M
Martin Aeschlimann 已提交
545 546
	}

547 548 549 550 551 552 553 554 555 556
	public writeConfiguration(key: string, value: any, settingsTarget: ConfigurationTarget | 'auto'): Promise<void> {
		let settings = this.configurationService.inspect(key);
		if (settingsTarget === 'auto') {
			if (!types.isUndefined(settings.workspaceFolder)) {
				settingsTarget = ConfigurationTarget.WORKSPACE_FOLDER;
			} else if (!types.isUndefined(settings.workspace)) {
				settingsTarget = ConfigurationTarget.WORKSPACE;
			} else {
				settingsTarget = ConfigurationTarget.USER;
			}
557
		}
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573

		if (settingsTarget === ConfigurationTarget.USER) {
			if (value === settings.user) {
				return Promise.resolve(undefined); // nothing to do
			} else if (value === settings.default) {
				if (types.isUndefined(settings.user)) {
					return Promise.resolve(undefined); // nothing to do
				}
				value = undefined; // remove configuration from user settings
			}
		} else if (settingsTarget === ConfigurationTarget.WORKSPACE || settingsTarget === ConfigurationTarget.WORKSPACE_FOLDER) {
			if (value === settings.value) {
				return Promise.resolve(undefined); // nothing to do
			}
		}
		return this.configurationService.updateValue(key, value, settingsTarget);
574
	}
575 576 577 578 579 580 581 582 583 584 585 586

	private getBaseThemeFromContainer() {
		if (this.container) {
			for (let i = this.container.classList.length - 1; i >= 0; i--) {
				const item = document.body.classList.item(i);
				if (item === VS_LIGHT_THEME || item === VS_DARK_THEME || item === VS_HC_THEME) {
					return item;
				}
			}
		}
		return VS_DARK_THEME;
	}
E
Erich Gamma 已提交
587 588
}

J
Johannes Rieken 已提交
589
function _applyIconTheme(data: FileIconThemeData, onApply: (theme: FileIconThemeData) => Promise<IFileIconTheme>): Promise<IFileIconTheme> {
590
	_applyRules(data.styleSheetContent!, iconThemeRulesClassName);
591
	return onApply(data);
M
Martin Aeschlimann 已提交
592 593 594 595
}

function _applyRules(styleSheetContent: string, rulesClassName: string) {
	let themeStyles = document.head.getElementsByClassName(rulesClassName);
E
Erich Gamma 已提交
596
	if (themeStyles.length === 0) {
B
Benjamin Pasero 已提交
597 598
		let elStyle = document.createElement('style');
		elStyle.type = 'text/css';
M
Martin Aeschlimann 已提交
599
		elStyle.className = rulesClassName;
E
Erich Gamma 已提交
600 601 602
		elStyle.innerHTML = styleSheetContent;
		document.head.appendChild(elStyle);
	} else {
B
Benjamin Pasero 已提交
603
		(<HTMLStyleElement>themeStyles[0]).innerHTML = styleSheetContent;
E
Erich Gamma 已提交
604 605 606
	}
}

607 608
registerColorThemeSchemas();
registerFileIconThemeSchemas();
M
Martin Aeschlimann 已提交
609

610
// Configuration: Themes
M
Martin Aeschlimann 已提交
611
const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration);
612

613
const colorThemeSettingSchema: IConfigurationPropertySchema = {
614 615
	type: 'string',
	description: nls.localize('colorTheme', "Specifies the color theme used in the workbench."),
616
	default: DEFAULT_THEME_SETTING_VALUE,
617 618
	enum: [],
	enumDescriptions: [],
619 620
	errorMessage: nls.localize('colorThemeError', "Theme is unknown or not installed."),
};
621

622
const iconThemeSettingSchema: IConfigurationPropertySchema = {
623
	type: ['string', 'null'],
624
	default: DEFAULT_ICON_THEME_SETTING_VALUE,
625
	description: nls.localize('iconTheme', "Specifies the icon theme used in the workbench or 'null' to not show any file icons."),
626 627 628 629
	enum: [null],
	enumDescriptions: [nls.localize('noIconThemeDesc', 'No file icons')],
	errorMessage: nls.localize('iconThemeError', "File icon theme is unknown or not installed.")
};
630
const colorCustomizationsSchema: IConfigurationPropertySchema = {
631
	type: 'object',
632
	description: nls.localize('workbenchColors', "Overrides colors from the currently selected color theme."),
633
	allOf: [{ $ref: workbenchColorsSchemaId }],
634
	default: {},
635 636 637 638
	defaultSnippets: [{
		body: {
		}
	}]
639 640
};

641
const themeSettingsConfiguration: IConfigurationNode = {
642 643 644 645
	id: 'workbench',
	order: 7.1,
	type: 'object',
	properties: {
646 647
		[COLOR_THEME_SETTING]: colorThemeSettingSchema,
		[ICON_THEME_SETTING]: iconThemeSettingSchema,
648
		[CUSTOM_WORKBENCH_COLORS_SETTING]: colorCustomizationsSchema
M
Martin Aeschlimann 已提交
649
	}
650 651
};
configurationRegistry.registerConfiguration(themeSettingsConfiguration);
652

653 654 655
function tokenGroupSettings(description: string) {
	return {
		description,
656
		default: '#FF0000',
657 658 659
		anyOf: [
			{
				type: 'string',
660
				format: 'color-hex'
661
			},
662 663 664
			{
				$ref: textmateColorSettingsSchemaId
			}
665 666
		]
	};
667
}
668

669 670 671 672 673 674 675 676 677 678 679 680 681 682
const tokenColorSchema: IJSONSchema = {
	properties: {
		comments: tokenGroupSettings(nls.localize('editorColors.comments', "Sets the colors and styles for comments")),
		strings: tokenGroupSettings(nls.localize('editorColors.strings', "Sets the colors and styles for strings literals.")),
		keywords: tokenGroupSettings(nls.localize('editorColors.keywords', "Sets the colors and styles for keywords.")),
		numbers: tokenGroupSettings(nls.localize('editorColors.numbers', "Sets the colors and styles for number literals.")),
		types: tokenGroupSettings(nls.localize('editorColors.types', "Sets the colors and styles for type declarations and references.")),
		functions: tokenGroupSettings(nls.localize('editorColors.functions', "Sets the colors and styles for functions declarations and references.")),
		variables: tokenGroupSettings(nls.localize('editorColors.variables', "Sets the colors and styles for variables declarations and references.")),
		textMateRules: {
			description: nls.localize('editorColors.textMateRules', 'Sets colors and styles using textmate theming rules (advanced).'),
			$ref: textmateColorsSchemaId
		}
	}
683
};
684
const tokenColorCustomizationSchema: IConfigurationPropertySchema = {
685 686
	description: nls.localize('editorColors', "Overrides editor colors and font style from the currently selected color theme."),
	default: {},
687
	allOf: [tokenColorSchema]
688
};
689
const tokenColorCustomizationConfiguration: IConfigurationNode = {
690 691 692 693
	id: 'editor',
	order: 7.2,
	type: 'object',
	properties: {
694
		[CUSTOM_EDITOR_COLORS_SETTING]: tokenColorCustomizationSchema
695
	}
696
};
697
configurationRegistry.registerConfiguration(tokenColorCustomizationConfiguration);
698

699
registerSingleton(IWorkbenchThemeService, WorkbenchThemeService);