settingsEditor2.ts 31.3 KB
Newer Older
R
Rob Lourens 已提交
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  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';
7
import { Button } from 'vs/base/browser/ui/button/button';
8
import * as arrays from 'vs/base/common/arrays';
R
Rob Lourens 已提交
9
import { Delayer, ThrottledDelayer } from 'vs/base/common/async';
R
Rob Lourens 已提交
10
import { CancellationToken } from 'vs/base/common/cancellation';
R
Rob Lourens 已提交
11
import * as collections from 'vs/base/common/collections';
R
Rob Lourens 已提交
12
import { Color } from 'vs/base/common/color';
13
import { getErrorMessage, isPromiseCanceledError } from 'vs/base/common/errors';
R
Rob Lourens 已提交
14
import URI from 'vs/base/common/uri';
R
Rob Lourens 已提交
15
import { TPromise } from 'vs/base/common/winjs.base';
16
import { ITree, ITreeConfiguration } from 'vs/base/parts/tree/browser/tree';
17
import { DefaultTreestyler, OpenMode } from 'vs/base/parts/tree/browser/treeDefaults';
R
Rob Lourens 已提交
18 19
import 'vs/css!./media/settingsEditor2';
import { localize } from 'vs/nls';
R
Rob Lourens 已提交
20
import { ConfigurationTarget, IConfigurationOverrides, IConfigurationService } from 'vs/platform/configuration/common/configuration';
R
Rob Lourens 已提交
21 22
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
R
Rob Lourens 已提交
23
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
24
import { WorkbenchTree, WorkbenchTreeController } from 'vs/platform/list/browser/listService';
25
import { ILogService } from 'vs/platform/log/common/log';
R
Rob Lourens 已提交
26
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
27
import { editorBackground, foreground, listActiveSelectionBackground, listInactiveSelectionBackground } from 'vs/platform/theme/common/colorRegistry';
28 29
import { attachButtonStyler, attachStyler } from 'vs/platform/theme/common/styler';
import { ICssStyleCollector, ITheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
R
Rob Lourens 已提交
30
import { BaseEditor } from 'vs/workbench/browser/parts/editor/baseEditor';
31
import { EditorOptions, IEditor } from 'vs/workbench/common/editor';
32
import { SearchWidget, SettingsTarget, SettingsTargetsWidget } from 'vs/workbench/parts/preferences/browser/preferencesWidgets';
R
Rob Lourens 已提交
33 34
import { commonlyUsedData, tocData } from 'vs/workbench/parts/preferences/browser/settingsLayout';
import { ISettingsEditorViewState, NonExpandableTree, resolveExtensionsSettings, resolveSettingsTree, SearchResultIdx, SearchResultModel, SettingsAccessibilityProvider, SettingsDataSource, SettingsRenderer, SettingsTreeController, SettingsTreeElement, SettingsTreeFilter, SettingsTreeGroupElement, SettingsTreeModel, SettingsTreeSettingElement } from 'vs/workbench/parts/preferences/browser/settingsTree';
35
import { TOCDataSource, TOCRenderer, TOCTreeModel } from 'vs/workbench/parts/preferences/browser/tocTree';
36
import { CONTEXT_SETTINGS_EDITOR, CONTEXT_SETTINGS_FIRST_ROW_FOCUS, CONTEXT_SETTINGS_SEARCH_FOCUS, IPreferencesSearchService, ISearchProvider, CONTEXT_SETTINGS_ROW_FOCUS } from 'vs/workbench/parts/preferences/common/preferences';
37
import { IPreferencesService, ISearchResult, ISettingsEditorModel } from 'vs/workbench/services/preferences/common/preferences';
38
import { SettingsEditor2Input } from 'vs/workbench/services/preferences/common/preferencesEditorInput';
R
Rob Lourens 已提交
39
import { DefaultSettingsEditorModel } from 'vs/workbench/services/preferences/common/preferencesModels';
R
Rob Lourens 已提交
40

41 42
const $ = DOM.$;

R
Rob Lourens 已提交
43 44 45 46 47 48
export class SettingsEditor2 extends BaseEditor {

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

	private defaultSettingsEditorModel: DefaultSettingsEditorModel;

49
	private rootElement: HTMLElement;
R
Rob Lourens 已提交
50 51 52 53
	private headerContainer: HTMLElement;
	private searchWidget: SearchWidget;
	private settingsTargetsWidget: SettingsTargetsWidget;

54
	private showConfiguredSettingsOnlyCheckbox: HTMLInputElement;
R
Rob Lourens 已提交
55

56 57 58
	private settingsTreeContainer: HTMLElement;
	private settingsTree: WorkbenchTree;
	private treeDataSource: SettingsDataSource;
59
	private tocTreeModel: TOCTreeModel;
60
	private settingsTreeModel: SettingsTreeModel;
R
Rob Lourens 已提交
61

R
Rob Lourens 已提交
62 63 64
	private tocTreeContainer: HTMLElement;
	private tocTree: WorkbenchTree;

R
Rob Lourens 已提交
65 66 67
	private delayedFilterLogging: Delayer<void>;
	private localSearchDelayer: Delayer<void>;
	private remoteSearchThrottle: ThrottledDelayer<void>;
R
Rob Lourens 已提交
68
	private searchInProgress: TPromise<void>;
R
Rob Lourens 已提交
69

70 71
	private settingUpdateDelayer: Delayer<void>;
	private pendingSettingUpdate: { key: string, value: any };
R
Rob Lourens 已提交
72

73
	private selectedElement: SettingsTreeElement;
74

75
	private viewState: ISettingsEditorViewState;
76
	private searchResultModel: SearchResultModel;
77 78

	private firstRowFocused: IContextKey<boolean>;
79
	private rowFocused: IContextKey<boolean>;
80 81
	private inSettingsEditorContextKey: IContextKey<boolean>;
	private searchFocusContextKey: IContextKey<boolean>;
82

R
Rob Lourens 已提交
83 84 85 86 87
	constructor(
		@ITelemetryService telemetryService: ITelemetryService,
		@IConfigurationService private configurationService: IConfigurationService,
		@IThemeService themeService: IThemeService,
		@IPreferencesService private preferencesService: IPreferencesService,
R
Rob Lourens 已提交
88 89
		@IInstantiationService private instantiationService: IInstantiationService,
		@IPreferencesSearchService private preferencesSearchService: IPreferencesSearchService,
90
		@ILogService private logService: ILogService,
91 92
		@IEnvironmentService private environmentService: IEnvironmentService,
		@IContextKeyService contextKeyService: IContextKeyService
R
Rob Lourens 已提交
93 94
	) {
		super(SettingsEditor2.ID, telemetryService, themeService);
R
Rob Lourens 已提交
95 96 97
		this.delayedFilterLogging = new Delayer<void>(1000);
		this.localSearchDelayer = new Delayer(100);
		this.remoteSearchThrottle = new ThrottledDelayer(200);
98
		this.viewState = { settingsTarget: ConfigurationTarget.USER };
R
Rob Lourens 已提交
99

100 101
		this.settingUpdateDelayer = new Delayer<void>(500);

102 103
		this.inSettingsEditorContextKey = CONTEXT_SETTINGS_EDITOR.bindTo(contextKeyService);
		this.searchFocusContextKey = CONTEXT_SETTINGS_SEARCH_FOCUS.bindTo(contextKeyService);
104
		this.firstRowFocused = CONTEXT_SETTINGS_FIRST_ROW_FOCUS.bindTo(contextKeyService);
105
		this.rowFocused = CONTEXT_SETTINGS_ROW_FOCUS.bindTo(contextKeyService);
106

107 108 109 110 111 112 113
		this._register(configurationService.onDidChangeConfiguration(e => {
			this.onConfigUpdate();

			if (e.affectsConfiguration('workbench.settings.tocVisible')) {
				this.updateTOCVisible();
			}
		}));
R
Rob Lourens 已提交
114 115 116
	}

	createEditor(parent: HTMLElement): void {
117
		this.rootElement = DOM.append(parent, $('.settings-editor'));
R
Rob Lourens 已提交
118

119 120
		this.createHeader(this.rootElement);
		this.createBody(this.rootElement);
R
Rob Lourens 已提交
121 122
	}

123
	setInput(input: SettingsEditor2Input, options: EditorOptions, token: CancellationToken): Thenable<void> {
124
		this.inSettingsEditorContextKey.set(true);
125
		return super.setInput(input, options, token)
R
Rob Lourens 已提交
126
			.then(() => {
127
				this.render(token);
R
Rob Lourens 已提交
128 129 130
			});
	}

131 132 133 134 135
	clearInput(): void {
		this.inSettingsEditorContextKey.set(false);
		super.clearInput();
	}

R
Rob Lourens 已提交
136 137
	layout(dimension: DOM.Dimension): void {
		this.searchWidget.layout(dimension);
138 139 140
		this.layoutTrees(dimension);

		DOM.toggleClass(this.rootElement, 'narrow', dimension.width < 600);
R
Rob Lourens 已提交
141 142 143
	}

	focus(): void {
144 145 146
		this.focusSearch();
	}

147 148 149 150 151 152 153 154 155 156 157
	focusSettings(): void {
		const selection = this.settingsTree.getSelection();
		if (selection && selection[0]) {
			this.settingsTree.setFocus(selection[0]);
		} else {
			this.settingsTree.focusFirst();
		}

		this.settingsTree.domFocus();
	}

158
	focusSearch(): void {
R
Rob Lourens 已提交
159 160 161
		this.searchWidget.focus();
	}

162 163 164 165 166 167 168 169
	editSelectedSetting(): void {
		const focus = this.settingsTree.getFocus();
		if (focus instanceof SettingsTreeSettingElement) {
			const itemId = focus.id.replace(/\./g, '_');
			this.focusEditControlForRow(itemId);
		}
	}

170 171 172 173
	clearSearchResults(): void {
		this.searchWidget.clear();
	}

R
Rob Lourens 已提交
174 175 176
	private createHeader(parent: HTMLElement): void {
		this.headerContainer = DOM.append(parent, $('.settings-header'));

177
		const previewHeader = DOM.append(this.headerContainer, $('.settings-preview-header'));
R
Rob Lourens 已提交
178 179 180 181 182

		const previewAlert = DOM.append(previewHeader, $('span.settings-preview-warning'));
		previewAlert.textContent = localize('previewWarning', "Preview");

		const previewTextLabel = DOM.append(previewHeader, $('span.settings-preview-label'));
183
		previewTextLabel.textContent = localize('previewLabel', "This is a preview of our new settings editor");
184

R
Rob Lourens 已提交
185 186 187
		const searchContainer = DOM.append(this.headerContainer, $('.search-container'));
		this.searchWidget = this._register(this.instantiationService.createInstance(SearchWidget, searchContainer, {
			ariaLabel: localize('SearchSettings.AriaLabel', "Search settings"),
188 189
			placeholder: localize('SearchSettings.Placeholder', "Search settings"),
			focusKey: this.searchFocusContextKey
R
Rob Lourens 已提交
190
		}));
191
		this._register(this.searchWidget.onDidChange(() => this.onSearchInputChanged()));
R
Rob Lourens 已提交
192

193 194 195 196 197 198 199 200 201 202 203 204 205 206
		const advancedCustomization = DOM.append(this.headerContainer, $('.settings-advanced-customization'));
		const advancedCustomizationLabel = DOM.append(advancedCustomization, $('span.settings-advanced-customization-label'));
		advancedCustomizationLabel.textContent = localize('advancedCustomizationLabel', "For advanced customizations open and edit") + ' ';
		const openSettingsButton = this._register(new Button(advancedCustomization, { title: true, buttonBackground: null, buttonHoverBackground: null }));
		this._register(attachButtonStyler(openSettingsButton, this.themeService, {
			buttonBackground: Color.transparent.toString(),
			buttonHoverBackground: Color.transparent.toString(),
			buttonForeground: foreground
		}));
		openSettingsButton.label = localize('openSettingsLabel', "settings.json");
		openSettingsButton.element.classList.add('open-settings-button');

		this._register(openSettingsButton.onDidClick(() => this.openSettingsFile()));

207
		const headerControlsContainer = DOM.append(this.headerContainer, $('.settings-header-controls'));
R
Rob Lourens 已提交
208 209 210
		const targetWidgetContainer = DOM.append(headerControlsContainer, $('.settings-target-container'));
		this.settingsTargetsWidget = this._register(this.instantiationService.createInstance(SettingsTargetsWidget, targetWidgetContainer));
		this.settingsTargetsWidget.settingsTarget = ConfigurationTarget.USER;
211 212
		this.settingsTargetsWidget.onDidTargetChange(() => {
			this.viewState.settingsTarget = this.settingsTargetsWidget.settingsTarget;
213 214 215

			this.settingsTreeModel.update();
			this.refreshTreeAndMaintainFocus();
216
		});
R
Rob Lourens 已提交
217

218
		this.createHeaderControls(headerControlsContainer);
R
Rob Lourens 已提交
219 220
	}

221 222 223
	private createHeaderControls(parent: HTMLElement): void {
		const headerControlsContainerRight = DOM.append(parent, $('.settings-header-controls-right'));

224 225 226
		this.showConfiguredSettingsOnlyCheckbox = DOM.append(headerControlsContainerRight, $('input#configured-only-checkbox'));
		this.showConfiguredSettingsOnlyCheckbox.type = 'checkbox';
		const showConfiguredSettingsOnlyLabel = <HTMLLabelElement>DOM.append(headerControlsContainerRight, $('label.configured-only-label'));
227
		showConfiguredSettingsOnlyLabel.textContent = localize('showOverriddenOnly', "Show modified only");
228
		showConfiguredSettingsOnlyLabel.htmlFor = 'configured-only-checkbox';
229

230
		this._register(DOM.addDisposableListener(this.showConfiguredSettingsOnlyCheckbox, 'change', e => this.onShowConfiguredOnlyClicked()));
231 232 233 234 235 236 237 238 239 240 241 242
	}

	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 已提交
243 244 245 246 247
	}

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

248
		this.createTOC(bodyContainer);
R
Rob Lourens 已提交
249
		this.createSettingsTree(bodyContainer);
250 251 252 253

		if (this.environmentService.appQuality !== 'stable') {
			this.createFeedbackButton(bodyContainer);
		}
R
Rob Lourens 已提交
254 255
	}

R
Rob Lourens 已提交
256 257 258
	private createTOC(parent: HTMLElement): void {
		this.tocTreeContainer = DOM.append(parent, $('.settings-toc-container'));

259 260 261
		const tocDataSource = this.instantiationService.createInstance(TOCDataSource);
		const tocRenderer = this.instantiationService.createInstance(TOCRenderer);
		this.tocTreeModel = new TOCTreeModel();
R
Rob Lourens 已提交
262 263 264

		this.tocTree = this.instantiationService.createInstance(WorkbenchTree, this.tocTreeContainer,
			<ITreeConfiguration>{
265 266
				dataSource: tocDataSource,
				renderer: tocRenderer,
267
				controller: this.instantiationService.createInstance(WorkbenchTreeController, { openMode: OpenMode.DOUBLE_CLICK }),
268
				filter: this.instantiationService.createInstance(SettingsTreeFilter, this.viewState)
R
Rob Lourens 已提交
269 270
			},
			{
271 272
				showLoading: false,
				twistiePixels: 15
R
Rob Lourens 已提交
273 274 275
			});

		this._register(this.tocTree.onDidChangeSelection(e => {
276 277 278 279 280
			if (this.searchResultModel) {
				const element = e.selection[0];
				this.viewState.filterToCategory = element;
				this.refreshTreeAndMaintainFocus();
			} else if (this.settingsTreeModel) {
281
				const element = e.selection[0];
R
Rob Lourens 已提交
282
				if (element && !e.payload.fromScroll) {
283 284 285
					this.settingsTree.reveal(element, 0);
					this.settingsTree.setSelection([element]);
					this.settingsTree.setFocus(element);
R
Rob Lourens 已提交
286
					this.settingsTree.domFocus();
287
				}
288
			}
R
Rob Lourens 已提交
289
		}));
290 291 292 293 294 295 296

		this.updateTOCVisible();
	}

	private updateTOCVisible(): void {
		const visible = !!this.configurationService.getValue('workbench.settings.tocVisible');
		DOM.toggleClass(this.tocTreeContainer, 'hidden', !visible);
R
Rob Lourens 已提交
297 298 299
	}

	private createSettingsTree(parent: HTMLElement): void {
300
		this.settingsTreeContainer = DOM.append(parent, $('.settings-tree-container'));
R
Rob Lourens 已提交
301

302
		this.treeDataSource = this.instantiationService.createInstance(SettingsDataSource, this.viewState);
303
		const renderer = this.instantiationService.createInstance(SettingsRenderer, this.settingsTreeContainer);
304
		this._register(renderer.onDidChangeSetting(e => this.onDidChangeSetting(e.key, e.value)));
305
		this._register(renderer.onDidOpenSettings(() => this.openSettingsFile()));
306

307
		const treeClass = 'settings-editor-tree';
308
		this.settingsTree = this.instantiationService.createInstance(NonExpandableTree, this.settingsTreeContainer,
309
			<ITreeConfiguration>{
310
				dataSource: this.treeDataSource,
R
Rob Lourens 已提交
311
				renderer,
312 313
				controller: this.instantiationService.createInstance(SettingsTreeController),
				accessibilityProvider: this.instantiationService.createInstance(SettingsAccessibilityProvider),
314 315
				filter: this.instantiationService.createInstance(SettingsTreeFilter, this.viewState),
				styler: new DefaultTreestyler(DOM.createStyleSheet(), treeClass)
316 317 318 319
			},
			{
				ariaLabel: localize('treeAriaLabel', "Settings"),
				showLoading: false,
320 321
				indentPixels: 0,
				twistiePixels: 0,
322
			});
323

324
		this._register(registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
325 326
			const activeBorderColor = theme.getColor(listActiveSelectionBackground);
			if (activeBorderColor) {
327
				collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .monaco-tree:focus .monaco-tree-row.focused {outline: solid 1px ${activeBorderColor}; outline-offset: -1px; }`);
328 329
			}

330 331
			const inactiveBorderColor = theme.getColor(listInactiveSelectionBackground);
			if (inactiveBorderColor) {
332
				collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .monaco-tree .monaco-tree-row.focused {outline: solid 1px ${inactiveBorderColor}; outline-offset: -1px; }`);
333
			}
334 335
		}));

336 337
		this.settingsTree.getHTMLElement().classList.add(treeClass);

338
		this._register(attachStyler(this.themeService, {
339 340 341 342 343 344 345 346 347 348
			listActiveSelectionBackground: editorBackground,
			listActiveSelectionForeground: foreground,
			listFocusAndSelectionBackground: editorBackground,
			listFocusAndSelectionForeground: foreground,
			listFocusBackground: editorBackground,
			listFocusForeground: foreground,
			listHoverForeground: foreground,
			listHoverBackground: editorBackground,
			listInactiveSelectionBackground: editorBackground,
			listInactiveSelectionForeground: foreground
349 350
		}, colors => {
			this.settingsTree.style(colors);
351
		}));
352

353
		this._register(this.settingsTree.onDidChangeFocus(e => {
354
			this.settingsTree.setSelection([e.focus]);
355 356
			if (this.selectedElement) {
				this.settingsTree.refresh(this.selectedElement);
357
			}
358

359 360
			if (e.focus) {
				this.settingsTree.refresh(e.focus);
361
			}
362 363

			this.selectedElement = e.focus;
364 365
		}));

366 367 368 369 370
		this._register(this.settingsTree.onDidBlur(() => {
			this.rowFocused.set(false);
			this.firstRowFocused.set(false);
		}));

371
		this._register(this.settingsTree.onDidChangeSelection(e => {
372
			this.updateTreeScrollSync();
373 374

			let firstRowFocused = false;
375
			let rowFocused = false;
376 377
			const selection: SettingsTreeElement = e.selection[0];
			if (selection) {
378
				rowFocused = true;
379 380 381 382 383 384 385 386
				if (this.searchResultModel) {
					firstRowFocused = selection.id === this.searchResultModel.getChildren()[0].id;
				} else {
					const firstRowId = this.settingsTreeModel.root.children[0] && this.settingsTreeModel.root.children[0].id;
					firstRowFocused = selection.id === firstRowId;
				}
			}

387
			this.rowFocused.set(rowFocused);
388
			this.firstRowFocused.set(firstRowFocused);
389
		}));
390

391 392
		this._register(this.settingsTree.onDidScroll(() => {
			this.updateTreeScrollSync();
393
		}));
394 395
	}

396 397 398 399 400 401 402 403 404 405 406 407
	private createFeedbackButton(parent: HTMLElement): void {
		const feedbackButton = this._register(new Button(parent));
		feedbackButton.label = localize('feedbackButtonLabel', "Provide Feedback");
		feedbackButton.element.classList.add('settings-feedback-button');

		this._register(attachButtonStyler(feedbackButton, this.themeService));
		this._register(feedbackButton.onDidClick(() => {
			// Github master issue
			window.open('https://go.microsoft.com/fwlink/?linkid=2000807');
		}));
	}

408
	private onShowConfiguredOnlyClicked(): void {
409
		this.viewState.showConfiguredOnly = this.showConfiguredSettingsOnlyCheckbox.checked;
R
Rob Lourens 已提交
410
		this.refreshTreeAndMaintainFocus();
411 412
		this.tocTree.refresh();
		this.settingsTree.setScrollPosition(0);
413
		this.expandAll(this.settingsTree);
414 415
	}

R
Rob Lourens 已提交
416
	private onDidChangeSetting(key: string, value: any): void {
417 418
		if (this.pendingSettingUpdate && this.pendingSettingUpdate.key !== key) {
			this.updateChangedSetting(key, value);
419 420
		}

421 422 423 424
		this.pendingSettingUpdate = { key, value };
		this.settingUpdateDelayer.trigger(() => this.updateChangedSetting(key, value));
	}

425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
	private updateTreeScrollSync(): void {
		if (this.searchResultModel) {
			return;
		}

		if (!this.tocTree.getInput()) {
			return;
		}

		let elementToSync = this.settingsTree.getFirstVisibleElement();
		const selection = this.settingsTree.getSelection()[0];
		if (selection) {
			const selectionPos = this.settingsTree.getRelativeTop(selection);
			if (selectionPos >= 0 && selectionPos <= 1) {
				elementToSync = selection;
			}
		}

		const element = elementToSync instanceof SettingsTreeSettingElement ? elementToSync.parent :
			elementToSync instanceof SettingsTreeGroupElement ? elementToSync :
				null;

		if (element && this.tocTree.getSelection()[0] !== element) {
			const elementTop = this.tocTree.getRelativeTop(element);
			if (elementTop < 0) {
				this.tocTree.reveal(element, 0);
			} else if (elementTop > 1) {
				this.tocTree.reveal(element, 1);
			}

			this.tocTree.setSelection([element], { fromScroll: true });
			this.tocTree.setFocus(element);
		}
	}

460 461 462
	private updateChangedSetting(key: string, value: any): TPromise<void> {
		// ConfigurationService displays the error if this fails.
		// Force a render afterwards because onDidConfigurationUpdate doesn't fire if the update doesn't result in an effective setting value change
R
Rob Lourens 已提交
463 464 465 466 467 468 469 470 471 472 473 474
		const settingsTarget = this.settingsTargetsWidget.settingsTarget;
		const resource = URI.isUri(settingsTarget) ? settingsTarget : undefined;
		const configurationTarget = <ConfigurationTarget>(resource ? undefined : settingsTarget);
		const overrides: IConfigurationOverrides = { resource };

		// If the user is changing the value back to the default, do a 'reset' instead
		const inspected = this.configurationService.inspect(key, overrides);
		if (inspected.default === value) {
			value = undefined;
		}

		return this.configurationService.updateValue(key, value, overrides, configurationTarget)
475 476 477 478 479 480 481 482 483 484 485 486 487 488
			.then(() => this.refreshTreeAndMaintainFocus())
			.then(() => {
				const reportModifiedProps = {
					key,
					query: this.searchWidget.getValue(),
					searchResults: this.searchResultModel && this.searchResultModel.getUniqueResults(),
					rawResults: this.searchResultModel && this.searchResultModel.getRawResults(),
					showConfiguredOnly: this.viewState.showConfiguredOnly,
					isReset: typeof value === 'undefined',
					settingsTarget: this.settingsTargetsWidget.settingsTarget as SettingsTarget
				};

				return this.reportModifiedSetting(reportModifiedProps);
			});
489 490 491
	}

	private reportModifiedSetting(props: { key: string, query: string, searchResults: ISearchResult[], rawResults: ISearchResult[], showConfiguredOnly: boolean, isReset: boolean, settingsTarget: SettingsTarget }): void {
492
		this.pendingSettingUpdate = null;
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509

		const remoteResult = props.searchResults && props.searchResults[SearchResultIdx.Remote];
		const localResult = props.searchResults && props.searchResults[SearchResultIdx.Local];

		let groupId = undefined;
		let nlpIndex = undefined;
		let displayIndex = undefined;
		if (props.searchResults) {
			const localIndex = arrays.firstIndex(localResult.filterMatches, m => m.setting.key === props.key);
			groupId = localIndex >= 0 ?
				'local' :
				'remote';

			displayIndex = localIndex >= 0 ?
				localIndex :
				remoteResult && (arrays.firstIndex(remoteResult.filterMatches, m => m.setting.key === props.key) + localResult.filterMatches.length);

510 511 512 513 514 515
			if (this.searchResultModel) {
				const rawResults = this.searchResultModel.getRawResults();
				if (rawResults[SearchResultIdx.Remote]) {
					const _nlpIndex = arrays.firstIndex(rawResults[SearchResultIdx.Remote].filterMatches, m => m.setting.key === props.key);
					nlpIndex = _nlpIndex >= 0 ? _nlpIndex : undefined;
				}
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
			}
		}

		const reportedTarget = props.settingsTarget === ConfigurationTarget.USER ? 'user' :
			props.settingsTarget === ConfigurationTarget.WORKSPACE ? 'workspace' :
				'folder';

		const data = {
			key: props.key,
			query: props.query,
			groupId,
			nlpIndex,
			displayIndex,
			showConfiguredOnly: props.showConfiguredOnly,
			isReset: props.isReset,
			target: reportedTarget
		};

		/* __GDPR__
535
			"settingsEditor.settingModified" : {
536 537 538 539 540 541 542 543 544 545
				"key" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
				"query" : { "classification": "CustomerContent", "purpose": "FeatureInsight" },
				"groupId" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
				"nlpIndex" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
				"displayIndex" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
				"showConfiguredOnly" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
				"isReset" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
				"target" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
			}
		*/
546
		this.telemetryService.publicLog('settingsEditor.settingModified', data);
R
Rob Lourens 已提交
547 548
	}

549
	private render(token: CancellationToken): TPromise<any> {
R
Rob Lourens 已提交
550 551
		if (this.input) {
			return this.input.resolve()
552 553 554 555 556 557
				.then((model: DefaultSettingsEditorModel) => {
					if (token.isCancellationRequested) {
						return void 0;
					}

					this.defaultSettingsEditorModel = model;
558
					this.onConfigUpdate();
559
				});
R
Rob Lourens 已提交
560 561 562 563
		}
		return TPromise.as(null);
	}

564
	private toggleSearchMode(): void {
565 566 567 568
		DOM.removeClass(this.rootElement, 'search-mode');
		if (this.configurationService.getValue('workbench.settings.settingsSearchTocBehavior') === 'hide') {
			DOM.toggleClass(this.rootElement, 'search-mode', !!this.searchResultModel);
		}
569 570
	}

571
	private onConfigUpdate(): TPromise<void> {
572
		const groups = this.defaultSettingsEditorModel.settingsGroups.slice(1); // Without commonlyUsed
573 574 575
		const dividedGroups = collections.groupBy(groups, g => g.contributedByExtension ? 'extension' : 'core');
		const resolvedSettingsRoot = resolveSettingsTree(tocData, dividedGroups.core);
		const commonlyUsed = resolveSettingsTree(commonlyUsedData, dividedGroups.core);
576 577
		resolvedSettingsRoot.children.unshift(commonlyUsed);

578 579
		resolvedSettingsRoot.children.push(resolveExtensionsSettings(dividedGroups.extension || []));

580 581 582 583
		if (this.searchResultModel) {
			this.searchResultModel.updateChildren();
		}

584 585 586 587
		if (this.settingsTreeModel) {
			this.settingsTreeModel.update(resolvedSettingsRoot);
		} else {
			this.settingsTreeModel = this.instantiationService.createInstance(SettingsTreeModel, this.viewState, resolvedSettingsRoot);
588
			this.settingsTree.setInput(this.settingsTreeModel.root);
589 590 591 592 593 594 595

			this.tocTreeModel.settingsTreeRoot = this.settingsTreeModel.root as SettingsTreeGroupElement;
			if (this.tocTree.getInput()) {
				this.tocTree.refresh();
			} else {
				this.tocTree.setInput(this.tocTreeModel);
			}
596 597 598 599 600
		}

		return this.refreshTreeAndMaintainFocus();
	}

R
Rob Lourens 已提交
601 602 603 604 605 606 607 608
	private refreshTreeAndMaintainFocus(): TPromise<any> {
		// Sort of a hack to maintain focus on the focused control across a refresh
		const focusedRowItem = DOM.findParentWithClass(<HTMLElement>document.activeElement, 'setting-item');
		const focusedRowId = focusedRowItem && focusedRowItem.id;
		const selection = focusedRowId && document.activeElement.tagName.toLowerCase() === 'input' ?
			(<HTMLInputElement>document.activeElement).selectionStart :
			null;

609 610 611
		return this.settingsTree.refresh()
			.then(() => {
				if (focusedRowId) {
612
					this.focusEditControlForRow(focusedRowId, selection);
R
Rob Lourens 已提交
613
				}
614 615 616 617
			})
			.then(() => {
				return this.tocTree.refresh();
			});
618 619
	}

620 621 622 623 624 625 626 627 628 629 630
	private focusEditControlForRow(id: string, selection?: number): void {
		const rowSelector = `.setting-item#${id}`;
		const inputElementToFocus: HTMLElement = this.settingsTreeContainer.querySelector(`${rowSelector} input, ${rowSelector} select, ${rowSelector} a, ${rowSelector} .monaco-custom-checkbox`);
		if (inputElementToFocus) {
			inputElementToFocus.focus();
			if (typeof selection === 'number') {
				(<HTMLInputElement>inputElementToFocus).setSelectionRange(selection, selection);
			}
		}
	}

631
	private onSearchInputChanged(): void {
R
Rob Lourens 已提交
632 633
		const query = this.searchWidget.getValue().trim();
		this.delayedFilterLogging.cancel();
634
		this.triggerSearch(query).then(() => {
635
			if (query && this.searchResultModel) {
636
				this.delayedFilterLogging.trigger(() => this.reportFilteringUsed(query, this.searchResultModel.getUniqueResults()));
637 638
			}
		});
R
Rob Lourens 已提交
639 640 641 642
	}

	private triggerSearch(query: string): TPromise<void> {
		if (query) {
R
Rob Lourens 已提交
643
			return this.searchInProgress = TPromise.join([
R
Rob Lourens 已提交
644
				this.localSearchDelayer.trigger(() => this.localFilterPreferences(query)),
645
				this.remoteSearchThrottle.trigger(() => this.remoteSearchPreferences(query), 500)
R
Rob Lourens 已提交
646 647 648
			]).then(() => {
				this.searchInProgress = null;
			});
R
Rob Lourens 已提交
649 650 651
		} else {
			this.localSearchDelayer.cancel();
			this.remoteSearchThrottle.cancel();
R
Rob Lourens 已提交
652 653 654
			if (this.searchInProgress && this.searchInProgress.cancel) {
				this.searchInProgress.cancel();
			}
R
Rob Lourens 已提交
655

656
			this.searchResultModel = null;
657
			this.tocTreeModel.currentSearchModel = null;
658
			this.viewState.filterToCategory = null;
659
			this.tocTree.refresh();
660
			this.toggleSearchMode();
661
			this.settingsTree.setInput(this.settingsTreeModel.root);
662

R
Rob Lourens 已提交
663 664 665 666
			return TPromise.wrap(null);
		}
	}

R
Rob Lourens 已提交
667 668 669 670 671 672
	private expandAll(tree: ITree): void {
		const nav = tree.getNavigator();
		let cur;
		while (cur = nav.next()) {
			tree.expand(cur);
		}
673 674
	}

675 676 677 678 679 680 681 682 683 684 685
	private reportFilteringUsed(query: string, results: ISearchResult[]): void {
		const nlpResult = results[SearchResultIdx.Remote];
		const nlpMetadata = nlpResult && nlpResult.metadata;

		const durations = {};
		durations['nlpResult'] = nlpMetadata && nlpMetadata.duration;

		// Count unique results
		const counts = {};
		const filterResult = results[SearchResultIdx.Local];
		counts['filterResult'] = filterResult.filterMatches.length;
686 687
		if (nlpResult) {
			counts['nlpResult'] = nlpResult.filterMatches.length;
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
		}

		const requestCount = nlpMetadata && nlpMetadata.requestCount;

		const data = {
			query,
			durations,
			counts,
			requestCount
		};

		/* __GDPR__
			"settingsEditor.filter" : {
				"query": { "classification": "CustomerContent", "purpose": "FeatureInsight" },
				"durations.nlpResult" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
				"counts.nlpResult" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
				"counts.filterResult" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
				"requestCount" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
			}
		*/
708
		this.telemetryService.publicLog('settingsEditor.filter', data);
709 710
	}

R
Rob Lourens 已提交
711
	private localFilterPreferences(query: string): TPromise<void> {
712 713
		const localSearchProvider = this.preferencesSearchService.getLocalSearchProvider(query);
		return this.filterOrSearchPreferences(query, SearchResultIdx.Local, localSearchProvider);
R
Rob Lourens 已提交
714 715 716
	}

	private remoteSearchPreferences(query: string): TPromise<void> {
717 718
		const remoteSearchProvider = this.preferencesSearchService.getRemoteSearchProvider(query);
		return this.filterOrSearchPreferences(query, SearchResultIdx.Remote, remoteSearchProvider);
R
Rob Lourens 已提交
719 720 721 722 723
	}

	private filterOrSearchPreferences(query: string, type: SearchResultIdx, searchProvider: ISearchProvider): TPromise<void> {
		const filterPs: TPromise<ISearchResult>[] = [this._filterOrSearchPreferencesModel(query, this.defaultSettingsEditorModel, searchProvider)];

R
Rob Lourens 已提交
724 725 726 727 728 729 730
		let isCanceled = false;
		return new TPromise(resolve => {
			return TPromise.join(filterPs).then(results => {
				if (isCanceled) {
					// Handle cancellation like this because cancellation is lost inside the search provider due to async/await
					return null;
				}
731

R
Rob Lourens 已提交
732 733
				const [result] = results;
				if (!this.searchResultModel) {
734
					this.searchResultModel = this.instantiationService.createInstance(SearchResultModel, this.viewState);
735
					this.searchResultModel.setResult(type, result);
736
					this.tocTreeModel.currentSearchModel = this.searchResultModel;
737
					this.toggleSearchMode();
R
Rob Lourens 已提交
738
					this.settingsTree.setInput(this.searchResultModel);
739 740
				} else {
					this.searchResultModel.setResult(type, result);
R
Rob Lourens 已提交
741 742
				}

743
				this.tocTreeModel.update();
R
Rob Lourens 已提交
744 745 746 747
				resolve(this.refreshTreeAndMaintainFocus());
			});
		}, () => {
			isCanceled = true;
R
Rob Lourens 已提交
748 749 750 751 752 753 754 755 756 757 758
		});
	}

	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__
759
						"settingsEditor.searchError" : {
R
Rob Lourens 已提交
760 761 762 763 764 765 766
							"message": { "classification": "CallstackOrException", "purpose": "FeatureInsight" },
							"filter": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
						}
					*/
					const message = getErrorMessage(err).trim();
					if (message && message !== 'Error') {
						// "Error" = any generic network error
767
						this.telemetryService.publicLog('settingsEditor.searchError', { message, filter });
R
Rob Lourens 已提交
768 769 770 771 772 773 774
						this.logService.info('Setting search error: ' + message);
					}
					return null;
				}
			});
	}

775
	private layoutTrees(dimension: DOM.Dimension): void {
776
		const listHeight = dimension.height - (DOM.getDomNodePagePosition(this.headerContainer).height + 12 /*padding*/);
777 778
		this.settingsTreeContainer.style.height = `${listHeight}px`;
		this.settingsTree.layout(listHeight, 800);
779 780 781 782

		const tocHeight = listHeight - 5; // padding
		this.tocTreeContainer.style.height = `${tocHeight}px`;
		this.tocTree.layout(tocHeight, 175);
783
	}
R
Rob Lourens 已提交
784
}