settingsEditor2.ts 27.8 KB
Newer Older
R
Rob Lourens 已提交
1 2 3 4 5 6 7 8 9 10 11
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import * as DOM from 'vs/base/browser/dom';
import { InputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { IDelegate, IRenderer } from 'vs/base/browser/ui/list/list';
import { List } from 'vs/base/browser/ui/list/listWidget';
import { SelectBox } from 'vs/base/browser/ui/selectBox/selectBox';
import { IAction } from 'vs/base/common/actions';
R
Rob Lourens 已提交
12
import { Delayer, ThrottledDelayer } from 'vs/base/common/async';
R
Rob Lourens 已提交
13 14
import { Color } from 'vs/base/common/color';
import { Emitter, Event } from 'vs/base/common/event';
15
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
R
Rob Lourens 已提交
16 17 18 19 20 21 22 23 24 25
import { TPromise } from 'vs/base/common/winjs.base';
import 'vs/css!./media/settingsEditor2';
import { localize } from 'vs/nls';
import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { WorkbenchList } from 'vs/platform/list/browser/listService';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { attachInputBoxStyler, attachSelectBoxStyler, attachButtonStyler } from 'vs/platform/theme/common/styler';
26
import { IThemeService, registerThemingParticipant, ITheme, ICssStyleCollector } from 'vs/platform/theme/common/themeService';
R
Rob Lourens 已提交
27 28 29
import { BaseEditor } from 'vs/workbench/browser/parts/editor/baseEditor';
import { EditorOptions } from 'vs/workbench/common/editor';
import { SearchWidget, SettingsTargetsWidget } from 'vs/workbench/parts/preferences/browser/preferencesWidgets';
R
Rob Lourens 已提交
30
import { IPreferencesService, ISetting, ISettingsEditorModel, ISearchResult } from 'vs/workbench/services/preferences/common/preferences';
R
Rob Lourens 已提交
31 32 33
import { PreferencesEditorInput2 } from 'vs/workbench/services/preferences/common/preferencesEditorInput';
import { DefaultSettingsEditorModel } from 'vs/workbench/services/preferences/common/preferencesModels';
import { Button } from 'vs/base/browser/ui/button/button';
R
Rob Lourens 已提交
34 35 36 37
import { IPreferencesSearchService, ISearchProvider } from '../common/preferences';
import { IProgressService } from 'vs/platform/progress/common/progress';
import { isPromiseCanceledError, getErrorMessage } from 'vs/base/common/errors';
import { ILogService } from 'vs/platform/log/common/log';
38
import { registerColor } from 'vs/platform/theme/common/colorRegistry';
39
import { IEditor } from 'vs/platform/editor/common/editor';
R
Rob Lourens 已提交
40 41 42

const SETTINGS_ENTRY_TEMPLATE_ID = 'settings.entry.template';
const SETTINGS_GROUP_ENTRY_TEMPLATE_ID = 'settings.group.template';
43 44 45
const BUTTON_ROW_ENTRY_TEMPLATE = 'settings.buttonRow.template';

const ALL_SETTINGS_BUTTON_ID = 'allSettings';
R
Rob Lourens 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61

interface IListEntry {
	id: string;
	templateId: string;
}

interface ISettingItemEntry extends IListEntry {
	key: string;
	value: any;
	isConfigured: boolean;
	description: string;
	overriddenScopeList: string[];
	type?: string | string[];
	enum?: string[];
}

62
interface IGroupTitleEntry extends IListEntry {
R
Rob Lourens 已提交
63 64 65
	title: string;
}

66 67
interface IButtonRowEntry extends IListEntry {
	label: string;
R
Rob Lourens 已提交
68 69
}

R
Rob Lourens 已提交
70 71 72 73 74
enum SearchResultIdx {
	Local = 0,
	Remote = 1
}

75 76 77 78 79 80 81 82 83 84 85 86 87 88
const $ = DOM.$;


export const configuredItemBackground = registerColor('settings.configuredItemBackground', {
	dark: '#0d466c',
	light: '#0d466c',
	hc: '#000000'
}, localize('configuredItemBackground', "The background color for a configured setting."));

export const configuredItemForeground = registerColor('settings.configuredItemForeground', {
	dark: '#dddddd',
	light: '#dddddd',
	hc: '#dddddd'
}, localize('configuredItemForeground', "The foreground color for a configured setting."));
R
Rob Lourens 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101

export class SettingsEditor2 extends BaseEditor {

	public static readonly ID: string = 'workbench.editor.settings2';

	private defaultSettingsEditorModel: DefaultSettingsEditorModel;

	private headerContainer: HTMLElement;
	private searchWidget: SearchWidget;
	private settingsTargetsWidget: SettingsTargetsWidget;

	private showConfiguredSettingsOnly = false;
	private showAllSettings = false;
102
	private showConfiguredSettingsOnlyButton: Button;
R
Rob Lourens 已提交
103 104 105 106 107 108 109

	private settingsListContainer: HTMLElement;
	private settingsList: List<IListEntry>;

	private dimension: DOM.Dimension;
	private searchFocusContextKey: IContextKey<boolean>;

R
Rob Lourens 已提交
110 111 112 113 114 115 116 117 118
	private delayedFilterLogging: Delayer<void>;
	private localSearchDelayer: Delayer<void>;
	private remoteSearchThrottle: ThrottledDelayer<void>;

	private currentLocalSearchProvider: ISearchProvider;
	private currentRemoteSearchProvider: ISearchProvider;

	private searchResults: ISearchResult[] = [];

R
Rob Lourens 已提交
119 120 121 122 123 124
	constructor(
		@ITelemetryService telemetryService: ITelemetryService,
		@IConfigurationService private configurationService: IConfigurationService,
		@IThemeService themeService: IThemeService,
		@IContextMenuService contextMenuService: IContextMenuService,
		@IPreferencesService private preferencesService: IPreferencesService,
R
Rob Lourens 已提交
125 126 127 128
		@IInstantiationService private instantiationService: IInstantiationService,
		@IPreferencesSearchService private preferencesSearchService: IPreferencesSearchService,
		@IProgressService private progressService: IProgressService,
		@ILogService private logService: ILogService
R
Rob Lourens 已提交
129 130
	) {
		super(SettingsEditor2.ID, telemetryService, themeService);
R
Rob Lourens 已提交
131 132 133 134
		this.delayedFilterLogging = new Delayer<void>(1000);
		this.localSearchDelayer = new Delayer(100);
		this.remoteSearchThrottle = new ThrottledDelayer(200);

R
Rob Lourens 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
		this._register(configurationService.onDidChangeConfiguration(() => this.render()));
	}

	createEditor(parent: HTMLElement): void {
		const prefsEditorElement = DOM.append(parent, $('div', { class: 'settings-editor' }));

		this.createHeader(prefsEditorElement);
		this.createBody(prefsEditorElement);
	}

	setInput(input: PreferencesEditorInput2, options: EditorOptions): TPromise<void> {
		const oldInput = this.input;
		return super.setInput(input)
			.then(() => {
				if (!input.matches(oldInput)) {
					this.render();
				}
			});
	}

	clearInput(): void {
		super.clearInput();
	}

	layout(dimension: DOM.Dimension): void {
		this.dimension = dimension;
		this.searchWidget.layout(dimension);

		this.layoutSettingsList();
		this.render();
	}

	focus(): void {
		this.searchWidget.focus();
	}

	getSecondaryActions(): IAction[] {
		return <IAction[]>[
		];
	}

	search(filter: string): void {
		this.searchWidget.focus();
	}

	clearSearchResults(): void {
		this.searchWidget.clear();
	}

	private createHeader(parent: HTMLElement): void {
		this.headerContainer = DOM.append(parent, $('.settings-header'));

		const searchContainer = DOM.append(this.headerContainer, $('.search-container'));
		this.searchWidget = this._register(this.instantiationService.createInstance(SearchWidget, searchContainer, {
			ariaLabel: localize('SearchSettings.AriaLabel', "Search settings"),
			placeholder: localize('SearchSettings.Placeholder', "Search settings"),
			focusKey: this.searchFocusContextKey
		}));
R
Rob Lourens 已提交
193
		this._register(this.searchWidget.onDidChange(() => this.onInputChanged()));
R
Rob Lourens 已提交
194

195
		const headerControlsContainer = DOM.append(this.headerContainer, $('.settings-header-controls'));
R
Rob Lourens 已提交
196 197 198 199 200
		const targetWidgetContainer = DOM.append(headerControlsContainer, $('.settings-target-container'));
		this.settingsTargetsWidget = this._register(this.instantiationService.createInstance(SettingsTargetsWidget, targetWidgetContainer));
		this.settingsTargetsWidget.settingsTarget = ConfigurationTarget.USER;
		this.settingsTargetsWidget.onDidTargetChange(e => this.renderEntries());

201
		this.createHeaderControls(headerControlsContainer);
R
Rob Lourens 已提交
202 203
	}

204 205 206 207 208 209 210 211 212 213 214 215 216
	private createHeaderControls(parent: HTMLElement): void {
		const headerControlsContainerRight = DOM.append(parent, $('.settings-header-controls-right'));

		this.showConfiguredSettingsOnlyButton = this._register(new Button(headerControlsContainerRight, { title: true }));
		this.showConfiguredSettingsOnlyButton.label = localize('showOverrides', "Show overrides");
		this.showConfiguredSettingsOnlyButton.element.classList.add('configured-only-button');

		this._register(this.showConfiguredSettingsOnlyButton.onDidClick(() => this.onShowConfiguredOnlyClicked()));

		const openSettingsButton = this._register(new Button(headerControlsContainerRight, { title: true, buttonBackground: null }));
		openSettingsButton.label = localize('openSettingsLabel', "Open config file");
		openSettingsButton.element.classList.add('open-settings-button');

217 218 219 220 221 222 223 224 225 226 227 228 229
		this._register(openSettingsButton.onDidClick(() => this.openSettingsFile()));
	}

	private openSettingsFile(): TPromise<IEditor> {
		const currentSettingsTarget = this.settingsTargetsWidget.settingsTarget;

		if (currentSettingsTarget === ConfigurationTarget.USER) {
			return this.preferencesService.openGlobalSettings();
		} else if (currentSettingsTarget === ConfigurationTarget.WORKSPACE) {
			return this.preferencesService.openWorkspaceSettings();
		} else {
			return this.preferencesService.openFolderSettings(currentSettingsTarget);
		}
R
Rob Lourens 已提交
230 231 232 233 234 235 236 237 238 239 240 241
	}

	private createBody(parent: HTMLElement): void {
		const bodyContainer = DOM.append(parent, $('.settings-body'));

		this.createList(bodyContainer);
	}

	private createList(parent: HTMLElement): void {
		this.settingsListContainer = DOM.append(parent, $('.settings-list-container'));

		const settingItemRenderer = this.instantiationService.createInstance(SettingItemRenderer);
242 243 244 245 246
		this._register(settingItemRenderer.onDidChangeSetting(e => this.onDidChangeSetting(e.key, e.value)));

		const buttonItemRenderer = new ButtonRowRenderer();
		this._register(buttonItemRenderer.onDidClick(e => this.onShowAllSettingsClicked()));

R
Rob Lourens 已提交
247 248 249 250
		this.settingsList = this._register(this.instantiationService.createInstance(
			WorkbenchList,
			this.settingsListContainer,
			new SettingItemDelegate(),
251
			[settingItemRenderer, new GroupTitleRenderer(), buttonItemRenderer],
R
Rob Lourens 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264
			{
				identityProvider: e => e.id,
				ariaLabel: localize('settingsListLabel', "Settings"),
				focusOnMouseDown: false,
				selectOnMouseDown: false,
				keyboardSupport: false,
				mouseSupport: false
			})
		) as WorkbenchList<IListEntry>;

		this.settingsList.style({ listHoverBackground: Color.transparent, listFocusOutline: Color.transparent });
	}

265 266 267 268 269
	private onShowAllSettingsClicked(): void {
		this.showAllSettings = !this.showAllSettings;
		this.render();
	}

270 271 272 273 274
	private onShowConfiguredOnlyClicked(): void {
		this.showConfiguredSettingsOnly = !this.showConfiguredSettingsOnly;
		this.render();
	}

R
Rob Lourens 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
	private onDidChangeSetting(key: string, value: any): void {
		this.configurationService.updateValue(key, value, <ConfigurationTarget>this.settingsTargetsWidget.settingsTarget).then(
			() => this.render(),
			e => {
				// ConfigurationService displays the error
			});
	}

	private render(): TPromise<any> {
		if (this.input) {
			return this.input.resolve()
				.then((model: DefaultSettingsEditorModel) => this.defaultSettingsEditorModel = model)
				.then(() => this.renderEntries());
		}
		return TPromise.as(null);
	}

R
Rob Lourens 已提交
292 293 294
	private onInputChanged(): void {
		const query = this.searchWidget.getValue().trim();
		this.delayedFilterLogging.cancel();
295
		this.triggerSearch(query);
R
Rob Lourens 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
	}

	private triggerSearch(query: string): TPromise<void> {
		if (query) {
			return TPromise.join([
				this.localSearchDelayer.trigger(() => this.localFilterPreferences(query)),
				this.remoteSearchThrottle.trigger(() => this.progressService.showWhile(this.remoteSearchPreferences(query), 500))
			]) as TPromise;
		} else {
			// When clearing the input, update immediately to clear it
			this.localSearchDelayer.cancel();
			// this.preferencesRenderers.localFilterPreferences(query);

			this.remoteSearchThrottle.cancel();
			// return this.preferencesRenderers.remoteSearchPreferences(query);

			this.searchResults = [];
			this.renderEntries();
			return TPromise.wrap(null);
		}
	}

	private localFilterPreferences(query: string): TPromise<void> {
		this.currentLocalSearchProvider = this.preferencesSearchService.getLocalSearchProvider(query);
		return this.filterOrSearchPreferences(query, SearchResultIdx.Local, this.currentLocalSearchProvider);
	}

	private remoteSearchPreferences(query: string): TPromise<void> {
		this.currentRemoteSearchProvider = this.preferencesSearchService.getRemoteSearchProvider(query);
		return this.filterOrSearchPreferences(query, SearchResultIdx.Remote, this.currentRemoteSearchProvider);
	}

	private filterOrSearchPreferences(query: string, type: SearchResultIdx, searchProvider: ISearchProvider): TPromise<void> {
		// this.lastQuery = query;

		const filterPs: TPromise<ISearchResult>[] = [this._filterOrSearchPreferencesModel(query, this.defaultSettingsEditorModel, searchProvider)];
		// filterPs.push(this.searchAllSettingsTargets(query, searchProvider));

		return TPromise.join(filterPs).then(results => {
			const [result] = results;
			this.searchResults[type] = result;
			this.renderSearchResults(this.searchResults);
		});
	}

	// private searchAllSettingsTargets(query: string, searchProvider: ISearchProvider): TPromise<void> {
	// 	const searchPs = [
	// 		this.searchSettingsTarget(query, searchProvider, ConfigurationTarget.WORKSPACE),
	// 		this.searchSettingsTarget(query, searchProvider, ConfigurationTarget.USER)
	// 	];

	// 	for (const folder of this.workspaceContextService.getWorkspace().folders) {
	// 		const folderSettingsResource = this.preferencesService.getFolderSettingsResource(folder.uri);
	// 		searchPs.push(this.searchSettingsTarget(query, searchProvider, folderSettingsResource));
	// 	}


	// 	return TPromise.join(searchPs).then(() => { });
	// }

	// private searchSettingsTarget(query: string, provider: ISearchProvider, target: SettingsTarget): TPromise<void> {
	// 	if (!query) {
	// 		// Don't open the other settings targets when query is empty
	// 		this._onDidFilterResultsCountChange.fire({ target, count: 0 });
	// 		return TPromise.wrap(null);
	// 	}

	// 	return this.getPreferencesEditorModel(target).then(model => {
	// 		return model && this._filterOrSearchPreferencesModel('', <ISettingsEditorModel>model, provider);
	// 	}).then(result => {
	// 		const count = result ? this._flatten(result.filteredGroups).length : 0;
	// 		this._onDidFilterResultsCountChange.fire({ target, count });
	// 	}, err => {
	// 		if (!isPromiseCanceledError(err)) {
	// 			return TPromise.wrapError(err);
	// 		}

	// 		return null;
	// 	});
	// }

	private _filterOrSearchPreferencesModel(filter: string, model: ISettingsEditorModel, provider: ISearchProvider): TPromise<ISearchResult> {
		const searchP = provider ? provider.searchModel(model) : TPromise.wrap(null);
		return searchP
			.then<ISearchResult>(null, err => {
				if (isPromiseCanceledError(err)) {
					return TPromise.wrapError(err);
				} else {
					/* __GDPR__
						"defaultSettings.searchError" : {
							"message": { "classification": "CallstackOrException", "purpose": "FeatureInsight" },
							"filter": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
						}
					*/
					const message = getErrorMessage(err).trim();
					if (message && message !== 'Error') {
						// "Error" = any generic network error
						this.telemetryService.publicLog('defaultSettings.searchError', { message, filter });
						this.logService.info('Setting search error: ' + message);
					}
					return null;
				}
			});
	}

	// private async getPreferencesEditorModel(target: SettingsTarget): TPromise<ISettingsEditorModel | null> {
	// 	const resource = target === ConfigurationTarget.USER ? this.preferencesService.userSettingsResource :
	// 		target === ConfigurationTarget.WORKSPACE ? this.preferencesService.workspaceSettingsResource :
	// 			target;

	// 	if (!resource) {
	// 		return null;
	// 	}

	// 	const targetKey = resource.toString();
	// 	if (!this._prefsModelsForSearch.has(targetKey)) {
	// 		try {
	// 			const model = this._register(await this.preferencesService.createPreferencesEditorModel(resource));
	// 			this._prefsModelsForSearch.set(targetKey, <ISettingsEditorModel>model);
	// 		} catch (e) {
	// 			// Will throw when the settings file doesn't exist.
	// 			return null;
	// 		}
	// 	}

	// 	return this._prefsModelsForSearch.get(targetKey);
	// }

	private renderSearchResults(searchResults: ISearchResult[]): void {
		const entries: ISettingItemEntry[] = [];
		const seenSettings = new Set<string>();

		for (let result of searchResults) {
			if (!result) {
				continue;
			}

			for (let match of result.filterMatches) {
				if (!seenSettings.has(match.setting.key)) {
					const entry = this.settingToEntry(match.setting);
					if (!this.showConfiguredSettingsOnly || entry.isConfigured) {
						seenSettings.add(entry.key);
						entries.push(entry);
					}
				}
			}
		}

		this.settingsList.splice(0, this.settingsList.length, entries);
R
Rob Lourens 已提交
445 446 447 448 449
	}

	private renderEntries(): void {
		if (this.defaultSettingsEditorModel) {

450
			const entries: IListEntry[] = [];
R
Rob Lourens 已提交
451
			for (let groupIdx = 0; groupIdx < this.defaultSettingsEditorModel.settingsGroups.length; groupIdx++) {
R
Rob Lourens 已提交
452
				if (groupIdx > 0 && !(this.showAllSettings)) {
R
Rob Lourens 已提交
453 454 455 456 457 458 459
					break;
				}

				const group = this.defaultSettingsEditorModel.settingsGroups[groupIdx];
				const groupEntries = [];
				for (const section of group.sections) {
					for (const setting of section.settings) {
R
Rob Lourens 已提交
460 461 462
						const entry = this.settingToEntry(setting);
						if (!this.showConfiguredSettingsOnly || (this.showConfiguredSettingsOnly && entry.isConfigured)) {
							groupEntries.push(entry);
R
Rob Lourens 已提交
463 464 465 466 467 468 469 470 471 472 473 474 475
						}
					}
				}

				if (groupEntries.length) {
					entries.push(<IGroupTitleEntry>{
						id: group.id,
						templateId: SETTINGS_GROUP_ENTRY_TEMPLATE_ID,
						title: group.title
					});

					entries.push(...groupEntries);
				}
476 477 478 479 480 481 482 483 484 485 486

				if (groupIdx === 0) {
					const showAllSettingsLabel = this.showAllSettings ?
						localize('showFewerSettingsLabel', "Show Fewer Settings") :
						localize('showAllSettingsLabel', "Show All Settings");
					entries.push(<IButtonRowEntry>{
						id: ALL_SETTINGS_BUTTON_ID,
						label: showAllSettingsLabel,
						templateId: BUTTON_ROW_ENTRY_TEMPLATE
					});
				}
R
Rob Lourens 已提交
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
			}

			this.settingsList.splice(0, this.settingsList.length, entries);
		}
	}

	private settingToEntry(s: ISetting): ISettingItemEntry {
		const targetSelector = this.settingsTargetsWidget.settingsTarget === ConfigurationTarget.USER ? 'user' : 'workspace';
		const inspected = this.configurationService.inspect(s.key);
		const isConfigured = typeof inspected[targetSelector] !== 'undefined';
		const displayValue = isConfigured ? inspected[targetSelector] : inspected.default;
		const overriddenScopeList = [];
		if (targetSelector === 'user' && typeof inspected.workspace !== 'undefined') {
			overriddenScopeList.push('Workspace');
		}

		if (targetSelector === 'workspace' && typeof inspected.user !== 'undefined') {
			overriddenScopeList.push('User');
		}

		return <ISettingItemEntry>{
			id: s.key,
			key: s.key,
			value: displayValue,
			isConfigured,
			overriddenScopeList,
			description: s.description.join('\n'),
			enum: s.enum,
			type: s.type,
			templateId: SETTINGS_ENTRY_TEMPLATE_ID
		};
	}

	private layoutSettingsList(): void {
		const listHeight = this.dimension.height - (DOM.getDomNodePagePosition(this.headerContainer).height + 12 /*padding*/);
		this.settingsListContainer.style.height = `${listHeight}px`;
		this.settingsList.layout(listHeight);
	}
}

class SettingItemDelegate implements IDelegate<IListEntry> {

529
	getHeight(entry: IListEntry) {
R
Rob Lourens 已提交
530 531 532 533 534 535
		if (entry.templateId === SETTINGS_GROUP_ENTRY_TEMPLATE_ID) {
			return 60;
		}

		if (entry.templateId === SETTINGS_ENTRY_TEMPLATE_ID) {
			// TODO dynamic height
536
			return 75;
R
Rob Lourens 已提交
537 538
		}

539 540 541 542
		if (entry.templateId === BUTTON_ROW_ENTRY_TEMPLATE) {
			return 60;
		}

R
Rob Lourens 已提交
543 544 545 546 547 548 549 550 551 552 553 554 555 556
		return 0;
	}

	getTemplateId(element: IListEntry) {
		return element.templateId;
	}
}

interface ISettingItemTemplate {
	parent: HTMLElement;
	toDispose: IDisposable[];

	containerElement: HTMLElement;
	labelElement: HTMLElement;
557
	// keyElement: HTMLElement;
R
Rob Lourens 已提交
558 559 560 561 562
	descriptionElement: HTMLElement;
	valueElement: HTMLElement;
	overridesElement: HTMLElement;
}

563
interface IGroupTitleTemplate {
R
Rob Lourens 已提交
564 565 566 567
	parent: HTMLElement;
	labelElement: HTMLElement;
}

568
interface IButtonRowTemplate {
R
Rob Lourens 已提交
569
	parent: HTMLElement;
570
	toDispose: IDisposable[];
R
Rob Lourens 已提交
571

572 573
	button: Button;
	entry?: IButtonRowEntry;
R
Rob Lourens 已提交
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
}

interface ISettingChangeEvent {
	key: string;
	value: any; // undefined => reset unconfigure
}

class SettingItemRenderer implements IRenderer<ISettingItemEntry, ISettingItemTemplate> {

	private readonly _onDidChangeSetting: Emitter<ISettingChangeEvent> = new Emitter<ISettingChangeEvent>();
	public readonly onDidChangeSetting: Event<ISettingChangeEvent> = this._onDidChangeSetting.event;

	get templateId(): string { return SETTINGS_ENTRY_TEMPLATE_ID; }

	constructor(
		@IContextViewService private contextViewService: IContextViewService,
		@IThemeService private themeService: IThemeService
	) { }

	renderTemplate(parent: HTMLElement): ISettingItemTemplate {
		DOM.addClass(parent, 'setting-item');

596
		const itemContainer = DOM.append(parent, $('.setting-item-container'));
R
Rob Lourens 已提交
597 598 599
		const leftElement = DOM.append(itemContainer, $('.setting-item-left'));
		const rightElement = DOM.append(itemContainer, $('.setting-item-right'));

600
		const titleElement = DOM.append(leftElement, $('.setting-item-title'));
R
Rob Lourens 已提交
601
		const labelElement = DOM.append(titleElement, $('span.setting-item-label'));
602 603 604
		// const keyElement = DOM.append(titleElement, $('span.setting-item-key'));
		const overridesElement = DOM.append(titleElement, $('span.setting-item-overrides'));
		const descriptionElement = DOM.append(leftElement, $('.setting-item-description'));
R
Rob Lourens 已提交
605

606
		const valueElement = DOM.append(rightElement, $('.setting-item-value'));
R
Rob Lourens 已提交
607 608 609 610 611 612

		return {
			parent: parent,
			toDispose: [],

			containerElement: itemContainer,
613
			// keyElement,
R
Rob Lourens 已提交
614 615 616 617 618 619 620 621 622 623
			labelElement,
			descriptionElement,
			valueElement,
			overridesElement
		};
	}

	renderElement(entry: ISettingItemEntry, index: number, template: ISettingItemTemplate): void {
		DOM.toggleClass(template.parent, 'odd', index % 2 === 1);

624
		// template.keyElement.textContent = entry.key;
R
Rob Lourens 已提交
625
		template.labelElement.textContent = settingKeyToLabel(entry.key);
626
		template.labelElement.title = entry.key;
R
Rob Lourens 已提交
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
		template.descriptionElement.textContent = entry.description;

		DOM.toggleClass(template.parent, 'is-configured', entry.isConfigured);
		this.renderValue(entry, template);

		const resetButton = new Button(template.valueElement);
		resetButton.element.classList.add('setting-reset-button');
		attachButtonStyler(resetButton, this.themeService, {
			buttonBackground: Color.transparent.toString(),
			buttonHoverBackground: Color.transparent.toString()
		});
		template.toDispose.push(resetButton.onDidClick(e => {
			this._onDidChangeSetting.fire({ key: entry.key, value: undefined });
		}));
		template.toDispose.push(resetButton);

643 644
		const alsoConfiguredInLabel = localize('alsoConfiguredIn', "Also configured in:");
		template.overridesElement.textContent = entry.overriddenScopeList.length ? `(${alsoConfiguredInLabel} ${entry.overriddenScopeList.join(', ')})` :
R
Rob Lourens 已提交
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
			'';
	}

	private renderValue(entry: ISettingItemEntry, template: ISettingItemTemplate): void {
		const onChange = value => this._onDidChangeSetting.fire({ key: entry.key, value });
		template.valueElement.innerHTML = '';
		if (entry.type === 'string' && entry.enum) {
			this.renderEnum(entry, template, onChange);
		} else if (entry.type === 'boolean') {
			this.renderBool(entry, template, onChange);
		} else if (entry.type === 'string') {
			this.renderText(entry, template, onChange);
		} else if (entry.type === 'number') {
			this.renderText(entry, template, value => onChange(parseInt(value)));
		} else {
			template.valueElement.textContent = 'Edit in settings.json!';
		}
	}

	private renderBool(entry: ISettingItemEntry, template: ISettingItemTemplate, onChange: (value: boolean) => void): void {
665 666 667
		const checkboxElement = <HTMLInputElement>DOM.append(template.valueElement, $('input.setting-value-checkbox'));
		checkboxElement.type = 'checkbox';
		checkboxElement.checked = entry.value;
R
Rob Lourens 已提交
668

669
		template.toDispose.push(DOM.addDisposableListener(checkboxElement, 'change', e => onChange(checkboxElement.checked)));
R
Rob Lourens 已提交
670 671 672 673 674 675
	}

	private renderEnum(entry: ISettingItemEntry, template: ISettingItemTemplate, onChange: (value: string) => void): void {
		const idx = entry.enum.indexOf(entry.value);
		const selectBox = new SelectBox(entry.enum, idx, this.contextViewService);
		template.toDispose.push(selectBox);
676 677 678 679
		template.toDispose.push(attachSelectBoxStyler(selectBox, this.themeService, {
			selectBackground: entry.isConfigured ? configuredItemBackground : undefined,
			selectForeground: entry.isConfigured ? configuredItemForeground : undefined
		}));
R
Rob Lourens 已提交
680 681 682 683 684 685 686 687 688
		selectBox.render(template.valueElement);

		template.toDispose.push(
			selectBox.onDidSelect(e => onChange(entry.enum[e.index])));
	}

	private renderText(entry: ISettingItemEntry, template: ISettingItemTemplate, onChange: (value: string) => void): void {
		const inputBox = new InputBox(template.valueElement, this.contextViewService);
		template.toDispose.push(attachInputBoxStyler(inputBox, this.themeService, {
689 690
			inputBackground: entry.isConfigured ? configuredItemBackground : undefined,
			inputForeground: entry.isConfigured ? configuredItemForeground : undefined
R
Rob Lourens 已提交
691 692 693 694 695 696 697 698 699 700 701 702 703
		}));
		template.toDispose.push(inputBox);
		inputBox.value = entry.value;

		template.toDispose.push(
			inputBox.onDidChange(e => onChange(e)));
	}

	disposeTemplate(template: ISettingItemTemplate): void {
		dispose(template.toDispose);
	}
}

704
class GroupTitleRenderer implements IRenderer<IGroupTitleEntry, IGroupTitleTemplate> {
R
Rob Lourens 已提交
705 706 707

	get templateId(): string { return SETTINGS_GROUP_ENTRY_TEMPLATE_ID; }

708
	renderTemplate(parent: HTMLElement): IGroupTitleTemplate {
R
Rob Lourens 已提交
709 710 711 712 713 714 715 716 717
		DOM.addClass(parent, 'group-title');

		const labelElement = DOM.append(parent, $('h2.group-title-label'));
		return {
			parent: parent,
			labelElement
		};
	}

718
	renderElement(entry: IGroupTitleEntry, index: number, template: IGroupTitleTemplate): void {
R
Rob Lourens 已提交
719 720 721
		template.labelElement.textContent = entry.title;
	}

722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
	disposeTemplate(template: IGroupTitleTemplate): void {
	}
}

class ButtonRowRenderer implements IRenderer<IButtonRowEntry, IButtonRowTemplate> {

	private readonly _onDidClick: Emitter<string> = new Emitter<string>();
	public readonly onDidClick: Event<string> = this._onDidClick.event;

	get templateId(): string { return BUTTON_ROW_ENTRY_TEMPLATE; }

	renderTemplate(parent: HTMLElement): IButtonRowTemplate {
		DOM.addClass(parent, 'all-settings');

		const buttonElement = DOM.append(parent, $('.all-settings-button'));

		const button = new Button(buttonElement);
		const toDispose: IDisposable[] = [button];

		const template: IButtonRowTemplate = {
			parent: parent,
			toDispose,

			button
		};
		toDispose.push(button.onDidClick(e => this._onDidClick.fire(template.entry && template.entry.label)));

		return template;
	}

	renderElement(entry: IButtonRowEntry, index: number, template: IButtonRowTemplate): void {
		template.button.label = entry.label;
		template.entry = entry;
	}

	disposeTemplate(template: IButtonRowTemplate): void {
R
Rob Lourens 已提交
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
		dispose(template.toDispose);
	}
}

function settingKeyToLabel(key: string): string {
	const lastDotIdx = key.lastIndexOf('.');
	if (lastDotIdx >= 0) {
		key = key.substr(0, lastDotIdx) + ': ' + key.substr(lastDotIdx + 1);
	}

	return key
		.replace(/\.([a-z])/, (match, p1) => `.${p1.toUpperCase()}`)
		.replace(/([a-z])([A-Z])/g, '$1 $2') // fooBar => foo Bar
		.replace(/^[a-z]/g, match => match.toUpperCase()) // foo => Foo
		.replace(/ [a-z]/g, match => match.toUpperCase()); // Foo bar => Foo Bar
}
774 775 776 777 778 779 780

registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
	const configuredItemBackgroundColor = theme.getColor(configuredItemBackground);
	if (configuredItemBackgroundColor) {
		collector.addRule(`.settings-editor > .settings-body > .settings-list-container .monaco-list-row.is-configured .setting-value-checkbox::after { background-color: ${configuredItemBackgroundColor}; }`);
	}
});