workbenchThemeService.ts 35.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';
M
polish  
Martin Aeschlimann 已提交
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, IColorCustomizations, CUSTOM_EDITOR_TOKENSTYLES_SETTING, IExperimentalTokenStyleCustomizations } 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';
M
polish  
Martin Aeschlimann 已提交
17
import { ITheme, Extensions as ThemingExtensions, IThemingRegistry, ThemeType, LIGHT, DARK, HIGH_CONTRAST } 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/browser/fileIconThemeStore';
import { FileIconThemeData } from 'vs/workbench/services/themes/browser/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
import { IJSONSchema } from 'vs/base/common/jsonSchema';
30
import { textmateColorsSchemaId, registerColorThemeSchemas, textmateColorGroupSchemaId } from 'vs/workbench/services/themes/common/colorThemeSchema';
31
import { workbenchColorsSchemaId } from 'vs/platform/theme/common/colorRegistry';
32
import { tokenStylingSchemaId } from 'vs/platform/theme/common/tokenClassificationRegistry';
33
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
34
import { getRemoteAuthority } from 'vs/platform/remote/common/remoteHosts';
35
import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
36
import { IExtensionResourceLoaderService } from 'vs/workbench/services/extensionResourceLoader/common/extensionResourceLoader';
37

M
polish  
Martin Aeschlimann 已提交
38 39 40 41 42 43 44 45
// settings

const PREFERRED_DARK_THEME_SETTING = 'workbench.preferredDarkColorTheme';
const PREFERRED_LIGHT_THEME_SETTING = 'workbench.preferredLightColorTheme';
const PREFERRED_HC_THEME_SETTING = 'workbench.preferredHighContrastColorTheme';
const DETECT_COLOR_SCHEME_SETTING = 'workbench.autoDetectColorScheme';
const DETECT_HC_SETTING = 'window.autoDetectHighContrast';

E
Erich Gamma 已提交
46 47
// implementation

M
Martin Aeschlimann 已提交
48
const DEFAULT_THEME_ID = 'vs-dark vscode-theme-defaults-themes-dark_plus-json';
49
const DEFAULT_THEME_SETTING_VALUE = 'Default Dark+';
M
Marvin Heilemann 已提交
50 51
const DEFAULT_THEME_DARK_SETTING_VALUE = 'Default Dark+';
const DEFAULT_THEME_LIGHT_SETTING_VALUE = 'Default Light+';
M
polish  
Martin Aeschlimann 已提交
52
const DEFAULT_THEME_HC_SETTING_VALUE = 'Default High Contrast';
M
Marvin Heilemann 已提交
53

54
const PERSISTED_THEME_STORAGE_KEY = 'colorThemeData';
55
const PERSISTED_ICON_THEME_STORAGE_KEY = 'iconThemeData';
56

57 58 59
const defaultThemeExtensionId = 'vscode-theme-defaults';
const oldDefaultThemeExtensionId = 'vscode-theme-colorful-defaults';

60
const DEFAULT_ICON_THEME_SETTING_VALUE = 'vs-seti';
61
const DEFAULT_ICON_THEME_ID = 'vscode.vscode-theme-seti-vs-seti';
62 63
const fileIconsEnabledClass = 'file-icons-enabled';

64 65 66
const colorThemeRulesClassName = 'contributedColorTheme';
const iconThemeRulesClassName = 'contributedIconTheme';

67 68
const themingRegistry = Registry.as<IThemingRegistry>(ThemingExtensions.ThemingContribution);

J
Johannes Rieken 已提交
69
function validateThemeId(theme: string): string {
70 71
	// migrations
	switch (theme) {
72 73 74 75 76
		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`;
		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`;
77 78 79 80
	}
	return theme;
}

81
export class WorkbenchThemeService implements IWorkbenchThemeService {
82
	_serviceBrand: undefined;
E
Erich Gamma 已提交
83

84
	private colorThemeStore: ColorThemeStore;
85
	private currentColorTheme: ColorThemeData;
M
Martin Aeschlimann 已提交
86
	private container: HTMLElement;
M
Matt Bierner 已提交
87
	private readonly onColorThemeChange: Emitter<IColorTheme>;
88
	private watchedColorThemeLocation: URI | undefined;
89
	private watchedColorThemeDisposable: IDisposable | undefined;
M
Martin Aeschlimann 已提交
90

91
	private iconThemeStore: FileIconThemeStore;
M
Martin Aeschlimann 已提交
92
	private currentIconTheme: FileIconThemeData;
M
Matt Bierner 已提交
93
	private readonly onFileIconThemeChange: Emitter<IFileIconTheme>;
94
	private watchedIconThemeLocation: URI | undefined;
95
	private watchedIconThemeDisposable: IDisposable | undefined;
E
Erich Gamma 已提交
96

97
	private themingParticipantChangeListener: IDisposable | undefined;
98

99
	private get colorCustomizations(): IColorCustomizations {
100
		return this.configurationService.getValue<IColorCustomizations>(CUSTOM_WORKBENCH_COLORS_SETTING) || {};
101 102 103
	}

	private get tokenColorCustomizations(): ITokenColorCustomizations {
104
		return this.configurationService.getValue<ITokenColorCustomizations>(CUSTOM_EDITOR_COLORS_SETTING) || {};
105 106
	}

107
	private get tokenStylesCustomizations(): IExperimentalTokenStyleCustomizations {
108
		return this.configurationService.getValue<IExperimentalTokenStyleCustomizations>(CUSTOM_EDITOR_TOKENSTYLES_SETTING) || {};
109 110
	}

M
Martin Aeschlimann 已提交
111
	constructor(
112
		@IExtensionService extensionService: IExtensionService,
113 114 115
		@IStorageService private readonly storageService: IStorageService,
		@IConfigurationService private readonly configurationService: IConfigurationService,
		@ITelemetryService private readonly telemetryService: ITelemetryService,
116
		@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
117
		@IFileService private readonly fileService: IFileService,
118
		@IExtensionResourceLoaderService private readonly extensionResourceLoaderService: IExtensionResourceLoaderService,
119
		@IWorkbenchLayoutService readonly layoutService: IWorkbenchLayoutService
120
	) {
121

122
		this.container = layoutService.getWorkbenchContainer();
123
		this.colorThemeStore = new ColorThemeStore(extensionService);
124
		this.onFileIconThemeChange = new Emitter<IFileIconTheme>();
125
		this.iconThemeStore = new FileIconThemeStore(extensionService);
126
		this.onColorThemeChange = new Emitter<IColorTheme>({ leakWarningThreshold: 400 });
127

128
		this.currentColorTheme = ColorThemeData.createUnloadedTheme('');
M
Martin Aeschlimann 已提交
129
		this.currentIconTheme = FileIconThemeData.createUnloadedTheme('');
130

131 132 133
		// 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
134
		let themeData: ColorThemeData | undefined = undefined;
135
		let persistedThemeData = this.storageService.get(PERSISTED_THEME_STORAGE_KEY, StorageScope.GLOBAL);
136
		if (persistedThemeData) {
137
			themeData = ColorThemeData.fromStorageData(persistedThemeData);
138
		}
139
		let containerBaseTheme = this.getBaseThemeFromContainer();
M
Martin Aeschlimann 已提交
140
		if (!themeData || themeData.baseTheme !== containerBaseTheme) {
141
			themeData = ColorThemeData.createUnloadedTheme(containerBaseTheme);
142
		}
143
		themeData.setCustomColors(this.colorCustomizations);
144
		themeData.setCustomTokenColors(this.tokenColorCustomizations);
145
		themeData.setCustomTokenStyleRules(this.tokenStylesCustomizations);
146
		this.updateDynamicCSSRules(themeData);
147
		this.applyTheme(themeData, undefined, true);
E
Erich Gamma 已提交
148

149
		let persistedIconThemeData = this.storageService.get(PERSISTED_ICON_THEME_STORAGE_KEY, StorageScope.GLOBAL);
150
		if (persistedIconThemeData) {
151
			const iconData = FileIconThemeData.fromStorageData(persistedIconThemeData);
152 153 154
			if (iconData) {
				_applyIconTheme(iconData, () => {
					this.doSetFileIconTheme(iconData);
M
Martin Aeschlimann 已提交
155
					return Promise.resolve(iconData);
156 157 158 159
				});
			}
		}

160 161
		this.initialize().then(undefined, errors.onUnexpectedError).then(_ => {
			this.installConfigurationListener();
M
polish  
Martin Aeschlimann 已提交
162
			this.installPreferredSchemeListener();
163
		});
164

165 166
		let prevColorId: string | undefined = undefined;

167
		// update settings schema setting for theme specific settings
168
		this.colorThemeStore.onDidChange(async event => {
169
			// updates enum for the 'workbench.colorTheme` setting
170 171
			colorThemeSettingEnum.splice(0, colorThemeSettingEnum.length, ...event.themes.map(t => t.settingsId));
			colorThemeSettingEnumDescriptions.splice(0, colorThemeSettingEnumDescriptions.length, ...event.themes.map(t => t.description || ''));
172

173 174
			const themeSpecificWorkbenchColors: IJSONSchema = { properties: {} };
			const themeSpecificTokenColors: IJSONSchema = { properties: {} };
175
			const themeSpecificTokenStyling: IJSONSchema = { properties: {} };
A
Alex 已提交
176

177 178
			const workbenchColors = { $ref: workbenchColorsSchemaId, additionalProperties: false };
			const tokenColors = { properties: tokenColorSchema.properties, additionalProperties: false };
179
			const tokenStyling = { $ref: tokenStylingSchemaId, additionalProperties: false };
180
			for (let t of event.themes) {
181
				// add theme specific color customization ("[Abyss]":{ ... })
182
				const themeId = `[${t.settingsId}]`;
183 184
				themeSpecificWorkbenchColors.properties![themeId] = workbenchColors;
				themeSpecificTokenColors.properties![themeId] = tokenColors;
185
				themeSpecificTokenStyling.properties![themeId] = tokenStyling;
186
			}
A
Alex 已提交
187

188 189
			colorCustomizationsSchema.allOf![1] = themeSpecificWorkbenchColors;
			tokenColorCustomizationSchema.allOf![1] = themeSpecificTokenColors;
190
			experimentalTokenStylingCustomizationSchema.allOf![1] = themeSpecificTokenStyling;
191

192
			configurationRegistry.notifyConfigurationSchemaUpdated(themeSettingsConfiguration, tokenColorCustomizationConfiguration);
193

194
			if (this.currentColorTheme.isLoaded) {
195 196 197
				const themeData = await this.colorThemeStore.findThemeData(this.currentColorTheme.id);
				if (!themeData) {
					// current theme is no longer available
198
					prevColorId = this.currentColorTheme.id;
199
					this.setColorTheme(DEFAULT_THEME_ID, 'auto');
200
				} else {
201
					if (this.currentColorTheme.id === DEFAULT_THEME_ID && !types.isUndefined(prevColorId) && await this.colorThemeStore.findThemeData(prevColorId)) {
202 203 204
						// restore color
						this.setColorTheme(prevColorId, 'auto');
						prevColorId = undefined;
205 206
					} else {
						this.reloadCurrentColorTheme();
207
					}
208
				}
209
			}
210
		});
211 212 213 214

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

			if (this.currentIconTheme.isLoaded) {
219 220 221
				const theme = await this.iconThemeStore.findThemeData(this.currentIconTheme.id);
				if (!theme) {
					// current theme is no longer available
222
					prevFileIconId = this.currentIconTheme.id;
223
					this.setFileIconTheme(DEFAULT_ICON_THEME_ID, 'auto');
224
				} else {
225
					// restore color
226
					if (this.currentIconTheme.id === DEFAULT_ICON_THEME_ID && !types.isUndefined(prevFileIconId) && await this.iconThemeStore.findThemeData(prevFileIconId)) {
227 228
						this.setFileIconTheme(prevFileIconId, 'auto');
						prevFileIconId = undefined;
229 230
					} else {
						this.reloadCurrentFileIconTheme();
231
					}
232
				}
233
			}
234
		});
M
Martin Aeschlimann 已提交
235 236

		this.fileService.onFileChanges(async e => {
237
			if (this.watchedColorThemeLocation && this.currentColorTheme && e.contains(this.watchedColorThemeLocation, FileChangeType.UPDATED)) {
238
				this.reloadCurrentColorTheme();
M
Martin Aeschlimann 已提交
239
			}
240
			if (this.watchedIconThemeLocation && this.currentIconTheme && e.contains(this.watchedIconThemeLocation, FileChangeType.UPDATED)) {
241
				this.reloadCurrentFileIconTheme();
M
Martin Aeschlimann 已提交
242 243
			}
		});
A
Alex Dima 已提交
244 245
	}

M
Martin Aeschlimann 已提交
246
	public get onDidColorThemeChange(): Event<IColorTheme> {
M
Martin Aeschlimann 已提交
247
		return this.onColorThemeChange.event;
E
Erich Gamma 已提交
248 249
	}

M
Martin Aeschlimann 已提交
250 251 252 253
	public get onDidFileIconThemeChange(): Event<IFileIconTheme> {
		return this.onFileIconThemeChange.event;
	}

254 255 256 257
	public get onIconThemeChange(): Event<IFileIconTheme> {
		return this.onFileIconThemeChange.event;
	}

258 259
	public get onThemeChange(): Event<ITheme> {
		return this.onColorThemeChange.event;
260 261
	}

262
	private initialize(): Promise<[IColorTheme | null, IFileIconTheme | null]> {
M
polish  
Martin Aeschlimann 已提交
263 264
		const colorThemeSetting = this.configurationService.getValue<string>(COLOR_THEME_SETTING);
		const iconThemeSetting = this.configurationService.getValue<string | null>(ICON_THEME_SETTING);
265

266
		const extDevLocs = this.environmentService.extensionDevelopmentLocationURI;
M
Marvin Heilemann 已提交
267

M
polish  
Martin Aeschlimann 已提交
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
		const initializeColorTheme = async () => {
			if (extDevLocs && extDevLocs.length > 0) { // in dev mode, switch to a theme provided by the extension under dev.
				const devThemes = await this.colorThemeStore.findThemeDataByParentLocation(extDevLocs[0]);
				if (devThemes.length) {
					return this.setColorTheme(devThemes[0].id, ConfigurationTarget.MEMORY);
				}
			}
			let theme = await this.colorThemeStore.findThemeDataBySettingsId(colorThemeSetting, DEFAULT_THEME_ID);
			const preferredType = this.getPreferredColorScheme();
			let settingsTarget: undefined | 'auto' = undefined;
			if (preferredType && theme && theme.type !== preferredType) {
				const preferedTheme = await this.getPreferredColorTheme(preferredType);
				if (preferedTheme) {
					theme = preferedTheme;
					settingsTarget = 'auto';
				}
			}
			return this.setColorTheme(theme && theme.id, settingsTarget);
		};
M
Marvin Heilemann 已提交
287

M
polish  
Martin Aeschlimann 已提交
288 289 290 291 292 293
		const initializeIconTheme = async () => {
			if (extDevLocs && extDevLocs.length > 0) { // in dev mode, switch to a theme provided by the extension under dev.
				const devThemes = await this.iconThemeStore.findThemeDataByParentLocation(extDevLocs[0]);
				if (devThemes.length) {
					return this.setFileIconTheme(devThemes[0].id, ConfigurationTarget.MEMORY);
				}
M
Marvin Heilemann 已提交
294
			}
M
polish  
Martin Aeschlimann 已提交
295 296 297 298 299
			const theme = await this.iconThemeStore.findThemeBySettingsId(iconThemeSetting);
			return this.setFileIconTheme(theme ? theme.id : DEFAULT_ICON_THEME_ID, undefined);
		};

		return Promise.all([initializeColorTheme(), initializeIconTheme()]);
M
Marvin Heilemann 已提交
300 301
	}

302
	private installConfigurationListener() {
303
		this.configurationService.onDidChangeConfiguration(e => {
304 305 306
			if (e.affectsConfiguration(COLOR_THEME_SETTING)) {
				let colorThemeSetting = this.configurationService.getValue<string>(COLOR_THEME_SETTING);
				if (colorThemeSetting !== this.currentColorTheme.settingsId) {
M
Marvin Heilemann 已提交
307 308 309 310 311
					this.colorThemeStore.findThemeDataBySettingsId(colorThemeSetting, DEFAULT_THEME_ID).then(theme => {
						if (theme) {
							this.setColorTheme(theme.id, undefined);
						}
					});
M
Marvin Heilemann 已提交
312 313
				}
			}
M
polish  
Martin Aeschlimann 已提交
314 315
			if (e.affectsConfiguration(DETECT_COLOR_SCHEME_SETTING)) {
				let autoSwitchColorTheme = this.configurationService.getValue<boolean>(DETECT_COLOR_SCHEME_SETTING);
M
Marvin Heilemann 已提交
316
				if (autoSwitchColorTheme) {
M
polish  
Martin Aeschlimann 已提交
317
					this.preferredSchemeUpdated();
318
				}
319
			}
320
			if (e.affectsConfiguration(ICON_THEME_SETTING)) {
321
				let iconThemeSetting = this.configurationService.getValue<string | null>(ICON_THEME_SETTING);
322 323
				if (iconThemeSetting !== this.currentIconTheme.settingsId) {
					this.iconThemeStore.findThemeBySettingsId(iconThemeSetting).then(theme => {
324
						this.setFileIconTheme(theme ? theme.id : DEFAULT_ICON_THEME_ID, undefined);
325 326 327 328 329 330 331 332 333 334 335 336 337
					});
				}
			}
			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;
				}
338 339 340 341
				if (e.affectsConfiguration(CUSTOM_EDITOR_TOKENSTYLES_SETTING)) {
					this.currentColorTheme.setCustomTokenStyleRules(this.tokenStylesCustomizations);
					hasColorChanges = true;
				}
342 343 344 345
				if (hasColorChanges) {
					this.updateDynamicCSSRules(this.currentColorTheme);
					this.onColorThemeChange.fire(this.currentColorTheme);
				}
346 347 348 349
			}
		});
	}

M
polish  
Martin Aeschlimann 已提交
350 351 352 353 354 355 356 357 358 359 360 361 362
	// preferred scheme handling

	private installPreferredSchemeListener() {
		window.matchMedia('(prefers-color-scheme: dark)').addListener(async () => this.preferredSchemeUpdated());
	}

	private async preferredSchemeUpdated() {
		const scheme = this.getPreferredColorScheme();
		if (scheme && this.currentColorTheme.type !== scheme) {
			const preferedTheme = await this.getPreferredColorTheme(scheme);
			if (preferedTheme) {
				return this.setColorTheme(preferedTheme.id, 'auto');
			}
M
Marvin Heilemann 已提交
363
		}
M
polish  
Martin Aeschlimann 已提交
364
		return undefined;
M
Marvin Heilemann 已提交
365 366
	}

M
polish  
Martin Aeschlimann 已提交
367 368 369 370
	private getPreferredColorScheme(): ThemeType | undefined {
		let detectHCThemeSetting = this.configurationService.getValue<boolean>(DETECT_HC_SETTING);
		if (this.environmentService.configuration.highContrast && detectHCThemeSetting) {
			return HIGH_CONTRAST;
M
Marvin Heilemann 已提交
371
		}
M
polish  
Martin Aeschlimann 已提交
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
		if (this.configurationService.getValue<boolean>(DETECT_COLOR_SCHEME_SETTING)) {
			if (window.matchMedia(`(prefers-color-scheme: light)`).matches) {
				return LIGHT;
			} else if (window.matchMedia(`(prefers-color-scheme: dark)`).matches) {
				return DARK;
			}
		}
		return undefined;
	}

	private getPreferredColorTheme(type: ThemeType): Promise<ColorThemeData | undefined> {
		const settingId = type === DARK ? PREFERRED_DARK_THEME_SETTING : type === LIGHT ? PREFERRED_LIGHT_THEME_SETTING : PREFERRED_HC_THEME_SETTING;
		const themeSettingId = this.configurationService.getValue<string>(settingId);
		if (themeSettingId) {
			return this.colorThemeStore.findThemeDataBySettingsId(themeSettingId, undefined);
		}
		return Promise.resolve(undefined);
M
Marvin Heilemann 已提交
389 390
	}

391 392 393 394
	public getColorTheme(): IColorTheme {
		return this.currentColorTheme;
	}

395 396
	public getColorThemes(): Promise<IColorTheme[]> {
		return this.colorThemeStore.getColorThemes();
397 398
	}

399 400 401 402
	public getTheme(): ITheme {
		return this.getColorTheme();
	}

403
	public setColorTheme(themeId: string | undefined, settingsTarget: ConfigurationTarget | undefined | 'auto'): Promise<IColorTheme | null> {
M
Martin Aeschlimann 已提交
404
		if (!themeId) {
M
Martin Aeschlimann 已提交
405
			return Promise.resolve(null);
M
Martin Aeschlimann 已提交
406
		}
M
Martin Aeschlimann 已提交
407
		if (themeId === this.currentColorTheme.id && this.currentColorTheme.isLoaded) {
408
			return this.writeColorThemeConfiguration(settingsTarget);
M
Martin Aeschlimann 已提交
409 410 411 412
		}

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

M
Marvin Heilemann 已提交
413 414
		return this.colorThemeStore.findThemeData(themeId, DEFAULT_THEME_ID).then(themeData => {
			if (!themeData) {
415 416
				return null;
			}
M
Marvin Heilemann 已提交
417
			this.configurationService.updateValue(COLOR_THEME_SETTING, themeData.settingsId);
418 419 420 421 422
			return themeData.ensureLoaded(this.extensionResourceLoaderService).then(_ => {
				if (themeId === this.currentColorTheme.id && !this.currentColorTheme.isLoaded && this.currentColorTheme.hasEqualData(themeData)) {
					this.currentColorTheme.clearCaches();
					// the loaded theme is identical to the perisisted theme. Don't need to send an event.
					this.currentColorTheme = themeData;
423
					themeData.setCustomColors(this.colorCustomizations);
C
Cody Hoover 已提交
424
					themeData.setCustomTokenColors(this.tokenColorCustomizations);
425
					themeData.setCustomTokenStyleRules(this.tokenStylesCustomizations);
426
					return Promise.resolve(themeData);
427
				}
428 429 430 431 432 433 434 435
				themeData.setCustomColors(this.colorCustomizations);
				themeData.setCustomTokenColors(this.tokenColorCustomizations);
				themeData.setCustomTokenStyleRules(this.tokenStylesCustomizations);
				this.updateDynamicCSSRules(themeData);
				return this.applyTheme(themeData, settingsTarget);
			}, error => {
				return Promise.reject(new Error(nls.localize('error.cannotloadtheme', "Unable to load {0}: {1}", themeData.location!.toString(), error.message)));
			});
M
Martin Aeschlimann 已提交
436 437 438
		});
	}

439
	private async reloadCurrentColorTheme() {
440
		await this.currentColorTheme.reload(this.extensionResourceLoaderService);
441 442
		this.currentColorTheme.setCustomColors(this.colorCustomizations);
		this.currentColorTheme.setCustomTokenColors(this.tokenColorCustomizations);
443
		this.currentColorTheme.setCustomTokenStyleRules(this.tokenStylesCustomizations);
444 445 446 447
		this.updateDynamicCSSRules(this.currentColorTheme);
		this.applyTheme(this.currentColorTheme, undefined, false);
	}

448 449 450
	public restoreColorTheme() {
		let colorThemeSetting = this.configurationService.getValue<string>(COLOR_THEME_SETTING);
		if (colorThemeSetting !== this.currentColorTheme.settingsId) {
M
Marvin Heilemann 已提交
451 452 453 454 455
			this.colorThemeStore.findThemeDataBySettingsId(colorThemeSetting, DEFAULT_THEME_ID).then(theme => {
				if (theme) {
					this.setColorTheme(theme.id, undefined);
				}
			});
456 457 458
		}
	}

459
	private updateDynamicCSSRules(themeData: ITheme) {
460 461
		const cssRules = new Set<string>();
		const ruleCollector = {
462
			addRule: (rule: string) => {
463 464
				if (!cssRules.has(rule)) {
					cssRules.add(rule);
465 466 467
				}
			}
		};
468
		themingRegistry.getThemingParticipants().forEach(p => p(themeData, ruleCollector, this.environmentService));
469
		_applyRules([...cssRules].join('\n'), colorThemeRulesClassName);
470 471
	}

472
	private applyTheme(newTheme: ColorThemeData, settingsTarget: ConfigurationTarget | undefined | 'auto', silent = false): Promise<IColorTheme | null> {
473
		if (this.currentColorTheme.id) {
474 475 476
			removeClasses(this.container, this.currentColorTheme.id);
		} else {
			removeClasses(this.container, VS_DARK_THEME, VS_LIGHT_THEME, VS_HC_THEME);
477
		}
478 479
		addClasses(this.container, newTheme.id);

480
		this.currentColorTheme.clearCaches();
481
		this.currentColorTheme = newTheme;
482
		if (!this.themingParticipantChangeListener) {
483
			this.themingParticipantChangeListener = themingRegistry.onThemingParticipantAdded(_ => this.updateDynamicCSSRules(this.currentColorTheme));
M
Martin Aeschlimann 已提交
484 485 486
		}

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

490 491
			if (newTheme.location && (newTheme.watch || !!this.environmentService.extensionDevelopmentLocationURI)) {
				this.watchedColorThemeLocation = newTheme.location;
492
				this.watchedColorThemeDisposable = this.fileService.watch(newTheme.location);
M
Martin Aeschlimann 已提交
493
			}
494
		}
495

496 497
		this.sendTelemetry(newTheme.id, newTheme.extensionData, 'color');

498
		if (silent) {
M
Martin Aeschlimann 已提交
499
			return Promise.resolve(null);
500 501 502 503 504
		}

		this.onColorThemeChange.fire(this.currentColorTheme);

		// remember theme data for a quick restore
505 506 507
		if (newTheme.isLoaded) {
			this.storageService.store(PERSISTED_THEME_STORAGE_KEY, newTheme.toStorageData(), StorageScope.GLOBAL);
		}
508 509

		return this.writeColorThemeConfiguration(settingsTarget);
510
	}
511

512
	private writeColorThemeConfiguration(settingsTarget: ConfigurationTarget | undefined | 'auto'): Promise<IColorTheme> {
513
		if (!types.isUndefinedOrNull(settingsTarget)) {
514
			return this.writeConfiguration(COLOR_THEME_SETTING, this.currentColorTheme.settingsId, settingsTarget).then(_ => this.currentColorTheme);
M
Martin Aeschlimann 已提交
515
		}
M
Martin Aeschlimann 已提交
516
		return Promise.resolve(this.currentColorTheme);
M
Martin Aeschlimann 已提交
517 518
	}

K
katainaka0503 已提交
519
	private themeExtensionsActivated = new Map<string, boolean>();
520
	private sendTelemetry(themeId: string, themeData: ExtensionData | undefined, themeType: string) {
521 522 523
		if (themeData) {
			let key = themeType + themeData.extensionId;
			if (!this.themeExtensionsActivated.get(key)) {
524
				type ActivatePluginClassification = {
525 526 527 528 529
					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' };
530 531 532 533 534 535 536 537 538
				};
				type ActivatePluginEvent = {
					id: string;
					name: string;
					isBuiltin: boolean;
					publisherDisplayName: string;
					themeId: string;
				};
				this.telemetryService.publicLog2<ActivatePluginEvent, ActivatePluginClassification>('activatePlugin', {
539 540 541
					id: themeData.extensionId,
					name: themeData.extensionName,
					isBuiltin: themeData.extensionIsBuiltin,
542
					publisherDisplayName: themeData.extensionPublisher,
543 544 545 546
					themeId: themeId
				});
				this.themeExtensionsActivated.set(key, true);
			}
547 548
		}
	}
M
Martin Aeschlimann 已提交
549

550 551
	public getFileIconThemes(): Promise<IFileIconTheme[]> {
		return this.iconThemeStore.getFileIconThemes();
M
Martin Aeschlimann 已提交
552 553
	}

554
	public getFileIconTheme() {
M
Martin Aeschlimann 已提交
555
		return this.currentIconTheme;
556 557
	}

558 559 560 561
	public getIconTheme() {
		return this.currentIconTheme;
	}

562
	public setFileIconTheme(iconTheme: string | undefined, settingsTarget: ConfigurationTarget | undefined | 'auto'): Promise<IFileIconTheme> {
563
		iconTheme = iconTheme || '';
M
Martin Aeschlimann 已提交
564
		if (iconTheme === this.currentIconTheme.id && this.currentIconTheme.isLoaded) {
M
Martin Aeschlimann 已提交
565
			return this.writeFileIconConfiguration(settingsTarget);
566
		}
567
		let onApply = (newIconTheme: FileIconThemeData) => {
568 569 570
			this.doSetFileIconTheme(newIconTheme);

			// remember theme data for a quick restore
B
Benjamin Pasero 已提交
571
			if (newIconTheme.isLoaded && (!newIconTheme.location || !getRemoteAuthority(newIconTheme.location))) {
572 573
				this.storageService.store(PERSISTED_ICON_THEME_STORAGE_KEY, newIconTheme.toStorageData(), StorageScope.GLOBAL);
			}
M
Martin Aeschlimann 已提交
574 575

			return this.writeFileIconConfiguration(settingsTarget);
576 577
		};

578 579
		return this.iconThemeStore.findThemeData(iconTheme).then(data => {
			const iconThemeData = data || FileIconThemeData.noIconTheme();
A
Alex Dima 已提交
580
			return iconThemeData.ensureLoaded(this.fileService).then(_ => {
581 582
				return _applyIconTheme(iconThemeData, onApply);
			});
M
Martin Aeschlimann 已提交
583 584
		});
	}
M
Martin Aeschlimann 已提交
585

586 587 588 589 590 591 592 593
	private async reloadCurrentFileIconTheme() {
		await this.currentIconTheme.reload(this.fileService);
		_applyIconTheme(this.currentIconTheme, () => {
			this.doSetFileIconTheme(this.currentIconTheme);
			return Promise.resolve(this.currentIconTheme);
		});
	}

594 595 596 597 598 599 600 601 602 603 604
	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);
				}
			});
		}
	}

605
	private doSetFileIconTheme(iconThemeData: FileIconThemeData): void {
606
		this.currentIconTheme = iconThemeData;
607

608 609 610 611
		if (iconThemeData.id) {
			addClasses(this.container, fileIconsEnabledClass);
		} else {
			removeClasses(this.container, fileIconsEnabledClass);
612
		}
M
Martin Aeschlimann 已提交
613 614

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

618
			if (iconThemeData.location && (iconThemeData.watch || !!this.environmentService.extensionDevelopmentLocationURI)) {
619
				this.watchedIconThemeLocation = iconThemeData.location;
620
				this.watchedIconThemeDisposable = this.fileService.watch(iconThemeData.location);
M
Martin Aeschlimann 已提交
621 622 623
			}
		}

624
		if (iconThemeData.id) {
625 626 627
			this.sendTelemetry(iconThemeData.id, iconThemeData.extensionData, 'fileIcon');
		}
		this.onFileIconThemeChange.fire(this.currentIconTheme);
628

629 630
	}

631
	private writeFileIconConfiguration(settingsTarget: ConfigurationTarget | undefined | 'auto'): Promise<IFileIconTheme> {
632
		if (!types.isUndefinedOrNull(settingsTarget)) {
633
			return this.writeConfiguration(ICON_THEME_SETTING, this.currentIconTheme.settingsId, settingsTarget).then(_ => this.currentIconTheme);
M
Martin Aeschlimann 已提交
634
		}
M
Martin Aeschlimann 已提交
635
		return Promise.resolve(this.currentIconTheme);
M
Martin Aeschlimann 已提交
636 637
	}

638 639 640
	public writeConfiguration(key: string, value: any, settingsTarget: ConfigurationTarget | 'auto'): Promise<void> {
		let settings = this.configurationService.inspect(key);
		if (settingsTarget === 'auto') {
S
rename  
Sandeep Somavarapu 已提交
641
			if (!types.isUndefined(settings.workspaceFolderValue)) {
642
				settingsTarget = ConfigurationTarget.WORKSPACE_FOLDER;
S
rename  
Sandeep Somavarapu 已提交
643
			} else if (!types.isUndefined(settings.workspaceValue)) {
644 645 646 647
				settingsTarget = ConfigurationTarget.WORKSPACE;
			} else {
				settingsTarget = ConfigurationTarget.USER;
			}
648
		}
649 650

		if (settingsTarget === ConfigurationTarget.USER) {
S
rename  
Sandeep Somavarapu 已提交
651
			if (value === settings.userValue) {
652
				return Promise.resolve(undefined); // nothing to do
S
rename  
Sandeep Somavarapu 已提交
653 654
			} else if (value === settings.defaultValue) {
				if (types.isUndefined(settings.userValue)) {
655 656 657 658
					return Promise.resolve(undefined); // nothing to do
				}
				value = undefined; // remove configuration from user settings
			}
659
		} else if (settingsTarget === ConfigurationTarget.WORKSPACE || settingsTarget === ConfigurationTarget.WORKSPACE_FOLDER) {
660 661 662 663 664
			if (value === settings.value) {
				return Promise.resolve(undefined); // nothing to do
			}
		}
		return this.configurationService.updateValue(key, value, settingsTarget);
665
	}
666 667

	private getBaseThemeFromContainer() {
668 669 670 671
		for (let i = this.container.classList.length - 1; i >= 0; i--) {
			const item = this.container.classList.item(i);
			if (item === VS_LIGHT_THEME || item === VS_DARK_THEME || item === VS_HC_THEME) {
				return item;
672 673 674 675
			}
		}
		return VS_DARK_THEME;
	}
E
Erich Gamma 已提交
676 677
}

678
function _applyIconTheme(data: FileIconThemeData, onApply: (theme: FileIconThemeData) => Promise<IFileIconTheme>): Promise<IFileIconTheme> {
679
	_applyRules(data.styleSheetContent!, iconThemeRulesClassName);
680
	return onApply(data);
M
Martin Aeschlimann 已提交
681 682 683 684
}

function _applyRules(styleSheetContent: string, rulesClassName: string) {
	let themeStyles = document.head.getElementsByClassName(rulesClassName);
E
Erich Gamma 已提交
685
	if (themeStyles.length === 0) {
B
Benjamin Pasero 已提交
686 687
		let elStyle = document.createElement('style');
		elStyle.type = 'text/css';
M
Martin Aeschlimann 已提交
688
		elStyle.className = rulesClassName;
E
Erich Gamma 已提交
689 690 691
		elStyle.innerHTML = styleSheetContent;
		document.head.appendChild(elStyle);
	} else {
B
Benjamin Pasero 已提交
692
		(<HTMLStyleElement>themeStyles[0]).innerHTML = styleSheetContent;
E
Erich Gamma 已提交
693 694 695
	}
}

696 697
registerColorThemeSchemas();
registerFileIconThemeSchemas();
M
Martin Aeschlimann 已提交
698

699
// Configuration: Themes
M
Martin Aeschlimann 已提交
700
const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration);
701

702 703 704
const colorThemeSettingEnum: string[] = [];
const colorThemeSettingEnumDescriptions: string[] = [];

705
const colorThemeSettingSchema: IConfigurationPropertySchema = {
706
	type: 'string',
707
	description: nls.localize('colorTheme', "Specifies the color theme used in the workbench."),
708
	default: DEFAULT_THEME_SETTING_VALUE,
709 710
	enum: colorThemeSettingEnum,
	enumDescriptions: colorThemeSettingEnumDescriptions,
711
	errorMessage: nls.localize('colorThemeError', "Theme is unknown or not installed."),
712
};
M
polish  
Martin Aeschlimann 已提交
713
const preferredDarkThemeSettingSchema: IConfigurationPropertySchema = {
M
Marvin Heilemann 已提交
714
	type: 'string',
M
polish  
Martin Aeschlimann 已提交
715
	description: nls.localize('preferredDarkColorTheme', 'Specifies the preferred color theme for dark OS appearance when \'{0}\' is enabled.', DETECT_COLOR_SCHEME_SETTING),
M
Marvin Heilemann 已提交
716
	default: DEFAULT_THEME_DARK_SETTING_VALUE,
717 718 719
	enum: colorThemeSettingEnum,
	enumDescriptions: colorThemeSettingEnumDescriptions,
	errorMessage: nls.localize('colorThemeError', "Theme is unknown or not installed."),
M
Marvin Heilemann 已提交
720
};
M
polish  
Martin Aeschlimann 已提交
721
const preferredLightThemeSettingSchema: IConfigurationPropertySchema = {
M
Marvin Heilemann 已提交
722
	type: 'string',
M
polish  
Martin Aeschlimann 已提交
723
	description: nls.localize('preferredLightColorTheme', 'Specifies the preferred color theme for light OS appearance when \'{0}\' is enabled.', DETECT_COLOR_SCHEME_SETTING),
M
Marvin Heilemann 已提交
724
	default: DEFAULT_THEME_LIGHT_SETTING_VALUE,
725 726 727
	enum: colorThemeSettingEnum,
	enumDescriptions: colorThemeSettingEnumDescriptions,
	errorMessage: nls.localize('colorThemeError', "Theme is unknown or not installed."),
M
Marvin Heilemann 已提交
728
};
M
polish  
Martin Aeschlimann 已提交
729 730 731 732
const preferredHCThemeSettingSchema: IConfigurationPropertySchema = {
	type: 'string',
	description: nls.localize('preferredHCColorTheme', 'Specifies the preferred color theme used in high contrast mode when \'{0}\' is enabled.', DETECT_HC_SETTING),
	default: DEFAULT_THEME_HC_SETTING_VALUE,
733 734 735
	enum: colorThemeSettingEnum,
	enumDescriptions: colorThemeSettingEnumDescriptions,
	errorMessage: nls.localize('colorThemeError', "Theme is unknown or not installed."),
M
polish  
Martin Aeschlimann 已提交
736 737
};
const detectColorSchemeSettingSchema: IConfigurationPropertySchema = {
M
Marvin Heilemann 已提交
738
	type: 'boolean',
M
polish  
Martin Aeschlimann 已提交
739 740
	description: nls.localize('detectColorScheme', 'If set, use the prefered color theme based on the OS appearance.'),
	default: true
M
Marvin Heilemann 已提交
741
};
742

743
const iconThemeSettingSchema: IConfigurationPropertySchema = {
744
	type: ['string', 'null'],
745
	default: DEFAULT_ICON_THEME_SETTING_VALUE,
746
	description: nls.localize('iconTheme', "Specifies the icon theme used in the workbench or 'null' to not show any file icons."),
747 748
	enum: [null],
	enumDescriptions: [nls.localize('noIconThemeDesc', 'No file icons')],
749
	errorMessage: nls.localize('iconThemeError', "File icon theme is unknown or not installed.")
750
};
751
const colorCustomizationsSchema: IConfigurationPropertySchema = {
752
	type: 'object',
753
	description: nls.localize('workbenchColors', "Overrides colors from the currently selected color theme."),
754
	allOf: [{ $ref: workbenchColorsSchemaId }],
755
	default: {},
756 757
	defaultSnippets: [{
		body: {
758
		}
759
	}]
760 761
};

762
const themeSettingsConfiguration: IConfigurationNode = {
763 764 765 766
	id: 'workbench',
	order: 7.1,
	type: 'object',
	properties: {
767
		[COLOR_THEME_SETTING]: colorThemeSettingSchema,
M
polish  
Martin Aeschlimann 已提交
768 769 770 771
		[PREFERRED_DARK_THEME_SETTING]: preferredDarkThemeSettingSchema,
		[PREFERRED_LIGHT_THEME_SETTING]: preferredLightThemeSettingSchema,
		[PREFERRED_HC_THEME_SETTING]: preferredHCThemeSettingSchema,
		[DETECT_COLOR_SCHEME_SETTING]: detectColorSchemeSettingSchema,
772
		[ICON_THEME_SETTING]: iconThemeSettingSchema,
773
		[CUSTOM_WORKBENCH_COLORS_SETTING]: colorCustomizationsSchema
M
Martin Aeschlimann 已提交
774
	}
775 776
};
configurationRegistry.registerConfiguration(themeSettingsConfiguration);
777

778
function tokenGroupSettings(description: string): IJSONSchema {
779 780
	return {
		description,
781
		$ref: textmateColorGroupSchemaId
782
	};
783
}
784

785 786
const tokenColorSchema: IJSONSchema = {
	properties: {
787 788 789 790 791 792 793
		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.")),
794
		textMateRules: {
795
			description: nls.localize('editorColors.textMateRules', 'Sets colors and styles using textmate theming rules (advanced).'),
796 797 798
			$ref: textmateColorsSchemaId
		}
	}
799
};
800
const tokenColorCustomizationSchema: IConfigurationPropertySchema = {
801
	description: nls.localize('editorColors', "Overrides editor colors and font style from the currently selected color theme."),
802
	default: {},
803
	allOf: [tokenColorSchema]
804
};
805
const experimentalTokenStylingCustomizationSchema: IConfigurationPropertySchema = {
806
	description: nls.localize('editorColorsTokenStyles', "Overrides token color and styles from the currently selected color theme."),
807 808 809
	default: {},
	allOf: [{ $ref: tokenStylingSchemaId }]
};
810
const tokenColorCustomizationConfiguration: IConfigurationNode = {
811 812 813 814
	id: 'editor',
	order: 7.2,
	type: 'object',
	properties: {
815 816
		[CUSTOM_EDITOR_COLORS_SETTING]: tokenColorCustomizationSchema,
		[CUSTOM_EDITOR_TOKENSTYLES_SETTING]: experimentalTokenStylingCustomizationSchema
817
	}
818
};
819
configurationRegistry.registerConfiguration(tokenColorCustomizationConfiguration);
820

M
polish  
Martin Aeschlimann 已提交
821
registerSingleton(IWorkbenchThemeService, WorkbenchThemeService);