settingsEditor2.ts 48.5 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';
R
Rob Lourens 已提交
7
import { ITreeElement } from 'vs/base/browser/ui/tree/tree';
8
import * as arrays from 'vs/base/common/arrays';
9
import { Delayer, ThrottledDelayer, timeout } from 'vs/base/common/async';
10
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
R
Rob Lourens 已提交
11
import * as collections from 'vs/base/common/collections';
12
import { getErrorMessage, isPromiseCanceledError } from 'vs/base/common/errors';
R
Rob Lourens 已提交
13
import { Iterator } from 'vs/base/common/iterator';
P
Peng Lyu 已提交
14
import * as strings from 'vs/base/common/strings';
15
import { isArray, withNullAsUndefined } from 'vs/base/common/types';
16
import { URI } from 'vs/base/common/uri';
R
Rob Lourens 已提交
17 18
import 'vs/css!./media/settingsEditor2';
import { localize } from 'vs/nls';
19
import { ConfigurationTarget, IConfigurationOverrides, IConfigurationService } from 'vs/platform/configuration/common/configuration';
R
Rob Lourens 已提交
20
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
R
Rob Lourens 已提交
21
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
R
Rob Lourens 已提交
22
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
23
import { ILogService } from 'vs/platform/log/common/log';
J
Jackson Kearl 已提交
24
import { INotificationService } from 'vs/platform/notification/common/notification';
B
Benjamin Pasero 已提交
25
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
R
Rob Lourens 已提交
26
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
J
Jackson Kearl 已提交
27
import { badgeBackground, badgeForeground, contrastBorder, editorForeground } from 'vs/platform/theme/common/colorRegistry';
28
import { attachStylerCallback } from 'vs/platform/theme/common/styler';
29
import { IThemeService } from 'vs/platform/theme/common/themeService';
R
Rob Lourens 已提交
30
import { BaseEditor } from 'vs/workbench/browser/parts/editor/baseEditor';
31
import { IEditor, IEditorMemento } from 'vs/workbench/common/editor';
32
import { attachSuggestEnabledInputBoxStyler, SuggestEnabledInput } from 'vs/workbench/contrib/codeEditor/browser/suggestEnabledInput/suggestEnabledInput';
33 34 35 36 37 38
import { SettingsTarget, SettingsTargetsWidget } from 'vs/workbench/contrib/preferences/browser/preferencesWidgets';
import { commonlyUsedData, tocData } from 'vs/workbench/contrib/preferences/browser/settingsLayout';
import { AbstractSettingRenderer, ISettingLinkClickEvent, ISettingOverrideClickEvent, resolveExtensionsSettings, resolveSettingsTree, SettingsTree, SettingTreeRenderers } from 'vs/workbench/contrib/preferences/browser/settingsTree';
import { ISettingsEditorViewState, parseQuery, SearchResultIdx, SearchResultModel, SettingsTreeElement, SettingsTreeGroupChild, SettingsTreeGroupElement, SettingsTreeModel, SettingsTreeSettingElement } from 'vs/workbench/contrib/preferences/browser/settingsTreeModels';
import { settingsTextInputBorder } from 'vs/workbench/contrib/preferences/browser/settingsWidgets';
import { createTOCIterator, TOCTree, TOCTreeModel } from 'vs/workbench/contrib/preferences/browser/tocTree';
39
import { CONTEXT_SETTINGS_EDITOR, CONTEXT_SETTINGS_SEARCH_FOCUS, CONTEXT_TOC_ROW_FOCUS, EXTENSION_SETTING_TAG, IPreferencesSearchService, ISearchProvider, MODIFIED_SETTING_TAG, SETTINGS_EDITOR_COMMAND_SHOW_CONTEXT_MENU } from 'vs/workbench/contrib/preferences/common/preferences';
40
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
41
import { IPreferencesService, ISearchResult, ISettingsEditorModel, ISettingsEditorOptions, SettingsEditorOptions, SettingValueType } from 'vs/workbench/services/preferences/common/preferences';
42
import { SettingsEditor2Input } from 'vs/workbench/services/preferences/common/preferencesEditorInput';
43
import { Settings2EditorModel } from 'vs/workbench/services/preferences/common/preferencesModels';
R
Rob Lourens 已提交
44

R
Rob Lourens 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57
function createGroupIterator(group: SettingsTreeGroupElement): Iterator<ITreeElement<SettingsTreeGroupChild>> {
	const groupsIt = Iterator.fromArray(group.children);

	return Iterator.map(groupsIt, g => {
		return {
			element: g,
			children: g instanceof SettingsTreeGroupElement ?
				createGroupIterator(g) :
				undefined
		};
	});
}

58 59
const $ = DOM.$;

R
Rob Lourens 已提交
60 61 62 63
interface IFocusEventFromScroll extends KeyboardEvent {
	fromScroll: true;
}

64
const SETTINGS_EDITOR_STATE_KEY = 'settingsEditorState';
R
Rob Lourens 已提交
65 66
export class SettingsEditor2 extends BaseEditor {

R
Rob Lourens 已提交
67
	static readonly ID: string = 'workbench.editor.settings2';
68
	private static NUM_INSTANCES: number = 0;
G
Guy Waldman 已提交
69 70
	private static SETTING_UPDATE_FAST_DEBOUNCE: number = 200;
	private static SETTING_UPDATE_SLOW_DEBOUNCE: number = 1000;
R
Rob Lourens 已提交
71

72
	private static readonly SUGGESTIONS: string[] = [
P
Peng Lyu 已提交
73
		`@${MODIFIED_SETTING_TAG}`, '@tag:usesOnlineServices', `@${EXTENSION_SETTING_TAG}`
74 75
	];

76 77 78
	private static shouldSettingUpdateFast(type: SettingValueType | SettingValueType[]): boolean {
		if (isArray(type)) {
			// nullable integer/number or complex
G
Guy Waldman 已提交
79
			return false;
80
		}
R
Rob Lourens 已提交
81
		return type === SettingValueType.Enum ||
P
Pine Wu 已提交
82
			type === SettingValueType.ArrayOfString ||
R
Rob Lourens 已提交
83 84 85
			type === SettingValueType.Complex ||
			type === SettingValueType.Boolean ||
			type === SettingValueType.Exclude;
86 87
	}

88
	private defaultSettingsEditorModel: Settings2EditorModel;
R
Rob Lourens 已提交
89

90
	private rootElement: HTMLElement;
R
Rob Lourens 已提交
91
	private headerContainer: HTMLElement;
92
	private searchWidget: SuggestEnabledInput;
93
	private countElement: HTMLElement;
R
Rob Lourens 已提交
94 95
	private settingsTargetsWidget: SettingsTargetsWidget;

96
	private settingsTreeContainer: HTMLElement;
R
Rob Lourens 已提交
97 98
	private settingsTree: SettingsTree;
	private settingRenderers: SettingTreeRenderers;
99
	private tocTreeModel: TOCTreeModel;
100
	private settingsTreeModel: SettingsTreeModel;
101
	private noResultsMessage: HTMLElement;
102
	private clearFilterLinkContainer: HTMLElement;
R
Rob Lourens 已提交
103

R
Rob Lourens 已提交
104
	private tocTreeContainer: HTMLElement;
R
Rob Lourens 已提交
105
	private tocTree: TOCTree;
R
Rob Lourens 已提交
106

107 108
	private settingsAriaExtraLabelsContainer: HTMLElement;

R
Rob Lourens 已提交
109 110 111
	private delayedFilterLogging: Delayer<void>;
	private localSearchDelayer: Delayer<void>;
	private remoteSearchThrottle: ThrottledDelayer<void>;
R
Rob Lourens 已提交
112
	private searchInProgress: CancellationTokenSource | null;
113

114 115
	private settingFastUpdateDelayer: Delayer<void>;
	private settingSlowUpdateDelayer: Delayer<void>;
R
Rob Lourens 已提交
116
	private pendingSettingUpdate: { key: string, value: any } | null;
R
Rob Lourens 已提交
117

118
	private readonly viewState: ISettingsEditorViewState;
R
Rob Lourens 已提交
119
	private _searchResultModel: SearchResultModel | null;
120

121
	private tocRowFocused: IContextKey<boolean>;
122 123
	private inSettingsEditorContextKey: IContextKey<boolean>;
	private searchFocusContextKey: IContextKey<boolean>;
124

125
	private scheduledRefreshes: Map<string, DOM.IFocusTracker>;
R
Rob Lourens 已提交
126
	private lastFocusedSettingElement: string;
127

128 129 130
	/** Don't spam warnings */
	private hasWarnedMissingSettings: boolean;

131 132
	private editorMemento: IEditorMemento<ISettingsEditor2State>;

R
Rob Lourens 已提交
133
	private tocFocusedElement: SettingsTreeGroupElement | null;
134 135
	private settingsTreeScrollTop = 0;

R
Rob Lourens 已提交
136 137
	constructor(
		@ITelemetryService telemetryService: ITelemetryService,
138
		@IConfigurationService private readonly configurationService: IConfigurationService,
R
Rob Lourens 已提交
139
		@IThemeService themeService: IThemeService,
140 141 142 143
		@IPreferencesService private readonly preferencesService: IPreferencesService,
		@IInstantiationService private readonly instantiationService: IInstantiationService,
		@IPreferencesSearchService private readonly preferencesSearchService: IPreferencesSearchService,
		@ILogService private readonly logService: ILogService,
144
		@IContextKeyService contextKeyService: IContextKeyService,
145 146
		@IStorageService private readonly storageService: IStorageService,
		@INotificationService private readonly notificationService: INotificationService,
147
		@IEditorGroupsService protected editorGroupService: IEditorGroupsService,
148
		@IKeybindingService private readonly keybindingService: IKeybindingService
R
Rob Lourens 已提交
149
	) {
150
		super(SettingsEditor2.ID, telemetryService, themeService, storageService);
R
Rob Lourens 已提交
151
		this.delayedFilterLogging = new Delayer<void>(1000);
152
		this.localSearchDelayer = new Delayer(300);
153
		this.remoteSearchThrottle = new ThrottledDelayer(200);
R
Rob Lourens 已提交
154
		this.viewState = { settingsTarget: ConfigurationTarget.USER_LOCAL };
R
Rob Lourens 已提交
155

156 157
		this.settingFastUpdateDelayer = new Delayer<void>(SettingsEditor2.SETTING_UPDATE_FAST_DEBOUNCE);
		this.settingSlowUpdateDelayer = new Delayer<void>(SettingsEditor2.SETTING_UPDATE_SLOW_DEBOUNCE);
158

159 160
		this.inSettingsEditorContextKey = CONTEXT_SETTINGS_EDITOR.bindTo(contextKeyService);
		this.searchFocusContextKey = CONTEXT_SETTINGS_SEARCH_FOCUS.bindTo(contextKeyService);
161
		this.tocRowFocused = CONTEXT_TOC_ROW_FOCUS.bindTo(contextKeyService);
162

163 164
		this.scheduledRefreshes = new Map<string, DOM.IFocusTracker>();

B
Benjamin Pasero 已提交
165
		this.editorMemento = this.getEditorMemento<ISettingsEditor2State>(editorGroupService, SETTINGS_EDITOR_STATE_KEY);
166

167
		this._register(configurationService.onDidChangeConfiguration(e => {
168 169 170
			if (e.source !== ConfigurationTarget.DEFAULT) {
				this.onConfigUpdate(e.affectedKeys);
			}
171
		}));
R
Rob Lourens 已提交
172 173
	}

174 175 176 177 178 179 180
	get minimumWidth(): number { return 375; }
	get maximumWidth(): number { return Number.POSITIVE_INFINITY; }

	// these setters need to exist because this extends from BaseEditor
	set minimumWidth(value: number) { /*noop*/ }
	set maximumWidth(value: number) { /*noop*/ }

R
Rob Lourens 已提交
181 182 183 184
	private get currentSettingsModel() {
		return this.searchResultModel || this.settingsTreeModel;
	}

R
Rob Lourens 已提交
185
	private get searchResultModel(): SearchResultModel | null {
186 187 188
		return this._searchResultModel;
	}

R
Rob Lourens 已提交
189
	private set searchResultModel(value: SearchResultModel | null) {
190 191 192 193 194
		this._searchResultModel = value;

		DOM.toggleClass(this.rootElement, 'search-mode', !!this._searchResultModel);
	}

R
Rob Lourens 已提交
195 196 197
	private get currentSettingsContextMenuKeyBindingLabel(): string {
		const keybinding = this.keybindingService.lookupKeybinding(SETTINGS_EDITOR_COMMAND_SHOW_CONTEXT_MENU);
		return (keybinding && keybinding.getAriaLabel()) || '';
198 199
	}

R
Rob Lourens 已提交
200
	createEditor(parent: HTMLElement): void {
201
		parent.setAttribute('tabindex', '-1');
202
		this.rootElement = DOM.append(parent, $('.settings-editor'));
R
Rob Lourens 已提交
203

204 205
		this.createHeader(this.rootElement);
		this.createBody(this.rootElement);
206
		this.updateStyles();
R
Rob Lourens 已提交
207 208
	}

R
Rob Lourens 已提交
209
	setInput(input: SettingsEditor2Input, options: SettingsEditorOptions | null, token: CancellationToken): Promise<void> {
210
		this.inSettingsEditorContextKey.set(true);
211
		return super.setInput(input, options, token)
212
			.then(() => timeout(0)) // Force setInput to be async
R
Rob Lourens 已提交
213 214 215
			.then(() => {
				return this.render(token);
			})
R
Rob Lourens 已提交
216
			.then(() => {
R
Rob Lourens 已提交
217 218
				options = options || SettingsEditorOptions.create({});

R
Rob Lourens 已提交
219
				if (!this.viewState.settingsTarget) {
R
Rob Lourens 已提交
220
					if (!options.target) {
R
Rob Lourens 已提交
221
						options.target = ConfigurationTarget.USER_LOCAL;
222
					}
223
				}
R
Rob Lourens 已提交
224

225
				this._setOptions(options);
226

R
Rob Lourens 已提交
227 228 229 230
				this._register(input.onDispose(() => {
					this.searchWidget.setValue('');
				}));

231 232
				// Init TOC selection
				this.updateTreeScrollSync();
233 234

				this.restoreCachedState();
R
Rob Lourens 已提交
235
			});
R
Rob Lourens 已提交
236 237
	}

238
	private restoreCachedState(): void {
R
Rob Lourens 已提交
239
		const cachedState = this.group && this.input && this.editorMemento.loadEditorState(this.group, this.input);
240
		if (cachedState && typeof cachedState.target === 'object') {
241 242 243 244 245 246 247 248 249 250 251
			cachedState.target = URI.revive(cachedState.target);
		}

		if (cachedState) {
			const settingsTarget = cachedState.target;
			this.settingsTargetsWidget.settingsTarget = settingsTarget;
			this.onDidSettingsTargetChange(settingsTarget);
			this.searchWidget.setValue(cachedState.searchQuery);
		}
	}

R
Rob Lourens 已提交
252
	setOptions(options: SettingsEditorOptions | null): void {
253 254
		super.setOptions(options);

R
Rob Lourens 已提交
255 256 257
		if (options) {
			this._setOptions(options);
		}
258
	}
259

260
	private _setOptions(options: SettingsEditorOptions): void {
261 262 263 264
		if (options.query) {
			this.searchWidget.setValue(options.query);
		}

265
		const target: SettingsTarget = options.folderUri || <SettingsTarget>options.target;
R
Rob Lourens 已提交
266 267 268 269
		if (target) {
			this.settingsTargetsWidget.settingsTarget = target;
			this.viewState.settingsTarget = target;
		}
270 271
	}

272 273
	clearInput(): void {
		this.inSettingsEditorContextKey.set(false);
R
Rob Lourens 已提交
274 275 276 277
		if (this.input) {
			this.editorMemento.clearEditorState(this.input, this.group);
		}

278 279 280
		super.clearInput();
	}

R
Rob Lourens 已提交
281
	layout(dimension: DOM.Dimension): void {
282 283
		this.layoutTrees(dimension);

R
Rob Lourens 已提交
284 285
		const innerWidth = dimension.width - 24 * 2; // 24px padding on left and right
		const monacoWidth = (innerWidth > 1000 ? 1000 : innerWidth) - 10;
286 287
		this.searchWidget.layout({ height: 20, width: monacoWidth });

288 289
		DOM.toggleClass(this.rootElement, 'mid-width', dimension.width < 1000 && dimension.width >= 600);
		DOM.toggleClass(this.rootElement, 'narrow-width', dimension.width < 600);
R
Rob Lourens 已提交
290 291 292
	}

	focus(): void {
R
Rob Lourens 已提交
293
		if (this.lastFocusedSettingElement) {
R
Rob Lourens 已提交
294
			const elements = this.settingRenderers.getDOMElementsForSettingKey(this.settingsTree.getHTMLElement(), this.lastFocusedSettingElement);
R
Rob Lourens 已提交
295
			if (elements.length) {
R
Rob Lourens 已提交
296
				const control = elements[0].querySelector(AbstractSettingRenderer.CONTROL_SELECTOR);
R
Rob Lourens 已提交
297 298 299 300 301 302 303
				if (control) {
					(<HTMLElement>control).focus();
					return;
				}
			}
		}

304 305 306
		this.focusSearch();
	}

307
	focusSettings(): void {
308 309 310 311 312
		// Update ARIA global labels
		const labelElement = this.settingsAriaExtraLabelsContainer.querySelector('#settings_aria_more_actions_shortcut_label');
		if (labelElement) {
			const settingsContextMenuShortcut = this.currentSettingsContextMenuKeyBindingLabel;
			if (settingsContextMenuShortcut) {
313
				labelElement.setAttribute('aria-label', localize('settingsContextMenuAriaShortcut', "For more actions, Press {0}.", settingsContextMenuShortcut));
314 315 316
			}
		}

R
Rob Lourens 已提交
317
		const firstFocusable = this.settingsTree.getHTMLElement().querySelector(AbstractSettingRenderer.CONTROL_SELECTOR);
318 319
		if (firstFocusable) {
			(<HTMLElement>firstFocusable).focus();
320 321 322
		}
	}

323
	showContextMenu(): void {
R
Rob Lourens 已提交
324 325 326 327 328 329
		const activeElement = this.getActiveElementInSettingsTree();
		if (!activeElement) {
			return;
		}

		const settingDOMElement = this.settingRenderers.getSettingDOMElementForDOMElement(activeElement);
330 331 332 333
		if (!settingDOMElement) {
			return;
		}

R
Rob Lourens 已提交
334
		const focusedKey = this.settingRenderers.getKeyForDOMElementInSetting(settingDOMElement);
335 336 337 338 339 340
		if (!focusedKey) {
			return;
		}

		const elements = this.currentSettingsModel.getElementsByName(focusedKey);
		if (elements && elements[0]) {
R
Rob Lourens 已提交
341
			this.settingRenderers.showContextMenu(elements[0], settingDOMElement);
342 343 344
		}
	}

345
	focusSearch(filter?: string, selectAll = true): void {
346 347 348 349
		if (filter && this.searchWidget) {
			this.searchWidget.setValue(filter);
		}

350
		this.searchWidget.focus(selectAll);
R
Rob Lourens 已提交
351 352
	}

353
	clearSearchResults(): void {
354
		this.searchWidget.setValue('');
355 356
	}

357 358 359 360 361 362 363 364 365 366
	clearSearchFilters(): void {
		let query = this.searchWidget.getValue();

		SettingsEditor2.SUGGESTIONS.forEach(suggestion => {
			query = query.replace(suggestion, '');
		});

		this.searchWidget.setValue(query.trim());
	}

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

		const searchContainer = DOM.append(this.headerContainer, $('.search-container'));
371

R
Rob Lourens 已提交
372
		const searchBoxLabel = localize('SearchSettings.AriaLabel', "Search settings");
373 374 375
		this.searchWidget = this._register(this.instantiationService.createInstance(SuggestEnabledInput, `${SettingsEditor2.ID}.searchbox`, searchContainer, {
			triggerCharacters: ['@'],
			provideResults: (query: string) => {
P
Peng Lyu 已提交
376
				return SettingsEditor2.SUGGESTIONS.filter(tag => query.indexOf(tag) === -1).map(tag => strings.endsWith(tag, ':') ? tag : tag + ' ');
377
			}
378
		}, searchBoxLabel, 'settingseditor:searchinput' + SettingsEditor2.NUM_INSTANCES++, {
379 380 381
				placeholderText: searchBoxLabel,
				focusContextKey: this.searchFocusContextKey,
				// TODO: Aria-live
J
Jeremy Shore 已提交
382 383
			})
		);
384

385 386 387 388
		this._register(this.searchWidget.onFocus(() => {
			this.lastFocusedSettingElement = '';
		}));

389 390 391 392
		this._register(attachSuggestEnabledInputBoxStyler(this.searchWidget, this.themeService, {
			inputBorder: settingsTextInputBorder
		}));

393 394 395 396
		this.countElement = DOM.append(searchContainer, DOM.$('.settings-count-widget'));
		this._register(attachStylerCallback(this.themeService, { badgeBackground, contrastBorder, badgeForeground }, colors => {
			const background = colors.badgeBackground ? colors.badgeBackground.toString() : null;
			const border = colors.contrastBorder ? colors.contrastBorder.toString() : null;
R
Rob Lourens 已提交
397
			const foreground = colors.badgeForeground ? colors.badgeForeground.toString() : null;
398 399

			this.countElement.style.backgroundColor = background;
R
Rob Lourens 已提交
400
			this.countElement.style.color = foreground;
401 402 403 404 405 406

			this.countElement.style.borderWidth = border ? '1px' : null;
			this.countElement.style.borderStyle = border ? 'solid' : null;
			this.countElement.style.borderColor = border;
		}));

407
		this._register(this.searchWidget.onInputDidChange(() => this.onSearchInputChanged()));
R
Rob Lourens 已提交
408

409
		const headerControlsContainer = DOM.append(this.headerContainer, $('.settings-header-controls'));
R
Rob Lourens 已提交
410
		const targetWidgetContainer = DOM.append(headerControlsContainer, $('.settings-target-container'));
R
Rob Lourens 已提交
411 412
		this.settingsTargetsWidget = this._register(this.instantiationService.createInstance(SettingsTargetsWidget, targetWidgetContainer, { enableRemoteSettings: true }));
		this.settingsTargetsWidget.settingsTarget = ConfigurationTarget.USER_LOCAL;
413
		this.settingsTargetsWidget.onDidTargetChange(target => this.onDidSettingsTargetChange(target));
R
Rob Lourens 已提交
414 415
	}

416 417 418
	private onDidSettingsTargetChange(target: SettingsTarget): void {
		this.viewState.settingsTarget = target;

419 420
		// TODO Instead of rebuilding the whole model, refresh and uncache the inspected setting value
		this.onConfigUpdate(undefined, true);
421 422
	}

423
	private onDidClickSetting(evt: ISettingLinkClickEvent, recursed?: boolean): void {
424
		const elements = this.currentSettingsModel.getElementsByName(evt.targetKey);
425
		if (elements && elements[0]) {
426
			let sourceTop = this.settingsTree.getRelativeTop(evt.source);
R
Rob Lourens 已提交
427 428 429 430
			if (typeof sourceTop !== 'number') {
				return;
			}

431 432
			if (sourceTop < 0) {
				// e.g. clicked a searched element, now the search has been cleared
433
				sourceTop = 0.5;
434 435
			}

436
			this.settingsTree.reveal(elements[0], sourceTop);
437

R
Rob Lourens 已提交
438
			const domElements = this.settingRenderers.getDOMElementsForSettingKey(this.settingsTree.getHTMLElement(), evt.targetKey);
439
			if (domElements && domElements[0]) {
R
Rob Lourens 已提交
440
				const control = domElements[0].querySelector(AbstractSettingRenderer.CONTROL_SELECTOR);
441 442 443 444
				if (control) {
					(<HTMLElement>control).focus();
				}
			}
445 446 447 448 449 450
		} else if (!recursed) {
			const p = this.triggerSearch('');
			p.then(() => {
				this.searchWidget.setValue('');
				this.onDidClickSetting(evt, true);
			});
451 452 453
		}
	}

R
Rob Lourens 已提交
454
	switchToSettingsFile(): Promise<IEditor | null> {
455 456 457 458
		const query = parseQuery(this.searchWidget.getValue());
		return this.openSettingsFile(query.query);
	}

R
Rob Lourens 已提交
459
	private openSettingsFile(query?: string): Promise<IEditor | null> {
460 461
		const currentSettingsTarget = this.settingsTargetsWidget.settingsTarget;

462
		const options: ISettingsEditorOptions = { query };
R
Rob Lourens 已提交
463
		if (currentSettingsTarget === ConfigurationTarget.USER_LOCAL) {
464
			return this.preferencesService.openGlobalSettings(true, options);
R
Rob Lourens 已提交
465 466
		} else if (currentSettingsTarget === ConfigurationTarget.USER_REMOTE) {
			return this.preferencesService.openRemoteSettings();
467
		} else if (currentSettingsTarget === ConfigurationTarget.WORKSPACE) {
468
			return this.preferencesService.openWorkspaceSettings(true, options);
469
		} else {
470
			return this.preferencesService.openFolderSettings(currentSettingsTarget, true, options);
471
		}
R
Rob Lourens 已提交
472 473 474 475 476
	}

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

R
Rob Lourens 已提交
477
		this.noResultsMessage = DOM.append(bodyContainer, $('.no-results-message'));
478

479
		this.noResultsMessage.innerText = localize('noResults', "No Settings Found");
480 481 482 483 484

		this.clearFilterLinkContainer = $('span.clear-search-filters');

		this.clearFilterLinkContainer.textContent = ' - ';
		const clearFilterLink = DOM.append(this.clearFilterLinkContainer, $('a.pointer.prominent', { tabindex: 0 }, localize('clearSearchFilters', 'Clear Filters')));
485
		this._register(DOM.addDisposableListener(clearFilterLink, DOM.EventType.CLICK, (e: MouseEvent) => {
486 487 488 489 490 491 492 493 494 495
			DOM.EventHelper.stop(e, false);
			this.clearSearchFilters();
		}));

		DOM.append(this.noResultsMessage, this.clearFilterLinkContainer);

		const clearSearchContainer = $('span.clear-search');
		clearSearchContainer.textContent = ' - ';

		const clearSearch = DOM.append(clearSearchContainer, $('a.pointer.prominent', { tabindex: 0 }, localize('clearSearch', 'Clear Search')));
496
		this._register(DOM.addDisposableListener(clearSearch, DOM.EventType.CLICK, (e: MouseEvent) => {
497 498
			DOM.EventHelper.stop(e, false);
			this.clearSearchResults();
499
			this.focusSearch();
500 501 502 503
		}));

		DOM.append(this.noResultsMessage, clearSearchContainer);

504 505 506 507
		this._register(attachStylerCallback(this.themeService, { editorForeground }, colors => {
			this.noResultsMessage.style.color = colors.editorForeground ? colors.editorForeground.toString() : null;
		}));

R
Rob Lourens 已提交
508 509
		this.createTOC(bodyContainer);

510 511 512 513 514
		this.createFocusSink(
			bodyContainer,
			e => {
				if (DOM.findParentWithClass(e.relatedTarget, 'settings-editor-tree')) {
					if (this.settingsTree.scrollTop > 0) {
515
						const firstElement = this.settingsTree.firstVisibleElement;
516 517 518 519 520 521 522 523 524 525 526 527 528
						this.settingsTree.reveal(firstElement, 0.1);
						return true;
					}
				} else {
					const firstControl = this.settingsTree.getHTMLElement().querySelector(AbstractSettingRenderer.CONTROL_SELECTOR);
					if (firstControl) {
						(<HTMLElement>firstControl).focus();
					}
				}

				return false;
			},
			'settings list focus helper');
R
Rob Lourens 已提交
529

R
Rob Lourens 已提交
530
		this.createSettingsTree(bodyContainer);
R
Rob Lourens 已提交
531

532 533 534 535 536
		this.createFocusSink(
			bodyContainer,
			e => {
				if (DOM.findParentWithClass(e.relatedTarget, 'settings-editor-tree')) {
					if (this.settingsTree.scrollTop < this.settingsTree.scrollHeight) {
537
						const lastElement = this.settingsTree.lastVisibleElement;
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
						this.settingsTree.reveal(lastElement, 0.9);
						return true;
					}
				}

				return false;
			},
			'settings list focus helper'
		);
	}

	private createFocusSink(container: HTMLElement, callback: (e: any) => boolean, label: string): HTMLElement {
		const listFocusSink = DOM.append(container, $('.settings-tree-focus-sink'));
		listFocusSink.setAttribute('aria-label', label);
		listFocusSink.tabIndex = 0;
		this._register(DOM.addDisposableListener(listFocusSink, 'focus', (e: any) => {
			if (e.relatedTarget && callback(e)) {
				e.relatedTarget.focus();
			}
		}));

		return listFocusSink;
	}
561

R
Rob Lourens 已提交
562
	private createTOC(parent: HTMLElement): void {
563
		this.tocTreeModel = this.instantiationService.createInstance(TOCTreeModel, this.viewState);
R
Rob Lourens 已提交
564 565
		this.tocTreeContainer = DOM.append(parent, $('.settings-toc-container'));

566 567
		this.tocTree = this._register(this.instantiationService.createInstance(TOCTree,
			DOM.append(this.tocTreeContainer, $('.settings-toc-wrapper')),
R
Rob Lourens 已提交
568
			this.viewState));
R
Rob Lourens 已提交
569

570
		this._register(this.tocTree.onDidChangeFocus(e => {
R
Rob Lourens 已提交
571
			const element: SettingsTreeGroupElement | null = e.elements[0];
R
Rob Lourens 已提交
572 573 574
			if (this.tocFocusedElement === element) {
				return;
			}
575

R
Rob Lourens 已提交
576 577 578 579
			this.tocFocusedElement = element;
			this.tocTree.setSelection(element ? [element] : []);
			if (this.searchResultModel) {
				if (this.viewState.filterToCategory !== element) {
580
					this.viewState.filterToCategory = withNullAsUndefined(element);
581 582
					this.renderTree();
					this.settingsTree.scrollTop = 0;
R
Rob Lourens 已提交
583
				}
R
Rob Lourens 已提交
584
			} else if (element && (!e.browserEvent || !(<IFocusEventFromScroll>e.browserEvent).fromScroll)) {
R
Rob Lourens 已提交
585 586
				this.settingsTree.reveal(element, 0);
			}
587 588 589 590 591 592 593 594
		}));

		this._register(this.tocTree.onDidFocus(() => {
			this.tocRowFocused.set(true);
		}));

		this._register(this.tocTree.onDidBlur(() => {
			this.tocRowFocused.set(false);
R
Rob Lourens 已提交
595 596 597 598
		}));
	}

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

601 602 603 604 605 606 607 608
		// Add  ARIA extra labels div
		this.settingsAriaExtraLabelsContainer = DOM.append(this.settingsTreeContainer, $('.settings-aria-extra-labels'));
		this.settingsAriaExtraLabelsContainer.id = 'settings_aria_extra_labels';
		// Add global labels here
		const labelDiv = DOM.append(this.settingsAriaExtraLabelsContainer, $('.settings-aria-extra-label'));
		labelDiv.id = 'settings_aria_more_actions_shortcut_label';
		labelDiv.setAttribute('aria-label', '');

R
Rob Lourens 已提交
609 610 611
		this.settingRenderers = this.instantiationService.createInstance(SettingTreeRenderers);
		this._register(this.settingRenderers.onDidChangeSetting(e => this.onDidChangeSetting(e.key, e.value, e.type)));
		this._register(this.settingRenderers.onDidOpenSettings(settingKey => {
612
			this.openSettingsFile(settingKey);
613
		}));
R
Rob Lourens 已提交
614 615
		this._register(this.settingRenderers.onDidClickSettingLink(settingName => this.onDidClickSetting(settingName)));
		this._register(this.settingRenderers.onDidFocusSetting(element => {
R
Rob Lourens 已提交
616
			this.lastFocusedSettingElement = element.setting.key;
617 618
			this.settingsTree.reveal(element);
		}));
R
Rob Lourens 已提交
619
		this._register(this.settingRenderers.onDidClickOverrideElement((element: ISettingOverrideClickEvent) => {
620
			if (element.scope.toLowerCase() === 'workspace') {
J
Jeremy Shore 已提交
621
				this.settingsTargetsWidget.updateTarget(ConfigurationTarget.WORKSPACE);
622
			} else if (element.scope.toLowerCase() === 'user') {
R
Rob Lourens 已提交
623
				this.settingsTargetsWidget.updateTarget(ConfigurationTarget.USER_LOCAL);
624
			} else if (element.scope.toLowerCase() === 'remote') {
R
Rob Lourens 已提交
625
				this.settingsTargetsWidget.updateTarget(ConfigurationTarget.USER_REMOTE);
J
Jeremy Shore 已提交
626 627 628 629
			}

			this.searchWidget.setValue(element.targetKey);
		}));
630

631
		this.settingsTree = this._register(this.instantiationService.createInstance(SettingsTree,
632 633
			this.settingsTreeContainer,
			this.viewState,
R
Rob Lourens 已提交
634
			this.settingRenderers.allRenderers));
R
Rob Lourens 已提交
635
		this.settingsTree.getHTMLElement().attributes.removeNamedItem('tabindex');
636

637
		this._register(this.settingsTree.onDidScroll(() => {
638 639 640 641 642 643 644 645 646 647 648
			if (this.settingsTree.scrollTop === this.settingsTreeScrollTop) {
				return;
			}

			this.settingsTreeScrollTop = this.settingsTree.scrollTop;

			// setTimeout because calling setChildren on the settingsTree can trigger onDidScroll, so it fires when
			// setChildren has called on the settings tree but not the toc tree yet, so their rendered elements are out of sync
			setTimeout(() => {
				this.updateTreeScrollSync();
			}, 0);
649
		}));
650 651
	}

B
Benjamin Pasero 已提交
652 653
	private notifyNoSaveNeeded() {
		if (!this.storageService.getBoolean('hasNotifiedOfSettingsAutosave', StorageScope.GLOBAL, false)) {
B
Benjamin Pasero 已提交
654
			this.storageService.store('hasNotifiedOfSettingsAutosave', true, StorageScope.GLOBAL);
655 656
			this.notificationService.info(localize('settingsNoSaveNeeded', "Your changes are automatically saved as you edit."));
		}
J
Jackson Kearl 已提交
657 658
	}

659
	private onDidChangeSetting(key: string, value: any, type: SettingValueType | SettingValueType[]): void {
B
Benjamin Pasero 已提交
660
		this.notifyNoSaveNeeded();
661

662 663
		if (this.pendingSettingUpdate && this.pendingSettingUpdate.key !== key) {
			this.updateChangedSetting(key, value);
664 665
		}

666
		this.pendingSettingUpdate = { key, value };
667 668 669 670 671
		if (SettingsEditor2.shouldSettingUpdateFast(type)) {
			this.settingFastUpdateDelayer.trigger(() => this.updateChangedSetting(key, value));
		} else {
			this.settingSlowUpdateDelayer.trigger(() => this.updateChangedSetting(key, value));
		}
672 673
	}

674
	private updateTreeScrollSync(): void {
R
Rob Lourens 已提交
675
		this.settingRenderers.cancelSuggesters();
676 677 678 679
		if (this.searchResultModel) {
			return;
		}

R
Rob Lourens 已提交
680
		if (!this.tocTreeModel) {
681 682
			return;
		}
683

684
		const elementToSync = this.settingsTree.firstVisibleElement;
685 686 687 688
		const element = elementToSync instanceof SettingsTreeSettingElement ? elementToSync.parent :
			elementToSync instanceof SettingsTreeGroupElement ? elementToSync :
				null;

R
Rob Lourens 已提交
689 690 691 692 693 694 695 696
		// It's possible for this to be called when the TOC and settings tree are out of sync - e.g. when the settings tree has deferred a refresh because
		// it is focused. So, bail if element doesn't exist in the TOC.
		let nodeExists = true;
		try { this.tocTree.getNode(element); } catch (e) { nodeExists = false; }
		if (!nodeExists) {
			return;
		}

697 698 699 700 701 702
		if (element && this.tocTree.getSelection()[0] !== element) {
			const ancestors = this.getAncestors(element);
			ancestors.forEach(e => this.tocTree.expand(<SettingsTreeGroupElement>e));

			this.tocTree.reveal(element);
			const elementTop = this.tocTree.getRelativeTop(element);
R
Rob Lourens 已提交
703 704 705 706
			if (typeof elementTop !== 'number') {
				return;
			}

707 708 709 710 711 712 713 714 715 716
			this.tocTree.collapseAll();

			ancestors.forEach(e => this.tocTree.expand(<SettingsTreeGroupElement>e));
			if (elementTop < 0 || elementTop > 1) {
				this.tocTree.reveal(element);
			} else {
				this.tocTree.reveal(element, elementTop);
			}

			this.tocTree.expand(element);
R
Rob Lourens 已提交
717

718
			this.tocTree.setSelection([element]);
719

720
			const fakeKeyboardEvent = new KeyboardEvent('keydown');
R
Rob Lourens 已提交
721
			(<IFocusEventFromScroll>fakeKeyboardEvent).fromScroll = true;
722 723 724
			this.tocTree.setFocus([element], fakeKeyboardEvent);
		}
	}
725

726 727 728 729 730 731 732 733 734 735
	private getAncestors(element: SettingsTreeElement): SettingsTreeElement[] {
		const ancestors: any[] = [];

		while (element.parent) {
			if (element.parent.id !== 'root') {
				ancestors.push(element.parent);
			}

			element = element.parent;
		}
736

737
		return ancestors.reverse();
738 739
	}

J
Johannes Rieken 已提交
740
	private updateChangedSetting(key: string, value: any): Promise<void> {
741 742
		// 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 已提交
743 744
		const settingsTarget = this.settingsTargetsWidget.settingsTarget;
		const resource = URI.isUri(settingsTarget) ? settingsTarget : undefined;
745
		const configurationTarget = <ConfigurationTarget>(resource ? ConfigurationTarget.WORKSPACE_FOLDER : settingsTarget);
R
Rob Lourens 已提交
746 747
		const overrides: IConfigurationOverrides = { resource };

748 749
		const isManualReset = value === undefined;

R
Rob Lourens 已提交
750 751 752 753 754 755 756
		// 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)
757
			.then(() => {
758
				this.renderTree(key, isManualReset);
759 760 761 762 763
				const reportModifiedProps = {
					key,
					query: this.searchWidget.getValue(),
					searchResults: this.searchResultModel && this.searchResultModel.getUniqueResults(),
					rawResults: this.searchResultModel && this.searchResultModel.getRawResults(),
764
					showConfiguredOnly: !!this.viewState.tagFilters && this.viewState.tagFilters.has(MODIFIED_SETTING_TAG),
765 766 767 768 769 770
					isReset: typeof value === 'undefined',
					settingsTarget: this.settingsTargetsWidget.settingsTarget as SettingsTarget
				};

				return this.reportModifiedSetting(reportModifiedProps);
			});
771 772
	}

R
Rob Lourens 已提交
773
	private reportModifiedSetting(props: { key: string, query: string, searchResults: ISearchResult[] | null, rawResults: ISearchResult[] | null, showConfiguredOnly: boolean, isReset: boolean, settingsTarget: SettingsTarget }): void {
774
		this.pendingSettingUpdate = null;
775

R
Rob Lourens 已提交
776 777 778
		let groupId: string | undefined = undefined;
		let nlpIndex: number | undefined = undefined;
		let displayIndex: number | undefined = undefined;
779
		if (props.searchResults) {
R
Rob Lourens 已提交
780 781 782 783
			const remoteResult = props.searchResults[SearchResultIdx.Remote];
			const localResult = props.searchResults[SearchResultIdx.Local];

			const localIndex = arrays.firstIndex(localResult!.filterMatches, m => m.setting.key === props.key);
784 785 786 787 788 789 790 791
			groupId = localIndex >= 0 ?
				'local' :
				'remote';

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

792 793 794 795 796 797
			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;
				}
798 799 800
			}
		}

R
Rob Lourens 已提交
801 802 803 804
		const reportedTarget = props.settingsTarget === ConfigurationTarget.USER_LOCAL ? 'user' :
			props.settingsTarget === ConfigurationTarget.USER_REMOTE ? 'user_remote' :
				props.settingsTarget === ConfigurationTarget.WORKSPACE ? 'workspace' :
					'folder';
805 806 807 808 809 810 811 812 813 814 815 816 817

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

		/* __GDPR__
818
			"settingsEditor.settingModified" : {
819 820 821 822 823 824 825 826 827 828
				"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" }
			}
		*/
829
		this.telemetryService.publicLog('settingsEditor.settingModified', data);
R
Rob Lourens 已提交
830 831
	}

J
Johannes Rieken 已提交
832
	private render(token: CancellationToken): Promise<any> {
R
Rob Lourens 已提交
833 834
		if (this.input) {
			return this.input.resolve()
835
				.then((model: Settings2EditorModel) => {
836
					if (token.isCancellationRequested) {
R
Rob Lourens 已提交
837
						return undefined;
838 839
					}

840 841
					this._register(model.onDidChangeGroups(() => this.onConfigUpdate()));
					this.defaultSettingsEditorModel = model;
842
					return this.onConfigUpdate();
843
				});
R
Rob Lourens 已提交
844
		}
R
Rob Lourens 已提交
845
		return Promise.resolve(null);
R
Rob Lourens 已提交
846 847
	}

848
	private onSearchModeToggled(): void {
849
		DOM.removeClass(this.rootElement, 'no-toc-search');
850
		if (this.configurationService.getValue('workbench.settings.settingsSearchTocBehavior') === 'hide') {
851
			DOM.toggleClass(this.rootElement, 'no-toc-search', !!this.searchResultModel);
852
		}
853 854
	}

855 856
	private scheduleRefresh(element: HTMLElement, key = ''): void {
		if (key && this.scheduledRefreshes.has(key)) {
857 858 859
			return;
		}

860 861 862 863 864 865 866 867 868 869 870
		if (!key) {
			this.scheduledRefreshes.forEach(r => r.dispose());
			this.scheduledRefreshes.clear();
		}

		const scheduledRefreshTracker = DOM.trackFocus(element);
		this.scheduledRefreshes.set(key, scheduledRefreshTracker);
		scheduledRefreshTracker.onDidBlur(() => {
			scheduledRefreshTracker.dispose();
			this.scheduledRefreshes.delete(key);
			this.onConfigUpdate([key]);
871 872 873
		});
	}

U
Ubuntu 已提交
874
	private onConfigUpdate(keys?: string[], forceRefresh = false): void {
875
		if (keys && this.settingsTreeModel) {
876 877 878
			return this.updateElementsByKey(keys);
		}

879
		const groups = this.defaultSettingsEditorModel.settingsGroups.slice(1); // Without commonlyUsed
880
		const dividedGroups = collections.groupBy(groups, g => g.contributedByExtension ? 'extension' : 'core');
881 882 883 884 885
		const settingsResult = resolveSettingsTree(tocData, dividedGroups.core);
		const resolvedSettingsRoot = settingsResult.tree;

		// Warn for settings not included in layout
		if (settingsResult.leftoverSettings.size && !this.hasWarnedMissingSettings) {
M
Matt Bierner 已提交
886
			const settingKeyList: string[] = [];
887 888 889 890 891 892 893 894
			settingsResult.leftoverSettings.forEach(s => {
				settingKeyList.push(s.key);
			});

			this.logService.warn(`SettingsEditor2: Settings not included in settingsLayout.ts: ${settingKeyList.join(', ')}`);
			this.hasWarnedMissingSettings = true;
		}

895
		const commonlyUsed = resolveSettingsTree(commonlyUsedData, dividedGroups.core);
R
Rob Lourens 已提交
896
		resolvedSettingsRoot.children!.unshift(commonlyUsed.tree);
897

R
Rob Lourens 已提交
898
		resolvedSettingsRoot.children!.push(resolveExtensionsSettings(dividedGroups.extension || []));
899

900 901 902 903
		if (this.searchResultModel) {
			this.searchResultModel.updateChildren();
		}

904 905
		if (this.settingsTreeModel) {
			this.settingsTreeModel.update(resolvedSettingsRoot);
906

907
			// Make sure that all extensions' settings are included in search results
R
Rob Lourens 已提交
908
			const cachedState = this.group && this.input && this.editorMemento.loadEditorState(this.group, this.input);
909 910 911
			if (cachedState && cachedState.searchQuery) {
				this.triggerSearch(cachedState.searchQuery);
			} else {
912 913
				this.renderTree(undefined, forceRefresh);
				this.refreshTOCTree();
914
			}
915
		} else {
916 917
			this.settingsTreeModel = this.instantiationService.createInstance(SettingsTreeModel, this.viewState);
			this.settingsTreeModel.update(resolvedSettingsRoot);
918
			this.tocTreeModel.settingsTreeRoot = this.settingsTreeModel.root as SettingsTreeGroupElement;
919

R
Rob Lourens 已提交
920
			this.refreshTOCTree();
921 922
			this.refreshTree();

R
Rob Lourens 已提交
923
			this.tocTree.collapseAll();
924 925 926
		}
	}

U
Ubuntu 已提交
927
	private updateElementsByKey(keys: string[]): void {
928 929
		if (keys.length) {
			if (this.searchResultModel) {
R
Rob Lourens 已提交
930
				keys.forEach(key => this.searchResultModel!.updateElementsByName(key));
931 932 933 934 935 936
			}

			if (this.settingsTreeModel) {
				keys.forEach(key => this.settingsTreeModel.updateElementsByName(key));
			}

U
Ubuntu 已提交
937
			keys.forEach(key => this.renderTree(key));
938 939 940 941 942
		} else {
			return this.renderTree();
		}
	}

943 944 945 946 947 948
	private getActiveElementInSettingsTree(): HTMLElement | null {
		return (document.activeElement && DOM.isAncestor(document.activeElement, this.settingsTree.getHTMLElement())) ?
			<HTMLElement>document.activeElement :
			null;
	}

U
Ubuntu 已提交
949
	private renderTree(key?: string, force = false): void {
950
		if (!force && key && this.scheduledRefreshes.has(key)) {
951
			this.updateModifiedLabelForKey(key);
U
Ubuntu 已提交
952
			return;
953 954
		}

955 956
		// If the context view is focused, delay rendering settings
		if (this.contextViewFocused()) {
M
Matt Bierner 已提交
957 958 959 960
			const element = document.querySelector('.context-view');
			if (element) {
				this.scheduleRefresh(element as HTMLElement, key);
			}
U
Ubuntu 已提交
961
			return;
962 963
		}

964
		// If a setting control is currently focused, schedule a refresh for later
R
Rob Lourens 已提交
965 966
		const activeElement = this.getActiveElementInSettingsTree();
		const focusedSetting = activeElement && this.settingRenderers.getSettingDOMElementForDOMElement(activeElement);
967
		if (focusedSetting && !force) {
968 969
			// If a single setting is being refreshed, it's ok to refresh now if that is not the focused setting
			if (key) {
R
Rob Lourens 已提交
970
				const focusedKey = focusedSetting.getAttribute(AbstractSettingRenderer.SETTING_KEY_ATTR);
971
				if (focusedKey === key &&
P
Pine Wu 已提交
972
					!DOM.hasClass(focusedSetting, 'setting-item-list')) { // update `list`s live, as they have a separate "submit edit" step built in before this
973

974
					this.updateModifiedLabelForKey(key);
975
					this.scheduleRefresh(focusedSetting, key);
U
Ubuntu 已提交
976
					return;
977 978
				}
			} else {
979
				this.scheduleRefresh(focusedSetting);
U
Ubuntu 已提交
980
				return;
981
			}
982
		}
R
Rob Lourens 已提交
983

R
Rob Lourens 已提交
984 985
		this.renderResultCountMessages();

986
		if (key) {
987
			const elements = this.currentSettingsModel.getElementsByName(key);
988
			if (elements && elements.length) {
989
				// TODO https://github.com/Microsoft/vscode/issues/57360
R
Rob Lourens 已提交
990
				this.refreshTree();
991 992
			} else {
				// Refresh requested for a key that we don't know about
U
Ubuntu 已提交
993
				return;
994
			}
995
		} else {
R
Rob Lourens 已提交
996
			this.refreshTree();
997 998
		}

U
Ubuntu 已提交
999
		return;
R
Rob Lourens 已提交
1000 1001
	}

1002 1003 1004 1005
	private contextViewFocused(): boolean {
		return !!DOM.findParentWithClass(<HTMLElement>document.activeElement, 'context-view');
	}

R
Rob Lourens 已提交
1006
	private refreshTree(): void {
1007 1008 1009
		if (this.isVisible()) {
			this.settingsTree.setChildren(null, createGroupIterator(this.currentSettingsModel.root));
		}
1010 1011
	}

R
Rob Lourens 已提交
1012
	private refreshTOCTree(): void {
1013
		if (this.isVisible()) {
R
Rob Lourens 已提交
1014
			this.tocTreeModel.update();
1015 1016
			this.tocTree.setChildren(null, createTOCIterator(this.tocTreeModel, this.tocTree));
		}
R
Rob Lourens 已提交
1017 1018
	}

1019
	private updateModifiedLabelForKey(key: string): void {
1020
		const dataElements = this.currentSettingsModel.getElementsByName(key);
1021
		const isModified = dataElements && dataElements[0] && dataElements[0].isConfigured; // all elements are either configured or not
R
Rob Lourens 已提交
1022
		const elements = this.settingRenderers.getDOMElementsForSettingKey(this.settingsTree.getHTMLElement(), key);
1023
		if (elements && elements[0]) {
R
Rob Lourens 已提交
1024
			DOM.toggleClass(elements[0], 'is-configured', !!isModified);
1025 1026 1027
		}
	}

1028
	private onSearchInputChanged(): void {
R
Rob Lourens 已提交
1029 1030
		const query = this.searchWidget.getValue().trim();
		this.delayedFilterLogging.cancel();
1031
		this.triggerSearch(query.replace(/›/g, ' ')).then(() => {
1032
			if (query && this.searchResultModel) {
R
Rob Lourens 已提交
1033
				this.delayedFilterLogging.trigger(() => this.reportFilteringUsed(query, this.searchResultModel!.getUniqueResults()));
1034 1035
			}
		});
R
Rob Lourens 已提交
1036 1037
	}

R
Rob Lourens 已提交
1038
	private parseSettingFromJSON(query: string): string | null {
1039 1040 1041 1042
		const match = query.match(/"([a-zA-Z.]+)": /);
		return match && match[1];
	}

J
Johannes Rieken 已提交
1043
	private triggerSearch(query: string): Promise<void> {
1044
		this.viewState.tagFilters = new Set<string>();
P
Peng Lyu 已提交
1045
		this.viewState.extensionFilters = new Set<string>();
1046
		if (query) {
1047
			const parsedQuery = parseQuery(query);
R
Rob Lourens 已提交
1048
			query = parsedQuery.query;
R
Rob Lourens 已提交
1049
			parsedQuery.tags.forEach(tag => this.viewState.tagFilters!.add(tag));
P
Peng Lyu 已提交
1050
			parsedQuery.extensionFilters.forEach(extensionId => this.viewState.extensionFilters!.add(extensionId));
1051
		}
1052 1053

		if (query && query !== '@') {
1054
			query = this.parseSettingFromJSON(query) || query;
1055
			return this.triggerFilterPreferences(query);
R
Rob Lourens 已提交
1056
		} else {
P
Peng Lyu 已提交
1057
			if ((this.viewState.tagFilters && this.viewState.tagFilters.size) || (this.viewState.extensionFilters && this.viewState.extensionFilters.size)) {
1058 1059 1060 1061 1062
				this.searchResultModel = this.createFilterModel();
			} else {
				this.searchResultModel = null;
			}

R
Rob Lourens 已提交
1063 1064
			this.localSearchDelayer.cancel();
			this.remoteSearchThrottle.cancel();
1065 1066 1067 1068
			if (this.searchInProgress) {
				this.searchInProgress.cancel();
				this.searchInProgress.dispose();
				this.searchInProgress = null;
R
Rob Lourens 已提交
1069
			}
R
Rob Lourens 已提交
1070

1071
			this.tocTree.setFocus([]);
R
Rob Lourens 已提交
1072
			this.viewState.filterToCategory = undefined;
1073
			this.tocTreeModel.currentSearchModel = this.searchResultModel;
1074
			this.onSearchModeToggled();
1075 1076

			if (this.searchResultModel) {
1077 1078
				// Added a filter model
				this.tocTree.setSelection([]);
R
Rob Lourens 已提交
1079
				this.tocTree.expandAll();
R
Rob Lourens 已提交
1080
				this.renderResultCountMessages();
R
Rob Lourens 已提交
1081
				this.refreshTree();
1082
			} else {
1083
				// Leaving search mode
R
Rob Lourens 已提交
1084
				this.tocTree.collapseAll();
R
Rob Lourens 已提交
1085
				this.renderResultCountMessages();
R
Rob Lourens 已提交
1086
				this.refreshTree();
1087
			}
1088 1089

			this.refreshTOCTree();
R
Rob Lourens 已提交
1090
		}
R
Rob Lourens 已提交
1091

R
Rob Lourens 已提交
1092
		return Promise.resolve();
R
Rob Lourens 已提交
1093 1094
	}

1095 1096 1097 1098 1099 1100 1101 1102 1103
	/**
	 * Return a fake SearchResultModel which can hold a flat list of all settings, to be filtered (@modified etc)
	 */
	private createFilterModel(): SearchResultModel {
		const filterModel = this.instantiationService.createInstance(SearchResultModel, this.viewState);

		const fullResult: ISearchResult = {
			filterMatches: []
		};
R
Rob Lourens 已提交
1104 1105 1106
		for (const g of this.defaultSettingsEditorModel.settingsGroups.slice(1)) {
			for (const sect of g.sections) {
				for (const setting of sect.settings) {
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
					fullResult.filterMatches.push({ setting, matches: [], score: 0 });
				}
			}
		}

		filterModel.setResult(0, fullResult);

		return filterModel;
	}

1117 1118 1119 1120
	private reportFilteringUsed(query: string, results: ISearchResult[]): void {
		const nlpResult = results[SearchResultIdx.Remote];
		const nlpMetadata = nlpResult && nlpResult.metadata;

1121 1122 1123
		const durations = {
			nlpResult: nlpMetadata && nlpMetadata.duration
		};
1124 1125

		// Count unique results
1126
		const counts: { nlpResult?: number, filterResult?: number } = {};
1127
		const filterResult = results[SearchResultIdx.Local];
1128 1129 1130 1131
		if (filterResult) {
			counts['filterResult'] = filterResult.filterMatches.length;
		}

1132 1133
		if (nlpResult) {
			counts['nlpResult'] = nlpResult.filterMatches.length;
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
		}

		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 }
			}
		*/
1154
		this.telemetryService.publicLog('settingsEditor.filter', data);
1155 1156
	}

J
Johannes Rieken 已提交
1157
	private triggerFilterPreferences(query: string): Promise<void> {
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
		if (this.searchInProgress) {
			this.searchInProgress.cancel();
			this.searchInProgress = null;
		}

		// Trigger the local search. If it didn't find an exact match, trigger the remote search.
		const searchInProgress = this.searchInProgress = new CancellationTokenSource();
		return this.localSearchDelayer.trigger(() => {
			if (searchInProgress && !searchInProgress.token.isCancellationRequested) {
				return this.localFilterPreferences(query).then(result => {
1168
					if (result && !result.exactMatch) {
1169 1170
						this.remoteSearchThrottle.trigger(() => {
							return searchInProgress && !searchInProgress.token.isCancellationRequested ?
R
Rob Lourens 已提交
1171 1172
								this.remoteSearchPreferences(query, this.searchInProgress!.token) :
								Promise.resolve();
1173 1174
						});
					}
1175
				});
1176
			} else {
R
Rob Lourens 已提交
1177
				return Promise.resolve();
1178 1179 1180 1181
			}
		});
	}

R
Rob Lourens 已提交
1182
	private localFilterPreferences(query: string, token?: CancellationToken): Promise<ISearchResult | null> {
1183
		const localSearchProvider = this.preferencesSearchService.getLocalSearchProvider(query);
1184
		return this.filterOrSearchPreferences(query, SearchResultIdx.Local, localSearchProvider, token);
R
Rob Lourens 已提交
1185 1186
	}

J
Johannes Rieken 已提交
1187
	private remoteSearchPreferences(query: string, token?: CancellationToken): Promise<void> {
1188
		const remoteSearchProvider = this.preferencesSearchService.getRemoteSearchProvider(query);
1189 1190
		const newExtSearchProvider = this.preferencesSearchService.getRemoteSearchProvider(query, true);

R
Rob Lourens 已提交
1191
		return Promise.all([
1192 1193
			this.filterOrSearchPreferences(query, SearchResultIdx.Remote, remoteSearchProvider, token),
			this.filterOrSearchPreferences(query, SearchResultIdx.NewExtensions, newExtSearchProvider, token)
R
Rob Lourens 已提交
1194
		]).then(() => { });
R
Rob Lourens 已提交
1195 1196
	}

R
Rob Lourens 已提交
1197
	private filterOrSearchPreferences(query: string, type: SearchResultIdx, searchProvider?: ISearchProvider, token?: CancellationToken): Promise<ISearchResult | null> {
1198 1199 1200 1201 1202
		return this._filterOrSearchPreferencesModel(query, this.defaultSettingsEditorModel, searchProvider, token).then(result => {
			if (token && token.isCancellationRequested) {
				// Handle cancellation like this because cancellation is lost inside the search provider due to async/await
				return null;
			}
1203

1204 1205 1206 1207
			if (!this.searchResultModel) {
				this.searchResultModel = this.instantiationService.createInstance(SearchResultModel, this.viewState);
				this.searchResultModel.setResult(type, result);
				this.tocTreeModel.currentSearchModel = this.searchResultModel;
1208
				this.onSearchModeToggled();
1209 1210
			} else {
				this.searchResultModel.setResult(type, result);
1211
				this.tocTreeModel.update();
1212
			}
R
Rob Lourens 已提交
1213

1214
			this.tocTree.setFocus([]);
R
Rob Lourens 已提交
1215
			this.viewState.filterToCategory = undefined;
R
Rob Lourens 已提交
1216
			this.tocTree.expandAll();
1217

U
Ubuntu 已提交
1218
			this.renderTree(undefined, true);
1219
			this.refreshTOCTree();
U
Ubuntu 已提交
1220
			return result;
R
Rob Lourens 已提交
1221 1222 1223
		});
	}

1224
	private renderResultCountMessages() {
1225
		if (!this.currentSettingsModel) {
1226 1227 1228
			return;
		}

R
Rob Lourens 已提交
1229 1230 1231 1232
		this.clearFilterLinkContainer.style.display = this.viewState.tagFilters && this.viewState.tagFilters.size > 0
			? 'initial'
			: 'none';

1233 1234
		if (!this.searchResultModel) {
			this.countElement.style.display = 'none';
R
Rob Lourens 已提交
1235 1236
			DOM.removeClass(this.rootElement, 'no-results');
			return;
1237 1238
		}

1239 1240 1241 1242 1243 1244 1245
		if (this.tocTreeModel && this.tocTreeModel.settingsTreeRoot) {
			const count = this.tocTreeModel.settingsTreeRoot.count;
			switch (count) {
				case 0: this.countElement.innerText = localize('noResults', "No Settings Found"); break;
				case 1: this.countElement.innerText = localize('oneResult', "1 Setting Found"); break;
				default: this.countElement.innerText = localize('moreThanOneResult', "{0} Settings Found", count);
			}
1246

1247
			this.countElement.style.display = 'block';
R
Rob Lourens 已提交
1248
			DOM.toggleClass(this.rootElement, 'no-results', count === 0);
1249
		}
1250 1251
	}

R
Rob Lourens 已提交
1252
	private _filterOrSearchPreferencesModel(filter: string, model: ISettingsEditorModel, provider?: ISearchProvider, token?: CancellationToken): Promise<ISearchResult | null> {
R
Rob Lourens 已提交
1253
		const searchP = provider ? provider.searchModel(model, token) : Promise.resolve(null);
R
Rob Lourens 已提交
1254 1255 1256
		return searchP
			.then<ISearchResult>(null, err => {
				if (isPromiseCanceledError(err)) {
R
Rob Lourens 已提交
1257
					return Promise.reject(err);
R
Rob Lourens 已提交
1258 1259
				} else {
					/* __GDPR__
1260
						"settingsEditor.searchError" : {
R
Rob Lourens 已提交
1261 1262 1263 1264 1265 1266 1267
							"message": { "classification": "CallstackOrException", "purpose": "FeatureInsight" },
							"filter": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
						}
					*/
					const message = getErrorMessage(err).trim();
					if (message && message !== 'Error') {
						// "Error" = any generic network error
1268
						this.telemetryService.publicLog('settingsEditor.searchError', { message, filter });
R
Rob Lourens 已提交
1269 1270
						this.logService.info('Setting search error: ' + message);
					}
R
Rob Lourens 已提交
1271
					return Promise.resolve(null);
R
Rob Lourens 已提交
1272 1273 1274 1275
				}
			});
	}

1276
	private layoutTrees(dimension: DOM.Dimension): void {
1277
		const listHeight = dimension.height - (76 + 11 /* header height + padding*/);
1278 1279
		const settingsTreeHeight = listHeight - 14;
		this.settingsTreeContainer.style.height = `${settingsTreeHeight}px`;
1280
		this.settingsTree.layout(settingsTreeHeight, dimension.width);
1281

1282 1283
		const tocTreeHeight = listHeight - 16;
		this.tocTreeContainer.style.height = `${tocTreeHeight}px`;
R
Rob Lourens 已提交
1284
		this.tocTree.layout(tocTreeHeight);
1285
	}
1286

B
Benjamin Pasero 已提交
1287
	protected saveState(): void {
1288 1289 1290
		if (this.isVisible()) {
			const searchQuery = this.searchWidget.getValue().trim();
			const target = this.settingsTargetsWidget.settingsTarget as SettingsTarget;
R
Rob Lourens 已提交
1291 1292 1293
			if (this.group && this.input) {
				this.editorMemento.saveEditorState(this.group, this.input, { searchQuery, target });
			}
1294
		}
B
Benjamin Pasero 已提交
1295 1296

		super.saveState();
1297
	}
R
Rob Lourens 已提交
1298
}
1299

1300 1301 1302 1303
interface ISettingsEditor2State {
	searchQuery: string;
	target: SettingsTarget;
}