settingsEditor2.ts 50.7 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, withUndefinedAsNull } 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, SETTINGS_EDITOR_COMMAND_CLEAR_SEARCH_RESULTS } 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';
44 45
import { Action } from 'vs/base/common/actions';
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
R
Rob Lourens 已提交
46

R
Rob Lourens 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59
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
		};
	});
}

60 61
const $ = DOM.$;

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

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

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

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

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

91 92
	// (!) Lots of props that are set once on the first render
	private defaultSettingsEditorModel!: Settings2EditorModel;
R
Rob Lourens 已提交
93

94 95 96 97 98
	private rootElement!: HTMLElement;
	private headerContainer!: HTMLElement;
	private searchWidget!: SuggestEnabledInput;
	private countElement!: HTMLElement;
	private settingsTargetsWidget!: SettingsTargetsWidget;
R
Rob Lourens 已提交
99

100 101 102 103 104 105 106
	private settingsTreeContainer!: HTMLElement;
	private settingsTree!: SettingsTree;
	private settingRenderers!: SettingTreeRenderers;
	private tocTreeModel!: TOCTreeModel;
	private settingsTreeModel!: SettingsTreeModel;
	private noResultsMessage!: HTMLElement;
	private clearFilterLinkContainer!: HTMLElement;
R
Rob Lourens 已提交
107

108 109
	private tocTreeContainer!: HTMLElement;
	private tocTree!: TOCTree;
R
Rob Lourens 已提交
110

111
	private settingsAriaExtraLabelsContainer!: HTMLElement;
112

R
Rob Lourens 已提交
113 114 115
	private delayedFilterLogging: Delayer<void>;
	private localSearchDelayer: Delayer<void>;
	private remoteSearchThrottle: ThrottledDelayer<void>;
116
	private searchInProgress: CancellationTokenSource | null = null;
117

118 119
	private updatedConfigSchemaDelayer: Delayer<void>;

120 121
	private settingFastUpdateDelayer: Delayer<void>;
	private settingSlowUpdateDelayer: Delayer<void>;
122
	private pendingSettingUpdate: { key: string, value: any } | null = null;
R
Rob Lourens 已提交
123

124
	private readonly viewState: ISettingsEditorViewState;
125
	private _searchResultModel: SearchResultModel | null = null;
126

127
	private tocRowFocused: IContextKey<boolean>;
128 129
	private inSettingsEditorContextKey: IContextKey<boolean>;
	private searchFocusContextKey: IContextKey<boolean>;
130

131
	private scheduledRefreshes: Map<string, DOM.IFocusTracker>;
132
	private lastFocusedSettingElement: string | null = null;
133

134 135 136
	private actionBar: ActionBar;
	private actionsContainer: HTMLElement;

137
	/** Don't spam warnings */
138
	private hasWarnedMissingSettings = false;
139

140 141
	private editorMemento: IEditorMemento<ISettingsEditor2State>;

142
	private tocFocusedElement: SettingsTreeGroupElement | null = null;
143
	private settingsTreeScrollTop = 0;
144
	private dimension!: DOM.Dimension;
145

R
Rob Lourens 已提交
146 147
	constructor(
		@ITelemetryService telemetryService: ITelemetryService,
148
		@IConfigurationService private readonly configurationService: IConfigurationService,
R
Rob Lourens 已提交
149
		@IThemeService themeService: IThemeService,
150 151 152 153
		@IPreferencesService private readonly preferencesService: IPreferencesService,
		@IInstantiationService private readonly instantiationService: IInstantiationService,
		@IPreferencesSearchService private readonly preferencesSearchService: IPreferencesSearchService,
		@ILogService private readonly logService: ILogService,
154
		@IContextKeyService contextKeyService: IContextKeyService,
155 156
		@IStorageService private readonly storageService: IStorageService,
		@INotificationService private readonly notificationService: INotificationService,
157
		@IEditorGroupsService protected editorGroupService: IEditorGroupsService,
158
		@IKeybindingService private readonly keybindingService: IKeybindingService
R
Rob Lourens 已提交
159
	) {
160
		super(SettingsEditor2.ID, telemetryService, themeService, storageService);
R
Rob Lourens 已提交
161
		this.delayedFilterLogging = new Delayer<void>(1000);
162
		this.localSearchDelayer = new Delayer(300);
163
		this.remoteSearchThrottle = new ThrottledDelayer(200);
R
Rob Lourens 已提交
164
		this.viewState = { settingsTarget: ConfigurationTarget.USER_LOCAL };
R
Rob Lourens 已提交
165

166 167
		this.settingFastUpdateDelayer = new Delayer<void>(SettingsEditor2.SETTING_UPDATE_FAST_DEBOUNCE);
		this.settingSlowUpdateDelayer = new Delayer<void>(SettingsEditor2.SETTING_UPDATE_SLOW_DEBOUNCE);
168

169 170
		this.updatedConfigSchemaDelayer = new Delayer<void>(SettingsEditor2.CONFIG_SCHEMA_UPDATE_DELAYER);

171 172
		this.inSettingsEditorContextKey = CONTEXT_SETTINGS_EDITOR.bindTo(contextKeyService);
		this.searchFocusContextKey = CONTEXT_SETTINGS_SEARCH_FOCUS.bindTo(contextKeyService);
173
		this.tocRowFocused = CONTEXT_TOC_ROW_FOCUS.bindTo(contextKeyService);
174

175 176
		this.scheduledRefreshes = new Map<string, DOM.IFocusTracker>();

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

179
		this._register(configurationService.onDidChangeConfiguration(e => {
180 181 182
			if (e.source !== ConfigurationTarget.DEFAULT) {
				this.onConfigUpdate(e.affectedKeys);
			}
183
		}));
R
Rob Lourens 已提交
184 185
	}

186 187 188 189 190 191 192
	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 已提交
193 194 195 196
	private get currentSettingsModel() {
		return this.searchResultModel || this.settingsTreeModel;
	}

R
Rob Lourens 已提交
197
	private get searchResultModel(): SearchResultModel | null {
198 199 200
		return this._searchResultModel;
	}

R
Rob Lourens 已提交
201
	private set searchResultModel(value: SearchResultModel | null) {
202 203 204 205 206
		this._searchResultModel = value;

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

R
Rob Lourens 已提交
207 208 209
	private get currentSettingsContextMenuKeyBindingLabel(): string {
		const keybinding = this.keybindingService.lookupKeybinding(SETTINGS_EDITOR_COMMAND_SHOW_CONTEXT_MENU);
		return (keybinding && keybinding.getAriaLabel()) || '';
210 211
	}

R
Rob Lourens 已提交
212
	createEditor(parent: HTMLElement): void {
213
		parent.setAttribute('tabindex', '-1');
R
Rob Lourens 已提交
214
		this.rootElement = DOM.append(parent, $('.settings-editor', { tabindex: '-1' }));
R
Rob Lourens 已提交
215

216 217
		this.createHeader(this.rootElement);
		this.createBody(this.rootElement);
218
		this.updateStyles();
R
Rob Lourens 已提交
219 220
	}

221
	setInput(input: SettingsEditor2Input, options: SettingsEditorOptions | undefined, token: CancellationToken): Promise<void> {
222
		this.inSettingsEditorContextKey.set(true);
223
		return super.setInput(input, options, token)
224
			.then(() => timeout(0)) // Force setInput to be async
R
Rob Lourens 已提交
225
			.then(() => {
226 227 228 229 230 231 232 233
				// Don't block setInput on render (which can trigger an async search)
				this.render(token).then(() => {
					options = options || SettingsEditorOptions.create({});

					if (!this.viewState.settingsTarget) {
						if (!options.target) {
							options.target = ConfigurationTarget.USER_LOCAL;
						}
234
					}
R
Rob Lourens 已提交
235

236
					this._setOptions(options);
237

238 239 240
					this._register(input.onDispose(() => {
						this.searchWidget.setValue('');
					}));
241

242 243 244
					// Init TOC selection
					this.updateTreeScrollSync();
				});
R
Rob Lourens 已提交
245
			});
R
Rob Lourens 已提交
246 247
	}

248
	private restoreCachedState(): ISettingsEditor2State | null {
R
Rob Lourens 已提交
249
		const cachedState = this.group && this.input && this.editorMemento.loadEditorState(this.group, this.input);
250
		if (cachedState && typeof cachedState.target === 'object') {
251 252 253 254 255 256
			cachedState.target = URI.revive(cachedState.target);
		}

		if (cachedState) {
			const settingsTarget = cachedState.target;
			this.settingsTargetsWidget.settingsTarget = settingsTarget;
257
			this.viewState.settingsTarget = settingsTarget;
258 259
			this.searchWidget.setValue(cachedState.searchQuery);
		}
260 261 262 263 264 265

		if (this.input) {
			this.editorMemento.clearEditorState(this.input, this.group);
		}

		return withUndefinedAsNull(cachedState);
266 267
	}

268
	setOptions(options: SettingsEditorOptions | undefined): void {
269 270
		super.setOptions(options);

R
Rob Lourens 已提交
271 272 273
		if (options) {
			this._setOptions(options);
		}
274
	}
275

276
	private _setOptions(options: SettingsEditorOptions): void {
277 278 279 280
		if (options.query) {
			this.searchWidget.setValue(options.query);
		}

281
		const target: SettingsTarget = options.folderUri || <SettingsTarget>options.target;
R
Rob Lourens 已提交
282 283 284 285
		if (target) {
			this.settingsTargetsWidget.settingsTarget = target;
			this.viewState.settingsTarget = target;
		}
286 287
	}

288 289 290 291 292
	clearInput(): void {
		this.inSettingsEditorContextKey.set(false);
		super.clearInput();
	}

R
Rob Lourens 已提交
293
	layout(dimension: DOM.Dimension): void {
294
		this.dimension = dimension;
J
Joao Moreno 已提交
295 296 297 298 299

		if (!this.isVisible()) {
			return;
		}

300 301
		this.layoutTrees(dimension);

302 303
		const innerWidth = Math.min(1000, dimension.width) - 24 * 2; // 24px padding on left and right;
		const monacoWidth = innerWidth - 10 - this.countElement.clientWidth - 12; // minus padding inside inputbox, countElement width, extra padding before countElement
304 305
		this.searchWidget.layout({ height: 20, width: monacoWidth });

306 307
		DOM.toggleClass(this.rootElement, 'mid-width', dimension.width < 1000 && dimension.width >= 600);
		DOM.toggleClass(this.rootElement, 'narrow-width', dimension.width < 600);
R
Rob Lourens 已提交
308 309 310
	}

	focus(): void {
R
Rob Lourens 已提交
311
		if (this.lastFocusedSettingElement) {
R
Rob Lourens 已提交
312
			const elements = this.settingRenderers.getDOMElementsForSettingKey(this.settingsTree.getHTMLElement(), this.lastFocusedSettingElement);
R
Rob Lourens 已提交
313
			if (elements.length) {
R
Rob Lourens 已提交
314
				const control = elements[0].querySelector(AbstractSettingRenderer.CONTROL_SELECTOR);
R
Rob Lourens 已提交
315 316 317 318 319 320 321
				if (control) {
					(<HTMLElement>control).focus();
					return;
				}
			}
		}

322 323 324
		this.focusSearch();
	}

325
	focusSettings(): void {
326 327 328 329 330
		// Update ARIA global labels
		const labelElement = this.settingsAriaExtraLabelsContainer.querySelector('#settings_aria_more_actions_shortcut_label');
		if (labelElement) {
			const settingsContextMenuShortcut = this.currentSettingsContextMenuKeyBindingLabel;
			if (settingsContextMenuShortcut) {
331
				labelElement.setAttribute('aria-label', localize('settingsContextMenuAriaShortcut', "For more actions, Press {0}.", settingsContextMenuShortcut));
332 333 334
			}
		}

R
Rob Lourens 已提交
335
		const firstFocusable = this.settingsTree.getHTMLElement().querySelector(AbstractSettingRenderer.CONTROL_SELECTOR);
336 337
		if (firstFocusable) {
			(<HTMLElement>firstFocusable).focus();
338 339 340
		}
	}

341
	showContextMenu(): void {
R
Rob Lourens 已提交
342 343 344 345 346 347
		const activeElement = this.getActiveElementInSettingsTree();
		if (!activeElement) {
			return;
		}

		const settingDOMElement = this.settingRenderers.getSettingDOMElementForDOMElement(activeElement);
348 349 350 351
		if (!settingDOMElement) {
			return;
		}

R
Rob Lourens 已提交
352
		const focusedKey = this.settingRenderers.getKeyForDOMElementInSetting(settingDOMElement);
353 354 355 356 357 358
		if (!focusedKey) {
			return;
		}

		const elements = this.currentSettingsModel.getElementsByName(focusedKey);
		if (elements && elements[0]) {
R
Rob Lourens 已提交
359
			this.settingRenderers.showContextMenu(elements[0], settingDOMElement);
360 361 362
		}
	}

363
	focusSearch(filter?: string, selectAll = true): void {
364 365 366 367
		if (filter && this.searchWidget) {
			this.searchWidget.setValue(filter);
		}

368
		this.searchWidget.focus(selectAll);
R
Rob Lourens 已提交
369 370
	}

371
	clearSearchResults(): void {
372
		this.searchWidget.setValue('');
373 374
	}

375 376 377 378 379 380 381 382 383 384
	clearSearchFilters(): void {
		let query = this.searchWidget.getValue();

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

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

385 386 387 388 389
	clearSearch(): void {
		this.clearSearchResults();
		this.focusSearch();
	}

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

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

395 396
		const clearInputAction = new Action(SETTINGS_EDITOR_COMMAND_CLEAR_SEARCH_RESULTS, localize('clearInput', "Clear Settings Search Input"), 'codicon-clear-all', false, () => { this.clearSearch(); return Promise.resolve(null); });

R
Rob Lourens 已提交
397
		const searchBoxLabel = localize('SearchSettings.AriaLabel', "Search settings");
398 399 400
		this.searchWidget = this._register(this.instantiationService.createInstance(SuggestEnabledInput, `${SettingsEditor2.ID}.searchbox`, searchContainer, {
			triggerCharacters: ['@'],
			provideResults: (query: string) => {
P
Peng Lyu 已提交
401
				return SettingsEditor2.SUGGESTIONS.filter(tag => query.indexOf(tag) === -1).map(tag => strings.endsWith(tag, ':') ? tag : tag + ' ');
402
			}
403
		}, searchBoxLabel, 'settingseditor:searchinput' + SettingsEditor2.NUM_INSTANCES++, {
M
Matt Bierner 已提交
404 405 406 407
			placeholderText: searchBoxLabel,
			focusContextKey: this.searchFocusContextKey,
			// TODO: Aria-live
		})
J
Jeremy Shore 已提交
408
		);
409

410 411 412 413
		this._register(this.searchWidget.onFocus(() => {
			this.lastFocusedSettingElement = '';
		}));

414 415 416 417
		this._register(attachSuggestEnabledInputBoxStyler(this.searchWidget, this.themeService, {
			inputBorder: settingsTextInputBorder
		}));

418 419
		this.countElement = DOM.append(searchContainer, DOM.$('.settings-count-widget'));
		this._register(attachStylerCallback(this.themeService, { badgeBackground, contrastBorder, badgeForeground }, colors => {
420 421 422
			const background = colors.badgeBackground ? colors.badgeBackground.toString() : '';
			const border = colors.contrastBorder ? colors.contrastBorder.toString() : '';
			const foreground = colors.badgeForeground ? colors.badgeForeground.toString() : '';
423 424

			this.countElement.style.backgroundColor = background;
R
Rob Lourens 已提交
425
			this.countElement.style.color = foreground;
426

427 428
			this.countElement.style.borderWidth = border ? '1px' : '';
			this.countElement.style.borderStyle = border ? 'solid' : '';
429 430 431
			this.countElement.style.borderColor = border;
		}));

432 433 434 435 436
		this._register(this.searchWidget.onInputDidChange(() => {
			const searchVal = this.searchWidget.getValue();
			clearInputAction.enabled = !!searchVal;
			this.onSearchInputChanged();
		}));
R
Rob Lourens 已提交
437

438
		const headerControlsContainer = DOM.append(this.headerContainer, $('.settings-header-controls'));
R
Rob Lourens 已提交
439
		const targetWidgetContainer = DOM.append(headerControlsContainer, $('.settings-target-container'));
R
Rob Lourens 已提交
440 441
		this.settingsTargetsWidget = this._register(this.instantiationService.createInstance(SettingsTargetsWidget, targetWidgetContainer, { enableRemoteSettings: true }));
		this.settingsTargetsWidget.settingsTarget = ConfigurationTarget.USER_LOCAL;
442
		this.settingsTargetsWidget.onDidTargetChange(target => this.onDidSettingsTargetChange(target));
443 444 445 446 447 448 449 450 451

		this.actionsContainer = DOM.append(searchContainer, DOM.$('.settings-clear-widget'));

		this.actionBar = this._register(new ActionBar(this.actionsContainer, {
			animated: false,
			actionViewItemProvider: (action: Action) => { return undefined; }
		}));

		this.actionBar.push([clearInputAction], { label: false, icon: true });
R
Rob Lourens 已提交
452 453
	}

454 455 456
	private onDidSettingsTargetChange(target: SettingsTarget): void {
		this.viewState.settingsTarget = target;

457 458
		// TODO Instead of rebuilding the whole model, refresh and uncache the inspected setting value
		this.onConfigUpdate(undefined, true);
459 460
	}

461
	private onDidClickSetting(evt: ISettingLinkClickEvent, recursed?: boolean): void {
462
		const elements = this.currentSettingsModel.getElementsByName(evt.targetKey);
463
		if (elements && elements[0]) {
464
			let sourceTop = this.settingsTree.getRelativeTop(evt.source);
R
Rob Lourens 已提交
465 466 467 468
			if (typeof sourceTop !== 'number') {
				return;
			}

469 470
			if (sourceTop < 0) {
				// e.g. clicked a searched element, now the search has been cleared
471
				sourceTop = 0.5;
472 473
			}

474
			this.settingsTree.reveal(elements[0], sourceTop);
475

R
Rob Lourens 已提交
476
			const domElements = this.settingRenderers.getDOMElementsForSettingKey(this.settingsTree.getHTMLElement(), evt.targetKey);
477
			if (domElements && domElements[0]) {
R
Rob Lourens 已提交
478
				const control = domElements[0].querySelector(AbstractSettingRenderer.CONTROL_SELECTOR);
479 480 481 482
				if (control) {
					(<HTMLElement>control).focus();
				}
			}
483 484 485 486 487 488
		} else if (!recursed) {
			const p = this.triggerSearch('');
			p.then(() => {
				this.searchWidget.setValue('');
				this.onDidClickSetting(evt, true);
			});
489 490 491
		}
	}

492
	switchToSettingsFile(): Promise<IEditor | undefined> {
493 494 495 496
		const query = parseQuery(this.searchWidget.getValue());
		return this.openSettingsFile(query.query);
	}

497
	private async openSettingsFile(query?: string): Promise<IEditor | undefined> {
498 499
		const currentSettingsTarget = this.settingsTargetsWidget.settingsTarget;

500
		const options: ISettingsEditorOptions = { query };
R
Rob Lourens 已提交
501
		if (currentSettingsTarget === ConfigurationTarget.USER_LOCAL) {
502
			return this.preferencesService.openGlobalSettings(true, options);
R
Rob Lourens 已提交
503 504
		} else if (currentSettingsTarget === ConfigurationTarget.USER_REMOTE) {
			return this.preferencesService.openRemoteSettings();
505
		} else if (currentSettingsTarget === ConfigurationTarget.WORKSPACE) {
506
			return this.preferencesService.openWorkspaceSettings(true, options);
507
		} else if (URI.isUri(currentSettingsTarget)) {
508
			return this.preferencesService.openFolderSettings(currentSettingsTarget, true, options);
509
		}
510 511

		return undefined;
R
Rob Lourens 已提交
512 513 514 515 516
	}

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

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

519
		this.noResultsMessage.innerText = localize('noResults', "No Settings Found");
520 521 522 523 524

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

		this.clearFilterLinkContainer.textContent = ' - ';
		const clearFilterLink = DOM.append(this.clearFilterLinkContainer, $('a.pointer.prominent', { tabindex: 0 }, localize('clearSearchFilters', 'Clear Filters')));
525
		this._register(DOM.addDisposableListener(clearFilterLink, DOM.EventType.CLICK, (e: MouseEvent) => {
526 527 528 529 530 531 532 533 534 535
			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')));
536
		this._register(DOM.addDisposableListener(clearSearch, DOM.EventType.CLICK, (e: MouseEvent) => {
537 538
			DOM.EventHelper.stop(e, false);
			this.clearSearchResults();
539
			this.focusSearch();
540 541 542 543
		}));

		DOM.append(this.noResultsMessage, clearSearchContainer);

544 545 546 547
		this._register(attachStylerCallback(this.themeService, { editorForeground }, colors => {
			this.noResultsMessage.style.color = colors.editorForeground ? colors.editorForeground.toString() : null;
		}));

R
Rob Lourens 已提交
548 549
		this.createTOC(bodyContainer);

550 551 552 553 554
		this.createFocusSink(
			bodyContainer,
			e => {
				if (DOM.findParentWithClass(e.relatedTarget, 'settings-editor-tree')) {
					if (this.settingsTree.scrollTop > 0) {
555
						const firstElement = this.settingsTree.firstVisibleElement;
556 557 558 559 560 561 562 563 564 565 566 567 568
						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 已提交
569

R
Rob Lourens 已提交
570
		this.createSettingsTree(bodyContainer);
R
Rob Lourens 已提交
571

572 573 574 575 576
		this.createFocusSink(
			bodyContainer,
			e => {
				if (DOM.findParentWithClass(e.relatedTarget, 'settings-editor-tree')) {
					if (this.settingsTree.scrollTop < this.settingsTree.scrollHeight) {
577
						const lastElement = this.settingsTree.lastVisibleElement;
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
						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;
	}
601

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

606 607
		this.tocTree = this._register(this.instantiationService.createInstance(TOCTree,
			DOM.append(this.tocTreeContainer, $('.settings-toc-wrapper')),
R
Rob Lourens 已提交
608
			this.viewState));
R
Rob Lourens 已提交
609

610
		this._register(this.tocTree.onDidChangeFocus(e => {
R
Rob Lourens 已提交
611
			const element: SettingsTreeGroupElement | null = e.elements[0];
R
Rob Lourens 已提交
612 613 614
			if (this.tocFocusedElement === element) {
				return;
			}
615

R
Rob Lourens 已提交
616 617 618 619
			this.tocFocusedElement = element;
			this.tocTree.setSelection(element ? [element] : []);
			if (this.searchResultModel) {
				if (this.viewState.filterToCategory !== element) {
620
					this.viewState.filterToCategory = withNullAsUndefined(element);
621 622
					this.renderTree();
					this.settingsTree.scrollTop = 0;
R
Rob Lourens 已提交
623
				}
R
Rob Lourens 已提交
624
			} else if (element && (!e.browserEvent || !(<IFocusEventFromScroll>e.browserEvent).fromScroll)) {
R
Rob Lourens 已提交
625 626
				this.settingsTree.reveal(element, 0);
			}
627 628 629 630 631 632 633 634
		}));

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

		this._register(this.tocTree.onDidBlur(() => {
			this.tocRowFocused.set(false);
R
Rob Lourens 已提交
635 636 637 638
		}));
	}

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

641 642 643 644 645 646 647 648
		// 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 已提交
649 650 651
		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 => {
652
			this.openSettingsFile(settingKey);
653
		}));
R
Rob Lourens 已提交
654 655
		this._register(this.settingRenderers.onDidClickSettingLink(settingName => this.onDidClickSetting(settingName)));
		this._register(this.settingRenderers.onDidFocusSetting(element => {
R
Rob Lourens 已提交
656
			this.lastFocusedSettingElement = element.setting.key;
657 658
			this.settingsTree.reveal(element);
		}));
R
Rob Lourens 已提交
659
		this._register(this.settingRenderers.onDidClickOverrideElement((element: ISettingOverrideClickEvent) => {
660
			if (element.scope.toLowerCase() === 'workspace') {
J
Jeremy Shore 已提交
661
				this.settingsTargetsWidget.updateTarget(ConfigurationTarget.WORKSPACE);
662
			} else if (element.scope.toLowerCase() === 'user') {
R
Rob Lourens 已提交
663
				this.settingsTargetsWidget.updateTarget(ConfigurationTarget.USER_LOCAL);
664
			} else if (element.scope.toLowerCase() === 'remote') {
R
Rob Lourens 已提交
665
				this.settingsTargetsWidget.updateTarget(ConfigurationTarget.USER_REMOTE);
J
Jeremy Shore 已提交
666 667 668 669
			}

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

671
		this.settingsTree = this._register(this.instantiationService.createInstance(SettingsTree,
672 673
			this.settingsTreeContainer,
			this.viewState,
R
Rob Lourens 已提交
674
			this.settingRenderers.allRenderers));
R
Rob Lourens 已提交
675
		this.settingsTree.getHTMLElement().attributes.removeNamedItem('tabindex');
676

677
		this._register(this.settingsTree.onDidScroll(() => {
678 679 680 681 682 683 684 685 686 687 688
			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);
689
		}));
690 691
	}

B
Benjamin Pasero 已提交
692 693
	private notifyNoSaveNeeded() {
		if (!this.storageService.getBoolean('hasNotifiedOfSettingsAutosave', StorageScope.GLOBAL, false)) {
B
Benjamin Pasero 已提交
694
			this.storageService.store('hasNotifiedOfSettingsAutosave', true, StorageScope.GLOBAL);
695 696
			this.notificationService.info(localize('settingsNoSaveNeeded', "Your changes are automatically saved as you edit."));
		}
J
Jackson Kearl 已提交
697 698
	}

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

702 703
		if (this.pendingSettingUpdate && this.pendingSettingUpdate.key !== key) {
			this.updateChangedSetting(key, value);
704 705
		}

706
		this.pendingSettingUpdate = { key, value };
707 708 709 710 711
		if (SettingsEditor2.shouldSettingUpdateFast(type)) {
			this.settingFastUpdateDelayer.trigger(() => this.updateChangedSetting(key, value));
		} else {
			this.settingSlowUpdateDelayer.trigger(() => this.updateChangedSetting(key, value));
		}
712 713
	}

714
	private updateTreeScrollSync(): void {
R
Rob Lourens 已提交
715
		this.settingRenderers.cancelSuggesters();
716 717 718 719
		if (this.searchResultModel) {
			return;
		}

R
Rob Lourens 已提交
720
		if (!this.tocTreeModel) {
721 722
			return;
		}
723

724
		const elementToSync = this.settingsTree.firstVisibleElement;
725 726 727 728
		const element = elementToSync instanceof SettingsTreeSettingElement ? elementToSync.parent :
			elementToSync instanceof SettingsTreeGroupElement ? elementToSync :
				null;

R
Rob Lourens 已提交
729 730 731 732 733 734 735 736
		// 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;
		}

737 738 739 740 741 742
		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 已提交
743 744 745 746
			if (typeof elementTop !== 'number') {
				return;
			}

747 748 749 750 751 752 753 754 755 756
			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 已提交
757

758
			this.tocTree.setSelection([element]);
759

760
			const fakeKeyboardEvent = new KeyboardEvent('keydown');
R
Rob Lourens 已提交
761
			(<IFocusEventFromScroll>fakeKeyboardEvent).fromScroll = true;
762 763 764
			this.tocTree.setFocus([element], fakeKeyboardEvent);
		}
	}
765

766 767 768 769 770 771 772 773 774 775
	private getAncestors(element: SettingsTreeElement): SettingsTreeElement[] {
		const ancestors: any[] = [];

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

			element = element.parent;
		}
776

777
		return ancestors.reverse();
778 779
	}

J
Johannes Rieken 已提交
780
	private updateChangedSetting(key: string, value: any): Promise<void> {
781 782
		// 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 已提交
783 784
		const settingsTarget = this.settingsTargetsWidget.settingsTarget;
		const resource = URI.isUri(settingsTarget) ? settingsTarget : undefined;
785
		const configurationTarget = <ConfigurationTarget>(resource ? ConfigurationTarget.WORKSPACE_FOLDER : settingsTarget);
R
Rob Lourens 已提交
786 787
		const overrides: IConfigurationOverrides = { resource };

788 789
		const isManualReset = value === undefined;

R
Rob Lourens 已提交
790 791 792 793 794 795 796
		// 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)
797
			.then(() => {
798
				this.renderTree(key, isManualReset);
799 800 801 802 803
				const reportModifiedProps = {
					key,
					query: this.searchWidget.getValue(),
					searchResults: this.searchResultModel && this.searchResultModel.getUniqueResults(),
					rawResults: this.searchResultModel && this.searchResultModel.getRawResults(),
804
					showConfiguredOnly: !!this.viewState.tagFilters && this.viewState.tagFilters.has(MODIFIED_SETTING_TAG),
805 806 807 808 809 810
					isReset: typeof value === 'undefined',
					settingsTarget: this.settingsTargetsWidget.settingsTarget as SettingsTarget
				};

				return this.reportModifiedSetting(reportModifiedProps);
			});
811 812
	}

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

R
Rob Lourens 已提交
816 817 818
		let groupId: string | undefined = undefined;
		let nlpIndex: number | undefined = undefined;
		let displayIndex: number | undefined = undefined;
819
		if (props.searchResults) {
R
Rob Lourens 已提交
820 821 822 823
			const remoteResult = props.searchResults[SearchResultIdx.Remote];
			const localResult = props.searchResults[SearchResultIdx.Local];

			const localIndex = arrays.firstIndex(localResult!.filterMatches, m => m.setting.key === props.key);
824 825 826 827 828 829 830 831
			groupId = localIndex >= 0 ?
				'local' :
				'remote';

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

832 833 834 835 836 837
			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;
				}
838 839 840
			}
		}

R
Rob Lourens 已提交
841 842 843 844
		const reportedTarget = props.settingsTarget === ConfigurationTarget.USER_LOCAL ? 'user' :
			props.settingsTarget === ConfigurationTarget.USER_REMOTE ? 'user_remote' :
				props.settingsTarget === ConfigurationTarget.WORKSPACE ? 'workspace' :
					'folder';
845 846 847 848 849 850 851 852 853 854 855 856 857

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

		/* __GDPR__
858
			"settingsEditor.settingModified" : {
859 860 861 862 863 864 865 866 867 868
				"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" }
			}
		*/
869
		this.telemetryService.publicLog('settingsEditor.settingModified', data);
R
Rob Lourens 已提交
870 871
	}

J
Johannes Rieken 已提交
872
	private render(token: CancellationToken): Promise<any> {
R
Rob Lourens 已提交
873 874
		if (this.input) {
			return this.input.resolve()
875
				.then((model: Settings2EditorModel) => {
876
					if (token.isCancellationRequested) {
R
Rob Lourens 已提交
877
						return undefined;
878 879
					}

880
					this._register(model.onDidChangeGroups(() => {
881 882 883
						this.updatedConfigSchemaDelayer.trigger(() => {
							this.onConfigUpdate(undefined, undefined, true);
						});
884
					}));
885
					this.defaultSettingsEditorModel = model;
886
					return this.onConfigUpdate(undefined, true);
887
				});
R
Rob Lourens 已提交
888
		}
R
Rob Lourens 已提交
889
		return Promise.resolve(null);
R
Rob Lourens 已提交
890 891
	}

892
	private onSearchModeToggled(): void {
893
		DOM.removeClass(this.rootElement, 'no-toc-search');
894
		if (this.configurationService.getValue('workbench.settings.settingsSearchTocBehavior') === 'hide') {
895
			DOM.toggleClass(this.rootElement, 'no-toc-search', !!this.searchResultModel);
896
		}
897 898
	}

899 900
	private scheduleRefresh(element: HTMLElement, key = ''): void {
		if (key && this.scheduledRefreshes.has(key)) {
901 902 903
			return;
		}

904 905 906 907 908 909 910 911 912 913 914
		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]);
915 916 917
		});
	}

918
	private async onConfigUpdate(keys?: string[], forceRefresh = false, schemaChange = false): Promise<void> {
919
		if (keys && this.settingsTreeModel) {
920 921 922
			return this.updateElementsByKey(keys);
		}

923
		const groups = this.defaultSettingsEditorModel.settingsGroups.slice(1); // Without commonlyUsed
924
		const dividedGroups = collections.groupBy(groups, g => g.contributedByExtension ? 'extension' : 'core');
925 926 927 928 929
		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 已提交
930
			const settingKeyList: string[] = [];
931 932 933 934 935 936 937 938
			settingsResult.leftoverSettings.forEach(s => {
				settingKeyList.push(s.key);
			});

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

939
		const commonlyUsed = resolveSettingsTree(commonlyUsedData, dividedGroups.core);
R
Rob Lourens 已提交
940
		resolvedSettingsRoot.children!.unshift(commonlyUsed.tree);
941

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

944 945 946 947
		if (this.searchResultModel) {
			this.searchResultModel.updateChildren();
		}

948 949
		if (this.settingsTreeModel) {
			this.settingsTreeModel.update(resolvedSettingsRoot);
950

951 952 953
			if (schemaChange && !!this.searchResultModel) {
				// If an extension's settings were just loaded and a search is active, retrigger the search so it shows up
				return await this.onSearchInputChanged();
954
			}
955 956

			this.refreshTOCTree();
957
			this.renderTree(undefined, forceRefresh);
958
		} else {
959 960
			this.settingsTreeModel = this.instantiationService.createInstance(SettingsTreeModel, this.viewState);
			this.settingsTreeModel.update(resolvedSettingsRoot);
961
			this.tocTreeModel.settingsTreeRoot = this.settingsTreeModel.root as SettingsTreeGroupElement;
962

963 964 965 966 967 968 969 970
			const cachedState = this.restoreCachedState();
			if (cachedState && cachedState.searchQuery) {
				await this.onSearchInputChanged();
			} else {
				this.refreshTOCTree();
				this.refreshTree();
				this.tocTree.collapseAll();
			}
971 972 973
		}
	}

U
Ubuntu 已提交
974
	private updateElementsByKey(keys: string[]): void {
975 976
		if (keys.length) {
			if (this.searchResultModel) {
R
Rob Lourens 已提交
977
				keys.forEach(key => this.searchResultModel!.updateElementsByName(key));
978 979 980 981 982 983
			}

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

U
Ubuntu 已提交
984
			keys.forEach(key => this.renderTree(key));
985 986 987 988 989
		} else {
			return this.renderTree();
		}
	}

990 991 992 993 994 995
	private getActiveElementInSettingsTree(): HTMLElement | null {
		return (document.activeElement && DOM.isAncestor(document.activeElement, this.settingsTree.getHTMLElement())) ?
			<HTMLElement>document.activeElement :
			null;
	}

U
Ubuntu 已提交
996
	private renderTree(key?: string, force = false): void {
997
		if (!force && key && this.scheduledRefreshes.has(key)) {
998
			this.updateModifiedLabelForKey(key);
U
Ubuntu 已提交
999
			return;
1000 1001
		}

1002 1003
		// If the context view is focused, delay rendering settings
		if (this.contextViewFocused()) {
M
Matt Bierner 已提交
1004 1005 1006 1007
			const element = document.querySelector('.context-view');
			if (element) {
				this.scheduleRefresh(element as HTMLElement, key);
			}
U
Ubuntu 已提交
1008
			return;
1009 1010
		}

1011
		// If a setting control is currently focused, schedule a refresh for later
R
Rob Lourens 已提交
1012 1013
		const activeElement = this.getActiveElementInSettingsTree();
		const focusedSetting = activeElement && this.settingRenderers.getSettingDOMElementForDOMElement(activeElement);
1014
		if (focusedSetting && !force) {
1015 1016
			// 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 已提交
1017
				const focusedKey = focusedSetting.getAttribute(AbstractSettingRenderer.SETTING_KEY_ATTR);
P
Pine Wu 已提交
1018
				if (focusedKey === key &&
P
Pine Wu 已提交
1019 1020 1021
					// update `list`s live, as they have a separate "submit edit" step built in before this
					(focusedSetting.parentElement && !DOM.hasClass(focusedSetting.parentElement, 'setting-item-list'))
				) {
1022

1023
					this.updateModifiedLabelForKey(key);
1024
					this.scheduleRefresh(focusedSetting, key);
U
Ubuntu 已提交
1025
					return;
1026 1027
				}
			} else {
1028
				this.scheduleRefresh(focusedSetting);
U
Ubuntu 已提交
1029
				return;
1030
			}
1031
		}
R
Rob Lourens 已提交
1032

R
Rob Lourens 已提交
1033 1034
		this.renderResultCountMessages();

1035
		if (key) {
1036
			const elements = this.currentSettingsModel.getElementsByName(key);
1037
			if (elements && elements.length) {
1038
				// TODO https://github.com/Microsoft/vscode/issues/57360
R
Rob Lourens 已提交
1039
				this.refreshTree();
1040 1041
			} else {
				// Refresh requested for a key that we don't know about
U
Ubuntu 已提交
1042
				return;
1043
			}
1044
		} else {
R
Rob Lourens 已提交
1045
			this.refreshTree();
1046 1047
		}

U
Ubuntu 已提交
1048
		return;
R
Rob Lourens 已提交
1049 1050
	}

1051 1052 1053 1054
	private contextViewFocused(): boolean {
		return !!DOM.findParentWithClass(<HTMLElement>document.activeElement, 'context-view');
	}

R
Rob Lourens 已提交
1055
	private refreshTree(): void {
1056 1057 1058
		if (this.isVisible()) {
			this.settingsTree.setChildren(null, createGroupIterator(this.currentSettingsModel.root));
		}
1059 1060
	}

R
Rob Lourens 已提交
1061
	private refreshTOCTree(): void {
1062
		if (this.isVisible()) {
R
Rob Lourens 已提交
1063
			this.tocTreeModel.update();
1064 1065
			this.tocTree.setChildren(null, createTOCIterator(this.tocTreeModel, this.tocTree));
		}
R
Rob Lourens 已提交
1066 1067
	}

1068
	private updateModifiedLabelForKey(key: string): void {
1069
		const dataElements = this.currentSettingsModel.getElementsByName(key);
1070
		const isModified = dataElements && dataElements[0] && dataElements[0].isConfigured; // all elements are either configured or not
R
Rob Lourens 已提交
1071
		const elements = this.settingRenderers.getDOMElementsForSettingKey(this.settingsTree.getHTMLElement(), key);
1072
		if (elements && elements[0]) {
R
Rob Lourens 已提交
1073
			DOM.toggleClass(elements[0], 'is-configured', !!isModified);
1074 1075 1076
		}
	}

1077
	private async onSearchInputChanged(): Promise<void> {
R
Rob Lourens 已提交
1078 1079
		const query = this.searchWidget.getValue().trim();
		this.delayedFilterLogging.cancel();
1080 1081 1082 1083 1084
		await this.triggerSearch(query.replace(/›/g, ' '));

		if (query && this.searchResultModel) {
			this.delayedFilterLogging.trigger(() => this.reportFilteringUsed(query, this.searchResultModel!.getUniqueResults()));
		}
R
Rob Lourens 已提交
1085 1086
	}

R
Rob Lourens 已提交
1087
	private parseSettingFromJSON(query: string): string | null {
1088 1089 1090 1091
		const match = query.match(/"([a-zA-Z.]+)": /);
		return match && match[1];
	}

J
Johannes Rieken 已提交
1092
	private triggerSearch(query: string): Promise<void> {
1093
		this.viewState.tagFilters = new Set<string>();
P
Peng Lyu 已提交
1094
		this.viewState.extensionFilters = new Set<string>();
1095
		if (query) {
1096
			const parsedQuery = parseQuery(query);
R
Rob Lourens 已提交
1097
			query = parsedQuery.query;
R
Rob Lourens 已提交
1098
			parsedQuery.tags.forEach(tag => this.viewState.tagFilters!.add(tag));
P
Peng Lyu 已提交
1099
			parsedQuery.extensionFilters.forEach(extensionId => this.viewState.extensionFilters!.add(extensionId));
1100
		}
1101 1102

		if (query && query !== '@') {
1103
			query = this.parseSettingFromJSON(query) || query;
1104
			return this.triggerFilterPreferences(query);
R
Rob Lourens 已提交
1105
		} else {
P
Peng Lyu 已提交
1106
			if ((this.viewState.tagFilters && this.viewState.tagFilters.size) || (this.viewState.extensionFilters && this.viewState.extensionFilters.size)) {
1107 1108 1109 1110 1111
				this.searchResultModel = this.createFilterModel();
			} else {
				this.searchResultModel = null;
			}

R
Rob Lourens 已提交
1112 1113
			this.localSearchDelayer.cancel();
			this.remoteSearchThrottle.cancel();
1114 1115 1116 1117
			if (this.searchInProgress) {
				this.searchInProgress.cancel();
				this.searchInProgress.dispose();
				this.searchInProgress = null;
R
Rob Lourens 已提交
1118
			}
R
Rob Lourens 已提交
1119

1120
			this.tocTree.setFocus([]);
R
Rob Lourens 已提交
1121
			this.viewState.filterToCategory = undefined;
1122
			this.tocTreeModel.currentSearchModel = this.searchResultModel;
1123
			this.onSearchModeToggled();
1124 1125

			if (this.searchResultModel) {
1126 1127
				// Added a filter model
				this.tocTree.setSelection([]);
R
Rob Lourens 已提交
1128
				this.tocTree.expandAll();
1129
				this.refreshTOCTree();
R
Rob Lourens 已提交
1130
				this.renderResultCountMessages();
R
Rob Lourens 已提交
1131
				this.refreshTree();
1132
			} else {
1133
				// Leaving search mode
R
Rob Lourens 已提交
1134
				this.tocTree.collapseAll();
1135
				this.refreshTOCTree();
R
Rob Lourens 已提交
1136
				this.renderResultCountMessages();
R
Rob Lourens 已提交
1137
				this.refreshTree();
1138
			}
R
Rob Lourens 已提交
1139
		}
R
Rob Lourens 已提交
1140

R
Rob Lourens 已提交
1141
		return Promise.resolve();
R
Rob Lourens 已提交
1142 1143
	}

1144 1145 1146 1147 1148 1149 1150 1151 1152
	/**
	 * 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 已提交
1153 1154 1155
		for (const g of this.defaultSettingsEditorModel.settingsGroups.slice(1)) {
			for (const sect of g.sections) {
				for (const setting of sect.settings) {
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
					fullResult.filterMatches.push({ setting, matches: [], score: 0 });
				}
			}
		}

		filterModel.setResult(0, fullResult);

		return filterModel;
	}

1166 1167 1168 1169
	private reportFilteringUsed(query: string, results: ISearchResult[]): void {
		const nlpResult = results[SearchResultIdx.Remote];
		const nlpMetadata = nlpResult && nlpResult.metadata;

1170 1171 1172
		const durations = {
			nlpResult: nlpMetadata && nlpMetadata.duration
		};
1173 1174

		// Count unique results
1175
		const counts: { nlpResult?: number, filterResult?: number } = {};
1176
		const filterResult = results[SearchResultIdx.Local];
1177 1178 1179 1180
		if (filterResult) {
			counts['filterResult'] = filterResult.filterMatches.length;
		}

1181 1182
		if (nlpResult) {
			counts['nlpResult'] = nlpResult.filterMatches.length;
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
		}

		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 }
			}
		*/
1203
		this.telemetryService.publicLog('settingsEditor.filter', data);
1204 1205
	}

J
Johannes Rieken 已提交
1206
	private triggerFilterPreferences(query: string): Promise<void> {
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
		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 => {
1217
					if (result && !result.exactMatch) {
1218 1219
						this.remoteSearchThrottle.trigger(() => {
							return searchInProgress && !searchInProgress.token.isCancellationRequested ?
R
Rob Lourens 已提交
1220 1221
								this.remoteSearchPreferences(query, this.searchInProgress!.token) :
								Promise.resolve();
1222 1223
						});
					}
1224
				});
1225
			} else {
R
Rob Lourens 已提交
1226
				return Promise.resolve();
1227 1228 1229 1230
			}
		});
	}

R
Rob Lourens 已提交
1231
	private localFilterPreferences(query: string, token?: CancellationToken): Promise<ISearchResult | null> {
1232
		const localSearchProvider = this.preferencesSearchService.getLocalSearchProvider(query);
1233
		return this.filterOrSearchPreferences(query, SearchResultIdx.Local, localSearchProvider, token);
R
Rob Lourens 已提交
1234 1235
	}

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

R
Rob Lourens 已提交
1240
		return Promise.all([
1241 1242
			this.filterOrSearchPreferences(query, SearchResultIdx.Remote, remoteSearchProvider, token),
			this.filterOrSearchPreferences(query, SearchResultIdx.NewExtensions, newExtSearchProvider, token)
R
Rob Lourens 已提交
1243
		]).then(() => { });
R
Rob Lourens 已提交
1244 1245
	}

R
Rob Lourens 已提交
1246
	private filterOrSearchPreferences(query: string, type: SearchResultIdx, searchProvider?: ISearchProvider, token?: CancellationToken): Promise<ISearchResult | null> {
1247 1248 1249 1250 1251
		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;
			}
1252

1253 1254 1255 1256
			if (!this.searchResultModel) {
				this.searchResultModel = this.instantiationService.createInstance(SearchResultModel, this.viewState);
				this.searchResultModel.setResult(type, result);
				this.tocTreeModel.currentSearchModel = this.searchResultModel;
1257
				this.onSearchModeToggled();
1258 1259
			} else {
				this.searchResultModel.setResult(type, result);
1260
				this.tocTreeModel.update();
1261
			}
R
Rob Lourens 已提交
1262

1263
			this.tocTree.setFocus([]);
R
Rob Lourens 已提交
1264
			this.viewState.filterToCategory = undefined;
R
Rob Lourens 已提交
1265
			this.tocTree.expandAll();
1266

1267
			this.refreshTOCTree();
1268
			this.renderTree(undefined, true);
U
Ubuntu 已提交
1269
			return result;
R
Rob Lourens 已提交
1270 1271 1272
		});
	}

1273
	private renderResultCountMessages() {
1274
		if (!this.currentSettingsModel) {
1275 1276 1277
			return;
		}

R
Rob Lourens 已提交
1278 1279 1280 1281
		this.clearFilterLinkContainer.style.display = this.viewState.tagFilters && this.viewState.tagFilters.size > 0
			? 'initial'
			: 'none';

1282
		if (!this.searchResultModel) {
1283 1284 1285 1286 1287
			if (this.countElement.style.display !== 'none') {
				this.countElement.style.display = 'none';
				this.layout(this.dimension);
			}

R
Rob Lourens 已提交
1288 1289
			DOM.removeClass(this.rootElement, 'no-results');
			return;
1290 1291
		}

1292 1293 1294 1295 1296 1297 1298
		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);
			}
1299

1300 1301 1302 1303
			if (this.countElement.style.display !== 'block') {
				this.countElement.style.display = 'block';
				this.layout(this.dimension);
			}
R
Rob Lourens 已提交
1304
			DOM.toggleClass(this.rootElement, 'no-results', count === 0);
1305
		}
1306 1307
	}

R
Rob Lourens 已提交
1308
	private _filterOrSearchPreferencesModel(filter: string, model: ISettingsEditorModel, provider?: ISearchProvider, token?: CancellationToken): Promise<ISearchResult | null> {
R
Rob Lourens 已提交
1309
		const searchP = provider ? provider.searchModel(model, token) : Promise.resolve(null);
R
Rob Lourens 已提交
1310 1311 1312
		return searchP
			.then<ISearchResult>(null, err => {
				if (isPromiseCanceledError(err)) {
R
Rob Lourens 已提交
1313
					return Promise.reject(err);
R
Rob Lourens 已提交
1314 1315
				} else {
					/* __GDPR__
1316
						"settingsEditor.searchError" : {
R
Rob Lourens 已提交
1317 1318 1319 1320 1321 1322 1323
							"message": { "classification": "CallstackOrException", "purpose": "FeatureInsight" },
							"filter": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
						}
					*/
					const message = getErrorMessage(err).trim();
					if (message && message !== 'Error') {
						// "Error" = any generic network error
1324
						this.telemetryService.publicLog('settingsEditor.searchError', { message, filter });
R
Rob Lourens 已提交
1325 1326
						this.logService.info('Setting search error: ' + message);
					}
R
Rob Lourens 已提交
1327
					return Promise.resolve(null);
R
Rob Lourens 已提交
1328 1329 1330 1331
				}
			});
	}

1332
	private layoutTrees(dimension: DOM.Dimension): void {
1333
		const listHeight = dimension.height - (76 + 11 /* header height + padding*/);
1334 1335
		const settingsTreeHeight = listHeight - 14;
		this.settingsTreeContainer.style.height = `${settingsTreeHeight}px`;
1336
		this.settingsTree.layout(settingsTreeHeight, dimension.width);
1337

1338 1339
		const tocTreeHeight = listHeight - 16;
		this.tocTreeContainer.style.height = `${tocTreeHeight}px`;
R
Rob Lourens 已提交
1340
		this.tocTree.layout(tocTreeHeight);
1341
	}
1342

B
Benjamin Pasero 已提交
1343
	protected saveState(): void {
1344 1345 1346
		if (this.isVisible()) {
			const searchQuery = this.searchWidget.getValue().trim();
			const target = this.settingsTargetsWidget.settingsTarget as SettingsTarget;
R
Rob Lourens 已提交
1347 1348 1349
			if (this.group && this.input) {
				this.editorMemento.saveEditorState(this.group, this.input, { searchQuery, target });
			}
1350
		}
B
Benjamin Pasero 已提交
1351 1352

		super.saveState();
1353
	}
R
Rob Lourens 已提交
1354
}
1355

1356 1357 1358 1359
interface ISettingsEditor2State {
	searchQuery: string;
	target: SettingsTarget;
}