workbenchThemeService.ts 28.4 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 } 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 './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/browser/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

E
Erich Gamma 已提交
34 35
// implementation

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

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

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

45
const DEFAULT_ICON_THEME_SETTING_VALUE = 'vs-seti';
46 47
const fileIconsEnabledClass = 'file-icons-enabled';

48 49 50
const colorThemeRulesClassName = 'contributedColorTheme';
const iconThemeRulesClassName = 'contributedIconTheme';

51 52
const themingRegistry = Registry.as<IThemingRegistry>(ThemingExtensions.ThemingContribution);

J
Johannes Rieken 已提交
53
function validateThemeId(theme: string): string {
54 55
	// migrations
	switch (theme) {
56 57 58
		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`;
59 60 61 62 63 64
		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;
}

65
export interface IColorCustomizations {
66
	[colorIdOrThemeSettingsId: string]: string | IColorCustomizations;
67 68
}

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

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

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

85
	private themingParticipantChangeListener: IDisposable;
86

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

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

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

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

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

112 113 114
		// 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
115
		let themeData: ColorThemeData | undefined = undefined;
116
		let persistedThemeData = this.storageService.get(PERSISTED_THEME_STORAGE_KEY, StorageScope.GLOBAL);
117
		if (persistedThemeData) {
118
			themeData = ColorThemeData.fromStorageData(persistedThemeData);
119
		}
120
		let containerBaseTheme = this.getBaseThemeFromContainer();
M
Martin Aeschlimann 已提交
121
		if (!themeData || themeData.baseTheme !== containerBaseTheme) {
122
			themeData = ColorThemeData.createUnloadedTheme(containerBaseTheme);
123
		}
124
		themeData.setCustomColors(this.colorCustomizations);
125
		themeData.setCustomTokenColors(this.tokenColorCustomizations);
126
		this.updateDynamicCSSRules(themeData);
127
		this.applyTheme(themeData, undefined, true);
E
Erich Gamma 已提交
128

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

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

144 145
		let prevColorId: string | undefined = undefined;

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

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

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

164 165
			colorCustomizationsSchema.allOf![1] = themeSpecificWorkbenchColors;
			tokenColorCustomizationSchema.allOf![1] = themeSpecificTokenColors;
166

167
			configurationRegistry.notifyConfigurationSchemaUpdated(themeSettingsConfiguration, tokenColorCustomizationConfiguration);
168

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

		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 || '')];
189
			configurationRegistry.notifyConfigurationSchemaUpdated(themeSettingsConfiguration);
190 191

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

		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);
213
				this.applyTheme(this.currentColorTheme, undefined, false);
M
Martin Aeschlimann 已提交
214 215 216
			}
			if (this.watchedIconThemeLocation && this.currentIconTheme && e.contains(this.watchedIconThemeLocation, FileChangeType.UPDATED)) {
				await this.currentIconTheme.reload(this.fileService);
217 218 219 220
				_applyIconTheme(this.currentIconTheme, () => {
					this.doSetFileIconTheme(this.currentIconTheme);
					return Promise.resolve(this.currentIconTheme);
				});
M
Martin Aeschlimann 已提交
221 222
			}
		});
A
Alex Dima 已提交
223 224
	}

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

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

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

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

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

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

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

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

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

282
	private installConfigurationListener() {
283
		this.configurationService.onDidChangeConfiguration(e => {
284 285 286
			if (e.affectsConfiguration(COLOR_THEME_SETTING)) {
				let colorThemeSetting = this.configurationService.getValue<string>(COLOR_THEME_SETTING);
				if (colorThemeSetting !== this.currentColorTheme.settingsId) {
287
					this.colorThemeStore.findThemeDataBySettingsId(colorThemeSetting, undefined).then(theme => {
288
						if (theme) {
289
							this.setColorTheme(theme.id, undefined);
290 291 292
						}
					});
				}
293
			}
294
			if (e.affectsConfiguration(ICON_THEME_SETTING)) {
295
				let iconThemeSetting = this.configurationService.getValue<string | null>(ICON_THEME_SETTING);
296 297
				if (iconThemeSetting !== this.currentIconTheme.settingsId) {
					this.iconThemeStore.findThemeBySettingsId(iconThemeSetting).then(theme => {
298
						this.setFileIconTheme(theme && theme.id || DEFAULT_ICON_THEME_SETTING_VALUE, undefined);
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
					});
				}
			}
			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);
				}
316 317 318 319
			}
		});
	}

320 321 322 323
	public getColorTheme(): IColorTheme {
		return this.currentColorTheme;
	}

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

328 329 330 331
	public getTheme(): ITheme {
		return this.getColorTheme();
	}

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

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

342 343
		return this.colorThemeStore.findThemeData(themeId, DEFAULT_THEME_ID).then(data => {
			if (!data) {
344 345
				return null;
			}
346
			const themeData = data;
347 348 349 350
			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;
351
					themeData.setCustomColors(this.colorCustomizations);
C
Cody Hoover 已提交
352
					themeData.setCustomTokenColors(this.tokenColorCustomizations);
353 354 355 356 357 358 359
					return Promise.resolve(themeData);
				}
				themeData.setCustomColors(this.colorCustomizations);
				themeData.setCustomTokenColors(this.tokenColorCustomizations);
				this.updateDynamicCSSRules(themeData);
				return this.applyTheme(themeData, settingsTarget);
			}, error => {
360
				return Promise.reject(new Error(nls.localize('error.cannotloadtheme', "Unable to load {0}: {1}", themeData.location!.toString(), error.message)));
361
			});
M
Martin Aeschlimann 已提交
362 363 364
		});
	}

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

376
	private updateDynamicCSSRules(themeData: ITheme) {
377 378
		let cssRules: string[] = [];
		let hasRule: { [rule: string]: boolean } = {};
379 380 381 382 383 384 385 386
		let ruleCollector = {
			addRule: (rule: string) => {
				if (!hasRule[rule]) {
					cssRules.push(rule);
					hasRule[rule] = true;
				}
			}
		};
387
		themingRegistry.getThemingParticipants().forEach(p => p(themeData, ruleCollector, this.environmentService));
388 389 390
		_applyRules(cssRules.join('\n'), colorThemeRulesClassName);
	}

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

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

409 410
			if (newTheme.location && (newTheme.watch || !!this.environmentService.extensionDevelopmentLocationURI)) {
				this.watchedColorThemeLocation = newTheme.location;
411
				this.watchedColorThemeDisposable = this.fileService.watch(newTheme.location);
M
Martin Aeschlimann 已提交
412
			}
413
		}
414

415 416
		this.sendTelemetry(newTheme.id, newTheme.extensionData, 'color');

417
		if (silent) {
M
Martin Aeschlimann 已提交
418
			return Promise.resolve(null);
419 420 421 422 423
		}

		this.onColorThemeChange.fire(this.currentColorTheme);

		// remember theme data for a quick restore
424 425 426
		if (newTheme.isLoaded) {
			this.storageService.store(PERSISTED_THEME_STORAGE_KEY, newTheme.toStorageData(), StorageScope.GLOBAL);
		}
427 428

		return this.writeColorThemeConfiguration(settingsTarget);
429
	}
430

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

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

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

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

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

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

			// remember theme data for a quick restore
485 486 487
			if (newIconTheme.isLoaded) {
				this.storageService.store(PERSISTED_ICON_THEME_STORAGE_KEY, newIconTheme.toStorageData(), StorageScope.GLOBAL);
			}
M
Martin Aeschlimann 已提交
488 489

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

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

500 501 502 503 504 505 506 507 508 509 510
	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);
				}
			});
		}
	}

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

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

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

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

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

	}

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

546 547 548 549 550 551 552 553 554 555
	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;
			}
556
		}
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572

		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);
573
	}
574 575 576 577 578 579 580 581 582 583 584 585

	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 已提交
586 587
}

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

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

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

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

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

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

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

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

668 669 670 671 672 673 674 675 676 677 678 679 680 681
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
		}
	}
682
};
683
const tokenColorCustomizationSchema: IConfigurationPropertySchema = {
684 685
	description: nls.localize('editorColors', "Overrides editor colors and font style from the currently selected color theme."),
	default: {},
686
	allOf: [tokenColorSchema]
687
};
688
const tokenColorCustomizationConfiguration: IConfigurationNode = {
689 690 691 692
	id: 'editor',
	order: 7.2,
	type: 'object',
	properties: {
693
		[CUSTOM_EDITOR_COLORS_SETTING]: tokenColorCustomizationSchema
694
	}
695
};
696
configurationRegistry.registerConfiguration(tokenColorCustomizationConfiguration);
697

698
registerSingleton(IWorkbenchThemeService, WorkbenchThemeService);