workbenchThemeService.ts 28.5 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';
B
Benjamin Pasero 已提交
24
import { IWindowService } from 'vs/platform/windows/common/windows';
25
import { removeClasses, addClasses } from 'vs/base/browser/dom';
26
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
27
import { IFileService, FileChangeType } from 'vs/platform/files/common/files';
M
Martin Aeschlimann 已提交
28 29
import { URI } from 'vs/base/common/uri';
import * as resources from 'vs/base/common/resources';
30 31 32
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';
33
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
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 48
const fileIconsEnabledClass = 'file-icons-enabled';

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

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

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

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

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

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

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

86
	private themingParticipantChangeListener: IDisposable;
87

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

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

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

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

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

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

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

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

146 147
		let prevColorId: string | undefined = undefined;

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

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

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

166 167
			colorCustomizationsSchema.allOf![1] = themeSpecificWorkbenchColors;
			tokenColorCustomizationSchema.allOf![1] = themeSpecificTokenColors;
168

169
			configurationRegistry.notifyConfigurationSchemaUpdated(themeSettingsConfiguration, tokenColorCustomizationConfiguration);
170

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

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

			if (this.currentIconTheme.isLoaded) {
194 195 196
				const theme = await this.iconThemeStore.findThemeData(this.currentIconTheme.id);
				if (!theme) {
					// current theme is no longer available
197
					prevFileIconId = this.currentIconTheme.id;
198
					this.setFileIconTheme(DEFAULT_ICON_THEME_SETTING_VALUE, 'auto');
199
				} else {
200 201 202 203
					// 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;
204
					}
205
				}
206
			}
207
		});
M
Martin Aeschlimann 已提交
208 209 210 211 212 213 214

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

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

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

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

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

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

		let colorThemeSetting: string;
		if (this.windowService.getConfiguration().highContrast && detectHCThemeSetting) {
			colorThemeSetting = HC_THEME_ID;
		} else {
			colorThemeSetting = this.configurationService.getValue<string>(COLOR_THEME_SETTING);
		}
249

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

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

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

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

323 324 325 326
	public getColorTheme(): IColorTheme {
		return this.currentColorTheme;
	}

327 328
	public getColorThemes(): Promise<IColorTheme[]> {
		return this.colorThemeStore.getColorThemes();
329 330
	}

331 332 333 334
	public getTheme(): ITheme {
		return this.getColorTheme();
	}

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

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

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

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

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

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

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

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

418 419
		this.sendTelemetry(newTheme.id, newTheme.extensionData, 'color');

420
		if (silent) {
M
Martin Aeschlimann 已提交
421
			return Promise.resolve(null);
422 423 424 425 426
		}

		this.onColorThemeChange.fire(this.currentColorTheme);

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

		return this.writeColorThemeConfiguration(settingsTarget);
432
	}
433

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

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

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

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

475 476 477 478
	public getIconTheme() {
		return this.currentIconTheme;
	}

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

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

			return this.writeFileIconConfiguration(settingsTarget);
493 494
		};

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

503 504 505 506 507 508 509 510 511 512 513
	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);
				}
			});
		}
	}

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

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

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

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

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

	}

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

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

		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);
576
	}
577 578 579 580 581 582 583 584 585 586 587 588

	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 已提交
589 590
}

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

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

609 610
registerColorThemeSchemas();
registerFileIconThemeSchemas();
M
Martin Aeschlimann 已提交
611

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

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

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

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

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

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

701
registerSingleton(IWorkbenchThemeService, WorkbenchThemeService);