settingsEditor2.ts 51.0 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 8
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
R
Rob Lourens 已提交
9
import { ITreeElement } from 'vs/base/browser/ui/tree/tree';
R
Rob Lourens 已提交
10
import { Action } from 'vs/base/common/actions';
11
import * as arrays from 'vs/base/common/arrays';
12
import { Delayer, ThrottledDelayer, timeout } from 'vs/base/common/async';
13
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
R
Rob Lourens 已提交
14
import * as collections from 'vs/base/common/collections';
15
import { getErrorMessage, isPromiseCanceledError } from 'vs/base/common/errors';
R
Rob Lourens 已提交
16
import { Iterator } from 'vs/base/common/iterator';
R
Rob Lourens 已提交
17 18
import { KeyCode } from 'vs/base/common/keyCodes';
import * as platform from 'vs/base/common/platform';
P
Peng Lyu 已提交
19
import * as strings from 'vs/base/common/strings';
20
import { isArray, withNullAsUndefined, withUndefinedAsNull } from 'vs/base/common/types';
21
import { URI } from 'vs/base/common/uri';
R
Rob Lourens 已提交
22 23
import 'vs/css!./media/settingsEditor2';
import { localize } from 'vs/nls';
24
import { ConfigurationTarget, IConfigurationOverrides, IConfigurationService } from 'vs/platform/configuration/common/configuration';
R
Rob Lourens 已提交
25
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
R
Rob Lourens 已提交
26
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
R
Rob Lourens 已提交
27
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
28
import { ILogService } from 'vs/platform/log/common/log';
J
Jackson Kearl 已提交
29
import { INotificationService } from 'vs/platform/notification/common/notification';
B
Benjamin Pasero 已提交
30
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
R
Rob Lourens 已提交
31
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
J
Jackson Kearl 已提交
32
import { badgeBackground, badgeForeground, contrastBorder, editorForeground } from 'vs/platform/theme/common/colorRegistry';
33
import { attachStylerCallback } from 'vs/platform/theme/common/styler';
34
import { IThemeService } from 'vs/platform/theme/common/themeService';
R
Rob Lourens 已提交
35
import { BaseEditor } from 'vs/workbench/browser/parts/editor/baseEditor';
36
import { IEditorPane, IEditorMemento } from 'vs/workbench/common/editor';
37
import { attachSuggestEnabledInputBoxStyler, SuggestEnabledInput } from 'vs/workbench/contrib/codeEditor/browser/suggestEnabledInput/suggestEnabledInput';
38 39 40 41 42 43
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';
R
Rob Lourens 已提交
44
import { CONTEXT_SETTINGS_EDITOR, CONTEXT_SETTINGS_SEARCH_FOCUS, CONTEXT_TOC_ROW_FOCUS, EXTENSION_SETTING_TAG, IPreferencesSearchService, ISearchProvider, MODIFIED_SETTING_TAG, SETTINGS_EDITOR_COMMAND_CLEAR_SEARCH_RESULTS, SETTINGS_EDITOR_COMMAND_SHOW_CONTEXT_MENU } from 'vs/workbench/contrib/preferences/common/preferences';
45
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
46
import { IPreferencesService, ISearchResult, ISettingsEditorModel, ISettingsEditorOptions, SettingsEditorOptions, SettingValueType } from 'vs/workbench/services/preferences/common/preferences';
47
import { SettingsEditor2Input } from 'vs/workbench/services/preferences/common/preferencesEditorInput';
48
import { Settings2EditorModel } from 'vs/workbench/services/preferences/common/preferencesModels';
M
Matt Bierner 已提交
49
import { IEditorModel } from 'vs/platform/editor/common/editor';
R
Rob Lourens 已提交
50

R
Rob Lourens 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63
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
		};
	});
}

64 65
const $ = DOM.$;

R
Rob Lourens 已提交
66 67 68 69
interface IFocusEventFromScroll extends KeyboardEvent {
	fromScroll: true;
}

70
const SETTINGS_EDITOR_STATE_KEY = 'settingsEditorState';
R
Rob Lourens 已提交
71 72
export class SettingsEditor2 extends BaseEditor {

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

79
	private static readonly SUGGESTIONS: string[] = [
R
Rob Lourens 已提交
80
		`@${MODIFIED_SETTING_TAG}`, '@tag:usesOnlineServices', '@tag:sync', `@${EXTENSION_SETTING_TAG}`
81 82
	];

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

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

98 99 100 101
	private rootElement!: HTMLElement;
	private headerContainer!: HTMLElement;
	private searchWidget!: SuggestEnabledInput;
	private countElement!: HTMLElement;
102
	private controlsElement!: HTMLElement;
103
	private settingsTargetsWidget!: SettingsTargetsWidget;
R
Rob Lourens 已提交
104

105 106 107 108 109 110 111
	private settingsTreeContainer!: HTMLElement;
	private settingsTree!: SettingsTree;
	private settingRenderers!: SettingTreeRenderers;
	private tocTreeModel!: TOCTreeModel;
	private settingsTreeModel!: SettingsTreeModel;
	private noResultsMessage!: HTMLElement;
	private clearFilterLinkContainer!: HTMLElement;
R
Rob Lourens 已提交
112

113 114
	private tocTreeContainer!: HTMLElement;
	private tocTree!: TOCTree;
R
Rob Lourens 已提交
115

116
	private settingsAriaExtraLabelsContainer!: HTMLElement;
117

R
Rob Lourens 已提交
118 119 120
	private delayedFilterLogging: Delayer<void>;
	private localSearchDelayer: Delayer<void>;
	private remoteSearchThrottle: ThrottledDelayer<void>;
121
	private searchInProgress: CancellationTokenSource | null = null;
122

123 124
	private updatedConfigSchemaDelayer: Delayer<void>;

125 126
	private settingFastUpdateDelayer: Delayer<void>;
	private settingSlowUpdateDelayer: Delayer<void>;
127
	private pendingSettingUpdate: { key: string, value: any } | null = null;
R
Rob Lourens 已提交
128

129
	private readonly viewState: ISettingsEditorViewState;
130
	private _searchResultModel: SearchResultModel | null = null;
131

132
	private tocRowFocused: IContextKey<boolean>;
133 134
	private inSettingsEditorContextKey: IContextKey<boolean>;
	private searchFocusContextKey: IContextKey<boolean>;
135

136
	private scheduledRefreshes: Map<string, DOM.IFocusTracker>;
137
	private lastFocusedSettingElement: string | null = null;
138

139
	/** Don't spam warnings */
140
	private hasWarnedMissingSettings = false;
141

142 143
	private editorMemento: IEditorMemento<ISettingsEditor2State>;

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

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

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

171 172
		this.updatedConfigSchemaDelayer = new Delayer<void>(SettingsEditor2.CONFIG_SCHEMA_UPDATE_DELAYER);

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

177 178
		this.scheduledRefreshes = new Map<string, DOM.IFocusTracker>();

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

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

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

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

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

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

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

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

218 219
		this.createHeader(this.rootElement);
		this.createBody(this.rootElement);
R
Rob Lourens 已提交
220
		this.addCtrlAInterceptor(this.rootElement);
221
		this.updateStyles();
R
Rob Lourens 已提交
222 223
	}

224
	setInput(input: SettingsEditor2Input, options: SettingsEditorOptions | undefined, token: CancellationToken): Promise<void> {
225
		this.inSettingsEditorContextKey.set(true);
226
		return super.setInput(input, options, token)
227
			.then(() => timeout(0)) // Force setInput to be async
R
Rob Lourens 已提交
228
			.then(() => {
229 230 231 232 233 234 235 236
				// 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;
						}
237
					}
R
Rob Lourens 已提交
238

239
					this._setOptions(options);
240

241 242 243
					this._register(input.onDispose(() => {
						this.searchWidget.setValue('');
					}));
244

245 246 247
					// Init TOC selection
					this.updateTreeScrollSync();
				});
R
Rob Lourens 已提交
248
			});
R
Rob Lourens 已提交
249 250
	}

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

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

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

		return withUndefinedAsNull(cachedState);
269 270
	}

271
	setOptions(options: SettingsEditorOptions | undefined): void {
272 273
		super.setOptions(options);

R
Rob Lourens 已提交
274 275 276
		if (options) {
			this._setOptions(options);
		}
277
	}
278

279
	private _setOptions(options: SettingsEditorOptions): void {
280 281 282 283
		if (options.query) {
			this.searchWidget.setValue(options.query);
		}

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

291 292 293 294 295
	clearInput(): void {
		this.inSettingsEditorContextKey.set(false);
		super.clearInput();
	}

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

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

303 304
		this.layoutTrees(dimension);

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

310 311
		DOM.toggleClass(this.rootElement, 'mid-width', dimension.width < 1000 && dimension.width >= 600);
		DOM.toggleClass(this.rootElement, 'narrow-width', dimension.width < 600);
R
Rob Lourens 已提交
312 313 314
	}

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

326 327 328
		this.focusSearch();
	}

329 330 331 332
	onHide(): void {
		this.searchWidget.onHide();
	}

333
	focusSettings(): void {
334 335 336 337 338
		// Update ARIA global labels
		const labelElement = this.settingsAriaExtraLabelsContainer.querySelector('#settings_aria_more_actions_shortcut_label');
		if (labelElement) {
			const settingsContextMenuShortcut = this.currentSettingsContextMenuKeyBindingLabel;
			if (settingsContextMenuShortcut) {
339
				labelElement.setAttribute('aria-label', localize('settingsContextMenuAriaShortcut', "For more actions, Press {0}.", settingsContextMenuShortcut));
340 341 342
			}
		}

R
Rob Lourens 已提交
343
		const firstFocusable = this.settingsTree.getHTMLElement().querySelector(AbstractSettingRenderer.CONTROL_SELECTOR);
344 345
		if (firstFocusable) {
			(<HTMLElement>firstFocusable).focus();
346 347 348
		}
	}

R
Rob Lourens 已提交
349 350 351 352
	focusTOC(): void {
		this.tocTree.domFocus();
	}

353
	showContextMenu(): void {
R
Rob Lourens 已提交
354 355 356 357 358 359
		const activeElement = this.getActiveElementInSettingsTree();
		if (!activeElement) {
			return;
		}

		const settingDOMElement = this.settingRenderers.getSettingDOMElementForDOMElement(activeElement);
360 361 362 363
		if (!settingDOMElement) {
			return;
		}

R
Rob Lourens 已提交
364
		const focusedKey = this.settingRenderers.getKeyForDOMElementInSetting(settingDOMElement);
365 366 367 368 369 370
		if (!focusedKey) {
			return;
		}

		const elements = this.currentSettingsModel.getElementsByName(focusedKey);
		if (elements && elements[0]) {
R
Rob Lourens 已提交
371
			this.settingRenderers.showContextMenu(elements[0], settingDOMElement);
372 373 374
		}
	}

375
	focusSearch(filter?: string, selectAll = true): void {
376 377 378 379
		if (filter && this.searchWidget) {
			this.searchWidget.setValue(filter);
		}

380
		this.searchWidget.focus(selectAll);
R
Rob Lourens 已提交
381 382
	}

383
	clearSearchResults(): void {
384
		this.searchWidget.setValue('');
385
		this.focusSearch();
386 387
	}

388 389 390 391 392 393 394 395 396 397
	clearSearchFilters(): void {
		let query = this.searchWidget.getValue();

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

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

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

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

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

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

418 419 420 421
		this._register(this.searchWidget.onFocus(() => {
			this.lastFocusedSettingElement = '';
		}));

422 423 424 425
		this._register(attachSuggestEnabledInputBoxStyler(this.searchWidget, this.themeService, {
			inputBorder: settingsTextInputBorder
		}));

426 427
		this.countElement = DOM.append(searchContainer, DOM.$('.settings-count-widget'));
		this._register(attachStylerCallback(this.themeService, { badgeBackground, contrastBorder, badgeForeground }, colors => {
428 429 430
			const background = colors.badgeBackground ? colors.badgeBackground.toString() : '';
			const border = colors.contrastBorder ? colors.contrastBorder.toString() : '';
			const foreground = colors.badgeForeground ? colors.badgeForeground.toString() : '';
431 432

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

435 436
			this.countElement.style.borderWidth = border ? '1px' : '';
			this.countElement.style.borderStyle = border ? 'solid' : '';
437 438 439
			this.countElement.style.borderColor = border;
		}));

440 441 442 443 444
		this._register(this.searchWidget.onInputDidChange(() => {
			const searchVal = this.searchWidget.getValue();
			clearInputAction.enabled = !!searchVal;
			this.onSearchInputChanged();
		}));
R
Rob Lourens 已提交
445

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

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

454
		const actionBar = this._register(new ActionBar(this.controlsElement, {
455
			animated: false,
M
Matt Bierner 已提交
456
			actionViewItemProvider: (_action) => { return undefined; }
457 458
		}));

459
		actionBar.push([clearInputAction], { label: false, icon: true });
R
Rob Lourens 已提交
460 461
	}

462 463 464
	private onDidSettingsTargetChange(target: SettingsTarget): void {
		this.viewState.settingsTarget = target;

465 466
		// TODO Instead of rebuilding the whole model, refresh and uncache the inspected setting value
		this.onConfigUpdate(undefined, true);
467 468
	}

469
	private onDidClickSetting(evt: ISettingLinkClickEvent, recursed?: boolean): void {
470
		const elements = this.currentSettingsModel.getElementsByName(evt.targetKey);
471
		if (elements && elements[0]) {
472
			let sourceTop = this.settingsTree.getRelativeTop(evt.source);
R
Rob Lourens 已提交
473 474 475 476
			if (typeof sourceTop !== 'number') {
				return;
			}

477 478
			if (sourceTop < 0) {
				// e.g. clicked a searched element, now the search has been cleared
479
				sourceTop = 0.5;
480 481
			}

482
			this.settingsTree.reveal(elements[0], sourceTop);
483

R
Rob Lourens 已提交
484
			const domElements = this.settingRenderers.getDOMElementsForSettingKey(this.settingsTree.getHTMLElement(), evt.targetKey);
485
			if (domElements && domElements[0]) {
R
Rob Lourens 已提交
486
				const control = domElements[0].querySelector(AbstractSettingRenderer.CONTROL_SELECTOR);
487 488 489 490
				if (control) {
					(<HTMLElement>control).focus();
				}
			}
491 492 493 494 495 496
		} else if (!recursed) {
			const p = this.triggerSearch('');
			p.then(() => {
				this.searchWidget.setValue('');
				this.onDidClickSetting(evt, true);
			});
497 498 499
		}
	}

500
	switchToSettingsFile(): Promise<IEditorPane | undefined> {
501 502
		const query = parseQuery(this.searchWidget.getValue()).query;
		return this.openSettingsFile({ query });
503 504
	}

505
	private async openSettingsFile(options?: ISettingsEditorOptions): Promise<IEditorPane | undefined> {
506 507
		const currentSettingsTarget = this.settingsTargetsWidget.settingsTarget;

R
Rob Lourens 已提交
508
		if (currentSettingsTarget === ConfigurationTarget.USER_LOCAL) {
509
			return this.preferencesService.openGlobalSettings(true, options);
R
Rob Lourens 已提交
510 511
		} else if (currentSettingsTarget === ConfigurationTarget.USER_REMOTE) {
			return this.preferencesService.openRemoteSettings();
512
		} else if (currentSettingsTarget === ConfigurationTarget.WORKSPACE) {
513
			return this.preferencesService.openWorkspaceSettings(true, options);
514
		} else if (URI.isUri(currentSettingsTarget)) {
515
			return this.preferencesService.openFolderSettings(currentSettingsTarget, true, options);
516
		}
517 518

		return undefined;
R
Rob Lourens 已提交
519 520 521 522 523
	}

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

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

526
		this.noResultsMessage.innerText = localize('noResults', "No Settings Found");
527 528 529 530 531

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

		this.clearFilterLinkContainer.textContent = ' - ';
		const clearFilterLink = DOM.append(this.clearFilterLinkContainer, $('a.pointer.prominent', { tabindex: 0 }, localize('clearSearchFilters', 'Clear Filters')));
532
		this._register(DOM.addDisposableListener(clearFilterLink, DOM.EventType.CLICK, (e: MouseEvent) => {
533 534 535 536 537 538
			DOM.EventHelper.stop(e, false);
			this.clearSearchFilters();
		}));

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

539
		this._register(attachStylerCallback(this.themeService, { editorForeground }, colors => {
M
Matt Bierner 已提交
540
			this.noResultsMessage.style.color = colors.editorForeground ? colors.editorForeground.toString() : '';
541 542
		}));

R
Rob Lourens 已提交
543 544
		this.createTOC(bodyContainer);

545 546 547
		this.createFocusSink(
			bodyContainer,
			e => {
J
Joao Moreno 已提交
548
				if (DOM.findParentWithClass(e.relatedTarget, 'settings-editor-tree')) {
549
					if (this.settingsTree.scrollTop > 0) {
550
						const firstElement = this.settingsTree.firstVisibleElement;
J
Joao Moreno 已提交
551 552 553 554 555

						if (typeof firstElement !== 'undefined') {
							this.settingsTree.reveal(firstElement, 0.1);
						}

556 557 558 559 560 561 562 563 564 565 566 567
						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 已提交
568

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

571 572 573
		this.createFocusSink(
			bodyContainer,
			e => {
J
Joao Moreno 已提交
574
				if (DOM.findParentWithClass(e.relatedTarget, 'settings-editor-tree')) {
575
					if (this.settingsTree.scrollTop < this.settingsTree.scrollHeight) {
576
						const lastElement = this.settingsTree.lastVisibleElement;
577 578 579 580 581 582 583 584 585 586 587
						this.settingsTree.reveal(lastElement, 0.9);
						return true;
					}
				}

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

R
Rob Lourens 已提交
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
	private addCtrlAInterceptor(container: HTMLElement): void {
		this._register(DOM.addStandardDisposableListener(container, DOM.EventType.KEY_DOWN, (e: StandardKeyboardEvent) => {
			if (
				e.keyCode === KeyCode.KEY_A &&
				(platform.isMacintosh ? e.metaKey : e.ctrlKey) &&
				e.target.tagName !== 'TEXTAREA' &&
				e.target.tagName !== 'INPUT'
			) {
				// Avoid browser ctrl+a
				e.browserEvent.stopPropagation();
				e.browserEvent.preventDefault();
			}
		}));
	}

603 604 605 606 607 608 609 610 611 612 613 614
	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;
	}
615

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

620 621
		this.tocTree = this._register(this.instantiationService.createInstance(TOCTree,
			DOM.append(this.tocTreeContainer, $('.settings-toc-wrapper')),
R
Rob Lourens 已提交
622
			this.viewState));
R
Rob Lourens 已提交
623

624
		this._register(this.tocTree.onDidChangeFocus(e => {
R
Rob Lourens 已提交
625
			const element: SettingsTreeGroupElement | null = e.elements[0];
R
Rob Lourens 已提交
626 627 628
			if (this.tocFocusedElement === element) {
				return;
			}
629

R
Rob Lourens 已提交
630 631 632 633
			this.tocFocusedElement = element;
			this.tocTree.setSelection(element ? [element] : []);
			if (this.searchResultModel) {
				if (this.viewState.filterToCategory !== element) {
634
					this.viewState.filterToCategory = withNullAsUndefined(element);
635 636
					this.renderTree();
					this.settingsTree.scrollTop = 0;
R
Rob Lourens 已提交
637
				}
R
Rob Lourens 已提交
638
			} else if (element && (!e.browserEvent || !(<IFocusEventFromScroll>e.browserEvent).fromScroll)) {
R
Rob Lourens 已提交
639 640
				this.settingsTree.reveal(element, 0);
			}
641 642 643 644 645 646 647 648
		}));

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

		this._register(this.tocTree.onDidBlur(() => {
			this.tocRowFocused.set(false);
R
Rob Lourens 已提交
649 650 651 652
		}));
	}

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

655 656 657 658 659 660 661 662
		// 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 已提交
663 664 665
		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 => {
666
			this.openSettingsFile({ editSetting: settingKey });
667
		}));
R
Rob Lourens 已提交
668 669
		this._register(this.settingRenderers.onDidClickSettingLink(settingName => this.onDidClickSetting(settingName)));
		this._register(this.settingRenderers.onDidFocusSetting(element => {
R
Rob Lourens 已提交
670
			this.lastFocusedSettingElement = element.setting.key;
671 672
			this.settingsTree.reveal(element);
		}));
R
Rob Lourens 已提交
673
		this._register(this.settingRenderers.onDidClickOverrideElement((element: ISettingOverrideClickEvent) => {
674
			if (element.scope.toLowerCase() === 'workspace') {
J
Jeremy Shore 已提交
675
				this.settingsTargetsWidget.updateTarget(ConfigurationTarget.WORKSPACE);
676
			} else if (element.scope.toLowerCase() === 'user') {
R
Rob Lourens 已提交
677
				this.settingsTargetsWidget.updateTarget(ConfigurationTarget.USER_LOCAL);
678
			} else if (element.scope.toLowerCase() === 'remote') {
R
Rob Lourens 已提交
679
				this.settingsTargetsWidget.updateTarget(ConfigurationTarget.USER_REMOTE);
J
Jeremy Shore 已提交
680 681 682 683
			}

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

685
		this.settingsTree = this._register(this.instantiationService.createInstance(SettingsTree,
686 687
			this.settingsTreeContainer,
			this.viewState,
R
Rob Lourens 已提交
688
			this.settingRenderers.allRenderers));
R
Rob Lourens 已提交
689
		this.settingsTree.getHTMLElement().attributes.removeNamedItem('tabindex');
690

691
		this._register(this.settingsTree.onDidScroll(() => {
692 693 694 695 696 697 698 699 700 701 702
			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);
703
		}));
704 705
	}

B
Benjamin Pasero 已提交
706 707
	private notifyNoSaveNeeded() {
		if (!this.storageService.getBoolean('hasNotifiedOfSettingsAutosave', StorageScope.GLOBAL, false)) {
B
Benjamin Pasero 已提交
708
			this.storageService.store('hasNotifiedOfSettingsAutosave', true, StorageScope.GLOBAL);
709 710
			this.notificationService.info(localize('settingsNoSaveNeeded', "Your changes are automatically saved as you edit."));
		}
J
Jackson Kearl 已提交
711 712
	}

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

716 717
		if (this.pendingSettingUpdate && this.pendingSettingUpdate.key !== key) {
			this.updateChangedSetting(key, value);
718 719
		}

720
		this.pendingSettingUpdate = { key, value };
721 722 723 724 725
		if (SettingsEditor2.shouldSettingUpdateFast(type)) {
			this.settingFastUpdateDelayer.trigger(() => this.updateChangedSetting(key, value));
		} else {
			this.settingSlowUpdateDelayer.trigger(() => this.updateChangedSetting(key, value));
		}
726 727
	}

728
	private updateTreeScrollSync(): void {
R
Rob Lourens 已提交
729
		this.settingRenderers.cancelSuggesters();
730 731 732 733
		if (this.searchResultModel) {
			return;
		}

R
Rob Lourens 已提交
734
		if (!this.tocTreeModel) {
735 736
			return;
		}
737

738
		const elementToSync = this.settingsTree.firstVisibleElement;
739 740 741 742
		const element = elementToSync instanceof SettingsTreeSettingElement ? elementToSync.parent :
			elementToSync instanceof SettingsTreeGroupElement ? elementToSync :
				null;

R
Rob Lourens 已提交
743 744 745 746 747 748 749 750
		// 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;
		}

751 752 753 754 755 756
		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 已提交
757 758 759 760
			if (typeof elementTop !== 'number') {
				return;
			}

761 762 763 764 765 766 767 768 769 770
			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 已提交
771

772
			this.tocTree.setSelection([element]);
773

774
			const fakeKeyboardEvent = new KeyboardEvent('keydown');
R
Rob Lourens 已提交
775
			(<IFocusEventFromScroll>fakeKeyboardEvent).fromScroll = true;
776 777 778
			this.tocTree.setFocus([element], fakeKeyboardEvent);
		}
	}
779

780 781 782 783 784 785 786 787 788 789
	private getAncestors(element: SettingsTreeElement): SettingsTreeElement[] {
		const ancestors: any[] = [];

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

			element = element.parent;
		}
790

791
		return ancestors.reverse();
792 793
	}

J
Johannes Rieken 已提交
794
	private updateChangedSetting(key: string, value: any): Promise<void> {
795 796
		// 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 已提交
797 798
		const settingsTarget = this.settingsTargetsWidget.settingsTarget;
		const resource = URI.isUri(settingsTarget) ? settingsTarget : undefined;
799
		const configurationTarget = <ConfigurationTarget>(resource ? ConfigurationTarget.WORKSPACE_FOLDER : settingsTarget);
R
Rob Lourens 已提交
800 801
		const overrides: IConfigurationOverrides = { resource };

802 803
		const isManualReset = value === undefined;

R
Rob Lourens 已提交
804 805
		// If the user is changing the value back to the default, do a 'reset' instead
		const inspected = this.configurationService.inspect(key, overrides);
S
rename  
Sandeep Somavarapu 已提交
806
		if (inspected.defaultValue === value) {
R
Rob Lourens 已提交
807 808 809 810
			value = undefined;
		}

		return this.configurationService.updateValue(key, value, overrides, configurationTarget)
811
			.then(() => {
812
				this.renderTree(key, isManualReset);
813 814 815 816 817
				const reportModifiedProps = {
					key,
					query: this.searchWidget.getValue(),
					searchResults: this.searchResultModel && this.searchResultModel.getUniqueResults(),
					rawResults: this.searchResultModel && this.searchResultModel.getRawResults(),
818
					showConfiguredOnly: !!this.viewState.tagFilters && this.viewState.tagFilters.has(MODIFIED_SETTING_TAG),
819 820 821 822 823 824
					isReset: typeof value === 'undefined',
					settingsTarget: this.settingsTargetsWidget.settingsTarget as SettingsTarget
				};

				return this.reportModifiedSetting(reportModifiedProps);
			});
825 826
	}

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

R
Rob Lourens 已提交
830 831 832
		let groupId: string | undefined = undefined;
		let nlpIndex: number | undefined = undefined;
		let displayIndex: number | undefined = undefined;
833
		if (props.searchResults) {
R
Rob Lourens 已提交
834 835 836 837
			const remoteResult = props.searchResults[SearchResultIdx.Remote];
			const localResult = props.searchResults[SearchResultIdx.Local];

			const localIndex = arrays.firstIndex(localResult!.filterMatches, m => m.setting.key === props.key);
838 839 840 841 842 843 844 845
			groupId = localIndex >= 0 ?
				'local' :
				'remote';

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

846 847 848 849 850 851
			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;
				}
852 853 854
			}
		}

R
Rob Lourens 已提交
855 856 857 858
		const reportedTarget = props.settingsTarget === ConfigurationTarget.USER_LOCAL ? 'user' :
			props.settingsTarget === ConfigurationTarget.USER_REMOTE ? 'user_remote' :
				props.settingsTarget === ConfigurationTarget.WORKSPACE ? 'workspace' :
					'folder';
859 860 861 862 863 864 865 866 867 868 869 870 871

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

		/* __GDPR__
872
			"settingsEditor.settingModified" : {
873 874 875 876 877 878 879 880 881 882
				"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" }
			}
		*/
883
		this.telemetryService.publicLog('settingsEditor.settingModified', data);
R
Rob Lourens 已提交
884 885
	}

J
Johannes Rieken 已提交
886
	private render(token: CancellationToken): Promise<any> {
R
Rob Lourens 已提交
887 888
		if (this.input) {
			return this.input.resolve()
M
Matt Bierner 已提交
889 890
				.then((model: IEditorModel | null) => {
					if (token.isCancellationRequested || !(model instanceof Settings2EditorModel)) {
R
Rob Lourens 已提交
891
						return undefined;
892 893
					}

894
					this._register(model.onDidChangeGroups(() => {
895 896 897
						this.updatedConfigSchemaDelayer.trigger(() => {
							this.onConfigUpdate(undefined, undefined, true);
						});
898
					}));
899
					this.defaultSettingsEditorModel = model;
900
					return this.onConfigUpdate(undefined, true);
901
				});
R
Rob Lourens 已提交
902
		}
R
Rob Lourens 已提交
903
		return Promise.resolve(null);
R
Rob Lourens 已提交
904 905
	}

906
	private onSearchModeToggled(): void {
907
		DOM.removeClass(this.rootElement, 'no-toc-search');
908
		if (this.configurationService.getValue('workbench.settings.settingsSearchTocBehavior') === 'hide') {
909
			DOM.toggleClass(this.rootElement, 'no-toc-search', !!this.searchResultModel);
910
		}
911 912
	}

913 914
	private scheduleRefresh(element: HTMLElement, key = ''): void {
		if (key && this.scheduledRefreshes.has(key)) {
915 916 917
			return;
		}

918 919 920 921 922 923 924 925 926 927 928
		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]);
929 930 931
		});
	}

932
	private async onConfigUpdate(keys?: string[], forceRefresh = false, schemaChange = false): Promise<void> {
933
		if (keys && this.settingsTreeModel) {
934 935 936
			return this.updateElementsByKey(keys);
		}

937
		const groups = this.defaultSettingsEditorModel.settingsGroups.slice(1); // Without commonlyUsed
938
		const dividedGroups = collections.groupBy(groups, g => g.contributedByExtension ? 'extension' : 'core');
939 940 941 942 943
		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 已提交
944
			const settingKeyList: string[] = [];
945 946 947 948 949 950 951 952
			settingsResult.leftoverSettings.forEach(s => {
				settingKeyList.push(s.key);
			});

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

953
		const commonlyUsed = resolveSettingsTree(commonlyUsedData, dividedGroups.core);
R
Rob Lourens 已提交
954
		resolvedSettingsRoot.children!.unshift(commonlyUsed.tree);
955

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

958 959 960 961
		if (this.searchResultModel) {
			this.searchResultModel.updateChildren();
		}

962 963
		if (this.settingsTreeModel) {
			this.settingsTreeModel.update(resolvedSettingsRoot);
964

965 966 967
			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();
968
			}
969 970

			this.refreshTOCTree();
971
			this.renderTree(undefined, forceRefresh);
972
		} else {
973 974
			this.settingsTreeModel = this.instantiationService.createInstance(SettingsTreeModel, this.viewState);
			this.settingsTreeModel.update(resolvedSettingsRoot);
975
			this.tocTreeModel.settingsTreeRoot = this.settingsTreeModel.root as SettingsTreeGroupElement;
976

977 978 979 980 981 982 983 984
			const cachedState = this.restoreCachedState();
			if (cachedState && cachedState.searchQuery) {
				await this.onSearchInputChanged();
			} else {
				this.refreshTOCTree();
				this.refreshTree();
				this.tocTree.collapseAll();
			}
985 986 987
		}
	}

U
Ubuntu 已提交
988
	private updateElementsByKey(keys: string[]): void {
989 990
		if (keys.length) {
			if (this.searchResultModel) {
R
Rob Lourens 已提交
991
				keys.forEach(key => this.searchResultModel!.updateElementsByName(key));
992 993 994 995 996 997
			}

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

U
Ubuntu 已提交
998
			keys.forEach(key => this.renderTree(key));
999 1000 1001 1002 1003
		} else {
			return this.renderTree();
		}
	}

1004 1005 1006 1007 1008 1009
	private getActiveElementInSettingsTree(): HTMLElement | null {
		return (document.activeElement && DOM.isAncestor(document.activeElement, this.settingsTree.getHTMLElement())) ?
			<HTMLElement>document.activeElement :
			null;
	}

U
Ubuntu 已提交
1010
	private renderTree(key?: string, force = false): void {
1011
		if (!force && key && this.scheduledRefreshes.has(key)) {
1012
			this.updateModifiedLabelForKey(key);
U
Ubuntu 已提交
1013
			return;
1014 1015
		}

1016 1017
		// If the context view is focused, delay rendering settings
		if (this.contextViewFocused()) {
M
Matt Bierner 已提交
1018 1019 1020 1021
			const element = document.querySelector('.context-view');
			if (element) {
				this.scheduleRefresh(element as HTMLElement, key);
			}
U
Ubuntu 已提交
1022
			return;
1023 1024
		}

1025
		// If a setting control is currently focused, schedule a refresh for later
R
Rob Lourens 已提交
1026 1027
		const activeElement = this.getActiveElementInSettingsTree();
		const focusedSetting = activeElement && this.settingRenderers.getSettingDOMElementForDOMElement(activeElement);
1028
		if (focusedSetting && !force) {
1029 1030
			// 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 已提交
1031
				const focusedKey = focusedSetting.getAttribute(AbstractSettingRenderer.SETTING_KEY_ATTR);
P
Pine Wu 已提交
1032
				if (focusedKey === key &&
P
Pine Wu 已提交
1033 1034 1035
					// 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'))
				) {
1036

1037
					this.updateModifiedLabelForKey(key);
1038
					this.scheduleRefresh(focusedSetting, key);
U
Ubuntu 已提交
1039
					return;
1040 1041
				}
			} else {
1042
				this.scheduleRefresh(focusedSetting);
U
Ubuntu 已提交
1043
				return;
1044
			}
1045
		}
R
Rob Lourens 已提交
1046

R
Rob Lourens 已提交
1047 1048
		this.renderResultCountMessages();

1049
		if (key) {
1050
			const elements = this.currentSettingsModel.getElementsByName(key);
1051
			if (elements && elements.length) {
1052
				// TODO https://github.com/Microsoft/vscode/issues/57360
R
Rob Lourens 已提交
1053
				this.refreshTree();
1054 1055
			} else {
				// Refresh requested for a key that we don't know about
U
Ubuntu 已提交
1056
				return;
1057
			}
1058
		} else {
R
Rob Lourens 已提交
1059
			this.refreshTree();
1060 1061
		}

U
Ubuntu 已提交
1062
		return;
R
Rob Lourens 已提交
1063 1064
	}

1065 1066 1067 1068
	private contextViewFocused(): boolean {
		return !!DOM.findParentWithClass(<HTMLElement>document.activeElement, 'context-view');
	}

R
Rob Lourens 已提交
1069
	private refreshTree(): void {
1070 1071 1072
		if (this.isVisible()) {
			this.settingsTree.setChildren(null, createGroupIterator(this.currentSettingsModel.root));
		}
1073 1074
	}

R
Rob Lourens 已提交
1075
	private refreshTOCTree(): void {
1076
		if (this.isVisible()) {
R
Rob Lourens 已提交
1077
			this.tocTreeModel.update();
1078 1079
			this.tocTree.setChildren(null, createTOCIterator(this.tocTreeModel, this.tocTree));
		}
R
Rob Lourens 已提交
1080 1081
	}

1082
	private updateModifiedLabelForKey(key: string): void {
1083
		const dataElements = this.currentSettingsModel.getElementsByName(key);
1084
		const isModified = dataElements && dataElements[0] && dataElements[0].isConfigured; // all elements are either configured or not
R
Rob Lourens 已提交
1085
		const elements = this.settingRenderers.getDOMElementsForSettingKey(this.settingsTree.getHTMLElement(), key);
1086
		if (elements && elements[0]) {
R
Rob Lourens 已提交
1087
			DOM.toggleClass(elements[0], 'is-configured', !!isModified);
1088 1089 1090
		}
	}

1091
	private async onSearchInputChanged(): Promise<void> {
R
Rob Lourens 已提交
1092 1093
		const query = this.searchWidget.getValue().trim();
		this.delayedFilterLogging.cancel();
1094 1095 1096 1097 1098
		await this.triggerSearch(query.replace(/›/g, ' '));

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

R
Rob Lourens 已提交
1101
	private parseSettingFromJSON(query: string): string | null {
1102 1103 1104 1105
		const match = query.match(/"([a-zA-Z.]+)": /);
		return match && match[1];
	}

J
Johannes Rieken 已提交
1106
	private triggerSearch(query: string): Promise<void> {
1107
		this.viewState.tagFilters = new Set<string>();
P
Peng Lyu 已提交
1108
		this.viewState.extensionFilters = new Set<string>();
1109
		if (query) {
1110
			const parsedQuery = parseQuery(query);
R
Rob Lourens 已提交
1111
			query = parsedQuery.query;
R
Rob Lourens 已提交
1112
			parsedQuery.tags.forEach(tag => this.viewState.tagFilters!.add(tag));
P
Peng Lyu 已提交
1113
			parsedQuery.extensionFilters.forEach(extensionId => this.viewState.extensionFilters!.add(extensionId));
1114
		}
1115 1116

		if (query && query !== '@') {
1117
			query = this.parseSettingFromJSON(query) || query;
1118
			return this.triggerFilterPreferences(query);
R
Rob Lourens 已提交
1119
		} else {
P
Peng Lyu 已提交
1120
			if ((this.viewState.tagFilters && this.viewState.tagFilters.size) || (this.viewState.extensionFilters && this.viewState.extensionFilters.size)) {
1121 1122 1123 1124 1125
				this.searchResultModel = this.createFilterModel();
			} else {
				this.searchResultModel = null;
			}

R
Rob Lourens 已提交
1126 1127
			this.localSearchDelayer.cancel();
			this.remoteSearchThrottle.cancel();
1128 1129 1130 1131
			if (this.searchInProgress) {
				this.searchInProgress.cancel();
				this.searchInProgress.dispose();
				this.searchInProgress = null;
R
Rob Lourens 已提交
1132
			}
R
Rob Lourens 已提交
1133

1134
			this.tocTree.setFocus([]);
R
Rob Lourens 已提交
1135
			this.viewState.filterToCategory = undefined;
1136
			this.tocTreeModel.currentSearchModel = this.searchResultModel;
1137
			this.onSearchModeToggled();
1138 1139

			if (this.searchResultModel) {
1140 1141
				// Added a filter model
				this.tocTree.setSelection([]);
R
Rob Lourens 已提交
1142
				this.tocTree.expandAll();
1143
				this.refreshTOCTree();
R
Rob Lourens 已提交
1144
				this.renderResultCountMessages();
R
Rob Lourens 已提交
1145
				this.refreshTree();
1146
			} else {
1147
				// Leaving search mode
R
Rob Lourens 已提交
1148
				this.tocTree.collapseAll();
1149
				this.refreshTOCTree();
R
Rob Lourens 已提交
1150
				this.renderResultCountMessages();
R
Rob Lourens 已提交
1151
				this.refreshTree();
1152
			}
R
Rob Lourens 已提交
1153
		}
R
Rob Lourens 已提交
1154

R
Rob Lourens 已提交
1155
		return Promise.resolve();
R
Rob Lourens 已提交
1156 1157
	}

1158 1159 1160 1161 1162 1163 1164 1165 1166
	/**
	 * 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 已提交
1167 1168 1169
		for (const g of this.defaultSettingsEditorModel.settingsGroups.slice(1)) {
			for (const sect of g.sections) {
				for (const setting of sect.settings) {
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
					fullResult.filterMatches.push({ setting, matches: [], score: 0 });
				}
			}
		}

		filterModel.setResult(0, fullResult);

		return filterModel;
	}

1180 1181 1182 1183
	private reportFilteringUsed(query: string, results: ISearchResult[]): void {
		const nlpResult = results[SearchResultIdx.Remote];
		const nlpMetadata = nlpResult && nlpResult.metadata;

1184 1185 1186
		const durations = {
			nlpResult: nlpMetadata && nlpMetadata.duration
		};
1187 1188

		// Count unique results
1189
		const counts: { nlpResult?: number, filterResult?: number } = {};
1190
		const filterResult = results[SearchResultIdx.Local];
1191 1192 1193 1194
		if (filterResult) {
			counts['filterResult'] = filterResult.filterMatches.length;
		}

1195 1196
		if (nlpResult) {
			counts['nlpResult'] = nlpResult.filterMatches.length;
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
		}

		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 }
			}
		*/
1217
		this.telemetryService.publicLog('settingsEditor.filter', data);
1218 1219
	}

J
Johannes Rieken 已提交
1220
	private triggerFilterPreferences(query: string): Promise<void> {
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
		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 => {
1231
					if (result && !result.exactMatch) {
1232 1233
						this.remoteSearchThrottle.trigger(() => {
							return searchInProgress && !searchInProgress.token.isCancellationRequested ?
R
Rob Lourens 已提交
1234 1235
								this.remoteSearchPreferences(query, this.searchInProgress!.token) :
								Promise.resolve();
1236 1237
						});
					}
1238
				});
1239
			} else {
R
Rob Lourens 已提交
1240
				return Promise.resolve();
1241 1242 1243 1244
			}
		});
	}

R
Rob Lourens 已提交
1245
	private localFilterPreferences(query: string, token?: CancellationToken): Promise<ISearchResult | null> {
1246
		const localSearchProvider = this.preferencesSearchService.getLocalSearchProvider(query);
1247
		return this.filterOrSearchPreferences(query, SearchResultIdx.Local, localSearchProvider, token);
R
Rob Lourens 已提交
1248 1249
	}

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

R
Rob Lourens 已提交
1254
		return Promise.all([
1255 1256
			this.filterOrSearchPreferences(query, SearchResultIdx.Remote, remoteSearchProvider, token),
			this.filterOrSearchPreferences(query, SearchResultIdx.NewExtensions, newExtSearchProvider, token)
R
Rob Lourens 已提交
1257
		]).then(() => { });
R
Rob Lourens 已提交
1258 1259
	}

R
Rob Lourens 已提交
1260
	private filterOrSearchPreferences(query: string, type: SearchResultIdx, searchProvider?: ISearchProvider, token?: CancellationToken): Promise<ISearchResult | null> {
1261 1262 1263 1264 1265
		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;
			}
1266

1267 1268 1269 1270
			if (!this.searchResultModel) {
				this.searchResultModel = this.instantiationService.createInstance(SearchResultModel, this.viewState);
				this.searchResultModel.setResult(type, result);
				this.tocTreeModel.currentSearchModel = this.searchResultModel;
1271
				this.onSearchModeToggled();
1272 1273
			} else {
				this.searchResultModel.setResult(type, result);
1274
				this.tocTreeModel.update();
1275
			}
R
Rob Lourens 已提交
1276

1277
			this.tocTree.setFocus([]);
R
Rob Lourens 已提交
1278
			this.viewState.filterToCategory = undefined;
R
Rob Lourens 已提交
1279
			this.tocTree.expandAll();
1280

1281
			this.refreshTOCTree();
1282
			this.renderTree(undefined, true);
U
Ubuntu 已提交
1283
			return result;
R
Rob Lourens 已提交
1284 1285 1286
		});
	}

1287
	private renderResultCountMessages() {
1288
		if (!this.currentSettingsModel) {
1289 1290 1291
			return;
		}

R
Rob Lourens 已提交
1292 1293 1294 1295
		this.clearFilterLinkContainer.style.display = this.viewState.tagFilters && this.viewState.tagFilters.size > 0
			? 'initial'
			: 'none';

1296
		if (!this.searchResultModel) {
1297 1298 1299 1300 1301
			if (this.countElement.style.display !== 'none') {
				this.countElement.style.display = 'none';
				this.layout(this.dimension);
			}

R
Rob Lourens 已提交
1302 1303
			DOM.removeClass(this.rootElement, 'no-results');
			return;
1304 1305
		}

1306 1307 1308 1309 1310 1311 1312
		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);
			}
1313

1314 1315 1316 1317
			if (this.countElement.style.display !== 'block') {
				this.countElement.style.display = 'block';
				this.layout(this.dimension);
			}
R
Rob Lourens 已提交
1318
			DOM.toggleClass(this.rootElement, 'no-results', count === 0);
1319
		}
1320 1321
	}

R
Rob Lourens 已提交
1322
	private _filterOrSearchPreferencesModel(filter: string, model: ISettingsEditorModel, provider?: ISearchProvider, token?: CancellationToken): Promise<ISearchResult | null> {
R
Rob Lourens 已提交
1323
		const searchP = provider ? provider.searchModel(model, token) : Promise.resolve(null);
R
Rob Lourens 已提交
1324
		return searchP
M
Matt Bierner 已提交
1325
			.then<ISearchResult, ISearchResult | null>(undefined, err => {
R
Rob Lourens 已提交
1326
				if (isPromiseCanceledError(err)) {
R
Rob Lourens 已提交
1327
					return Promise.reject(err);
R
Rob Lourens 已提交
1328 1329
				} else {
					/* __GDPR__
1330
						"settingsEditor.searchError" : {
R
Rob Lourens 已提交
1331
							"message": { "classification": "CallstackOrException", "purpose": "FeatureInsight" }
R
Rob Lourens 已提交
1332 1333 1334 1335 1336
						}
					*/
					const message = getErrorMessage(err).trim();
					if (message && message !== 'Error') {
						// "Error" = any generic network error
R
Rob Lourens 已提交
1337
						this.telemetryService.publicLog('settingsEditor.searchError', { message });
R
Rob Lourens 已提交
1338 1339
						this.logService.info('Setting search error: ' + message);
					}
M
Matt Bierner 已提交
1340
					return null;
R
Rob Lourens 已提交
1341 1342 1343 1344
				}
			});
	}

1345
	private layoutTrees(dimension: DOM.Dimension): void {
1346
		const listHeight = dimension.height - (76 + 11 /* header height + padding*/);
1347 1348
		const settingsTreeHeight = listHeight - 14;
		this.settingsTreeContainer.style.height = `${settingsTreeHeight}px`;
1349
		this.settingsTree.layout(settingsTreeHeight, dimension.width);
1350

1351 1352
		const tocTreeHeight = listHeight - 16;
		this.tocTreeContainer.style.height = `${tocTreeHeight}px`;
R
Rob Lourens 已提交
1353
		this.tocTree.layout(tocTreeHeight);
1354
	}
1355

B
Benjamin Pasero 已提交
1356
	protected saveState(): void {
1357 1358 1359
		if (this.isVisible()) {
			const searchQuery = this.searchWidget.getValue().trim();
			const target = this.settingsTargetsWidget.settingsTarget as SettingsTarget;
R
Rob Lourens 已提交
1360 1361 1362
			if (this.group && this.input) {
				this.editorMemento.saveEditorState(this.group, this.input, { searchQuery, target });
			}
1363
		}
B
Benjamin Pasero 已提交
1364 1365

		super.saveState();
1366
	}
R
Rob Lourens 已提交
1367
}
1368

1369 1370 1371 1372
interface ISettingsEditor2State {
	searchQuery: string;
	target: SettingsTarget;
}