settingsEditor2.ts 49.4 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 } from 'vs/workbench/contrib/preferences/common/preferences';
40
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
41
import { IPreferencesService, ISearchResult, ISettingsEditorModel, ISettingsEditorOptions, SettingsEditorOptions, SettingValueType } from 'vs/workbench/services/preferences/common/preferences';
42
import { SettingsEditor2Input } from 'vs/workbench/services/preferences/common/preferencesEditorInput';
43
import { Settings2EditorModel } from 'vs/workbench/services/preferences/common/preferencesModels';
R
Rob Lourens 已提交
44

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

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

58 59
const $ = DOM.$;

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

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

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

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

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

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

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

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

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

108
	private settingsAriaExtraLabelsContainer!: HTMLElement;
109

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

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

119
	private readonly viewState: ISettingsEditorViewState;
120
	private _searchResultModel: SearchResultModel | null = null;
121

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

126
	private scheduledRefreshes: Map<string, DOM.IFocusTracker>;
127
	private lastFocusedSettingElement: string | null = null;
128

129
	/** Don't spam warnings */
130
	private hasWarnedMissingSettings = false;
131

132 133
	private editorMemento: IEditorMemento<ISettingsEditor2State>;

134
	private tocFocusedElement: SettingsTreeGroupElement | null = null;
135
	private settingsTreeScrollTop = 0;
136
	private dimension!: DOM.Dimension;
137

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

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

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

165 166
		this.scheduledRefreshes = new Map<string, DOM.IFocusTracker>();

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

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

176 177 178 179 180 181 182
	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 已提交
183 184 185 186
	private get currentSettingsModel() {
		return this.searchResultModel || this.settingsTreeModel;
	}

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

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

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

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

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

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

211
	setInput(input: SettingsEditor2Input, options: SettingsEditorOptions | undefined, token: CancellationToken): Promise<void> {
212
		this.inSettingsEditorContextKey.set(true);
213
		return super.setInput(input, options, token)
214
			.then(() => timeout(0)) // Force setInput to be async
R
Rob Lourens 已提交
215
			.then(() => {
216 217 218 219 220 221 222 223
				// 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;
						}
224
					}
R
Rob Lourens 已提交
225

226
					this._setOptions(options);
227

228 229 230
					this._register(input.onDispose(() => {
						this.searchWidget.setValue('');
					}));
231

232 233 234
					// Init TOC selection
					this.updateTreeScrollSync();
				});
R
Rob Lourens 已提交
235
			});
R
Rob Lourens 已提交
236 237
	}

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

		if (cachedState) {
			const settingsTarget = cachedState.target;
			this.settingsTargetsWidget.settingsTarget = settingsTarget;
247
			this.viewState.settingsTarget = settingsTarget;
248 249
			this.searchWidget.setValue(cachedState.searchQuery);
		}
250 251 252 253 254 255

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

		return withUndefinedAsNull(cachedState);
256 257
	}

258
	setOptions(options: SettingsEditorOptions | undefined): void {
259 260
		super.setOptions(options);

R
Rob Lourens 已提交
261 262 263
		if (options) {
			this._setOptions(options);
		}
264
	}
265

266
	private _setOptions(options: SettingsEditorOptions): void {
267 268 269 270
		if (options.query) {
			this.searchWidget.setValue(options.query);
		}

271
		const target: SettingsTarget = options.folderUri || <SettingsTarget>options.target;
R
Rob Lourens 已提交
272 273 274 275
		if (target) {
			this.settingsTargetsWidget.settingsTarget = target;
			this.viewState.settingsTarget = target;
		}
276 277
	}

278 279 280 281 282
	clearInput(): void {
		this.inSettingsEditorContextKey.set(false);
		super.clearInput();
	}

R
Rob Lourens 已提交
283
	layout(dimension: DOM.Dimension): void {
284
		this.dimension = dimension;
J
Joao Moreno 已提交
285 286 287 288 289

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

290 291
		this.layoutTrees(dimension);

292 293
		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
294 295
		this.searchWidget.layout({ height: 20, width: monacoWidth });

296 297
		DOM.toggleClass(this.rootElement, 'mid-width', dimension.width < 1000 && dimension.width >= 600);
		DOM.toggleClass(this.rootElement, 'narrow-width', dimension.width < 600);
R
Rob Lourens 已提交
298 299 300
	}

	focus(): void {
R
Rob Lourens 已提交
301
		if (this.lastFocusedSettingElement) {
R
Rob Lourens 已提交
302
			const elements = this.settingRenderers.getDOMElementsForSettingKey(this.settingsTree.getHTMLElement(), this.lastFocusedSettingElement);
R
Rob Lourens 已提交
303
			if (elements.length) {
R
Rob Lourens 已提交
304
				const control = elements[0].querySelector(AbstractSettingRenderer.CONTROL_SELECTOR);
R
Rob Lourens 已提交
305 306 307 308 309 310 311
				if (control) {
					(<HTMLElement>control).focus();
					return;
				}
			}
		}

312 313 314
		this.focusSearch();
	}

315
	focusSettings(): void {
316 317 318 319 320
		// Update ARIA global labels
		const labelElement = this.settingsAriaExtraLabelsContainer.querySelector('#settings_aria_more_actions_shortcut_label');
		if (labelElement) {
			const settingsContextMenuShortcut = this.currentSettingsContextMenuKeyBindingLabel;
			if (settingsContextMenuShortcut) {
321
				labelElement.setAttribute('aria-label', localize('settingsContextMenuAriaShortcut', "For more actions, Press {0}.", settingsContextMenuShortcut));
322 323 324
			}
		}

R
Rob Lourens 已提交
325
		const firstFocusable = this.settingsTree.getHTMLElement().querySelector(AbstractSettingRenderer.CONTROL_SELECTOR);
326 327
		if (firstFocusable) {
			(<HTMLElement>firstFocusable).focus();
328 329 330
		}
	}

331
	showContextMenu(): void {
R
Rob Lourens 已提交
332 333 334 335 336 337
		const activeElement = this.getActiveElementInSettingsTree();
		if (!activeElement) {
			return;
		}

		const settingDOMElement = this.settingRenderers.getSettingDOMElementForDOMElement(activeElement);
338 339 340 341
		if (!settingDOMElement) {
			return;
		}

R
Rob Lourens 已提交
342
		const focusedKey = this.settingRenderers.getKeyForDOMElementInSetting(settingDOMElement);
343 344 345 346 347 348
		if (!focusedKey) {
			return;
		}

		const elements = this.currentSettingsModel.getElementsByName(focusedKey);
		if (elements && elements[0]) {
R
Rob Lourens 已提交
349
			this.settingRenderers.showContextMenu(elements[0], settingDOMElement);
350 351 352
		}
	}

353
	focusSearch(filter?: string, selectAll = true): void {
354 355 356 357
		if (filter && this.searchWidget) {
			this.searchWidget.setValue(filter);
		}

358
		this.searchWidget.focus(selectAll);
R
Rob Lourens 已提交
359 360
	}

361
	clearSearchResults(): void {
362
		this.searchWidget.setValue('');
363 364
	}

365 366 367 368 369 370 371 372 373 374
	clearSearchFilters(): void {
		let query = this.searchWidget.getValue();

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

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

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

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

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

393 394 395 396
		this._register(this.searchWidget.onFocus(() => {
			this.lastFocusedSettingElement = '';
		}));

397 398 399 400
		this._register(attachSuggestEnabledInputBoxStyler(this.searchWidget, this.themeService, {
			inputBorder: settingsTextInputBorder
		}));

401 402
		this.countElement = DOM.append(searchContainer, DOM.$('.settings-count-widget'));
		this._register(attachStylerCallback(this.themeService, { badgeBackground, contrastBorder, badgeForeground }, colors => {
403 404 405
			const background = colors.badgeBackground ? colors.badgeBackground.toString() : '';
			const border = colors.contrastBorder ? colors.contrastBorder.toString() : '';
			const foreground = colors.badgeForeground ? colors.badgeForeground.toString() : '';
406 407

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

410 411
			this.countElement.style.borderWidth = border ? '1px' : '';
			this.countElement.style.borderStyle = border ? 'solid' : '';
412 413 414
			this.countElement.style.borderColor = border;
		}));

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

417
		const headerControlsContainer = DOM.append(this.headerContainer, $('.settings-header-controls'));
R
Rob Lourens 已提交
418
		const targetWidgetContainer = DOM.append(headerControlsContainer, $('.settings-target-container'));
R
Rob Lourens 已提交
419 420
		this.settingsTargetsWidget = this._register(this.instantiationService.createInstance(SettingsTargetsWidget, targetWidgetContainer, { enableRemoteSettings: true }));
		this.settingsTargetsWidget.settingsTarget = ConfigurationTarget.USER_LOCAL;
421
		this.settingsTargetsWidget.onDidTargetChange(target => this.onDidSettingsTargetChange(target));
R
Rob Lourens 已提交
422 423
	}

424 425 426
	private onDidSettingsTargetChange(target: SettingsTarget): void {
		this.viewState.settingsTarget = target;

427 428
		// TODO Instead of rebuilding the whole model, refresh and uncache the inspected setting value
		this.onConfigUpdate(undefined, true);
429 430
	}

431
	private onDidClickSetting(evt: ISettingLinkClickEvent, recursed?: boolean): void {
432
		const elements = this.currentSettingsModel.getElementsByName(evt.targetKey);
433
		if (elements && elements[0]) {
434
			let sourceTop = this.settingsTree.getRelativeTop(evt.source);
R
Rob Lourens 已提交
435 436 437 438
			if (typeof sourceTop !== 'number') {
				return;
			}

439 440
			if (sourceTop < 0) {
				// e.g. clicked a searched element, now the search has been cleared
441
				sourceTop = 0.5;
442 443
			}

444
			this.settingsTree.reveal(elements[0], sourceTop);
445

R
Rob Lourens 已提交
446
			const domElements = this.settingRenderers.getDOMElementsForSettingKey(this.settingsTree.getHTMLElement(), evt.targetKey);
447
			if (domElements && domElements[0]) {
R
Rob Lourens 已提交
448
				const control = domElements[0].querySelector(AbstractSettingRenderer.CONTROL_SELECTOR);
449 450 451 452
				if (control) {
					(<HTMLElement>control).focus();
				}
			}
453 454 455 456 457 458
		} else if (!recursed) {
			const p = this.triggerSearch('');
			p.then(() => {
				this.searchWidget.setValue('');
				this.onDidClickSetting(evt, true);
			});
459 460 461
		}
	}

462
	switchToSettingsFile(): Promise<IEditor | undefined> {
463 464 465 466
		const query = parseQuery(this.searchWidget.getValue());
		return this.openSettingsFile(query.query);
	}

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

470
		const options: ISettingsEditorOptions = { query };
R
Rob Lourens 已提交
471
		if (currentSettingsTarget === ConfigurationTarget.USER_LOCAL) {
472
			return this.preferencesService.openGlobalSettings(true, options);
R
Rob Lourens 已提交
473 474
		} else if (currentSettingsTarget === ConfigurationTarget.USER_REMOTE) {
			return this.preferencesService.openRemoteSettings();
475
		} else if (currentSettingsTarget === ConfigurationTarget.WORKSPACE) {
476
			return this.preferencesService.openWorkspaceSettings(true, options);
477
		} else if (URI.isUri(currentSettingsTarget)) {
478
			return this.preferencesService.openFolderSettings(currentSettingsTarget, true, options);
479
		}
480 481

		return undefined;
R
Rob Lourens 已提交
482 483 484 485 486
	}

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

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

489
		this.noResultsMessage.innerText = localize('noResults', "No Settings Found");
490 491 492 493 494

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

		this.clearFilterLinkContainer.textContent = ' - ';
		const clearFilterLink = DOM.append(this.clearFilterLinkContainer, $('a.pointer.prominent', { tabindex: 0 }, localize('clearSearchFilters', 'Clear Filters')));
495
		this._register(DOM.addDisposableListener(clearFilterLink, DOM.EventType.CLICK, (e: MouseEvent) => {
496 497 498 499 500 501 502 503 504 505
			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')));
506
		this._register(DOM.addDisposableListener(clearSearch, DOM.EventType.CLICK, (e: MouseEvent) => {
507 508
			DOM.EventHelper.stop(e, false);
			this.clearSearchResults();
509
			this.focusSearch();
510 511 512 513
		}));

		DOM.append(this.noResultsMessage, clearSearchContainer);

514 515 516 517
		this._register(attachStylerCallback(this.themeService, { editorForeground }, colors => {
			this.noResultsMessage.style.color = colors.editorForeground ? colors.editorForeground.toString() : null;
		}));

R
Rob Lourens 已提交
518 519
		this.createTOC(bodyContainer);

520 521 522 523 524
		this.createFocusSink(
			bodyContainer,
			e => {
				if (DOM.findParentWithClass(e.relatedTarget, 'settings-editor-tree')) {
					if (this.settingsTree.scrollTop > 0) {
525
						const firstElement = this.settingsTree.firstVisibleElement;
526 527 528 529 530 531 532 533 534 535 536 537 538
						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 已提交
539

R
Rob Lourens 已提交
540
		this.createSettingsTree(bodyContainer);
R
Rob Lourens 已提交
541

542 543 544 545 546
		this.createFocusSink(
			bodyContainer,
			e => {
				if (DOM.findParentWithClass(e.relatedTarget, 'settings-editor-tree')) {
					if (this.settingsTree.scrollTop < this.settingsTree.scrollHeight) {
547
						const lastElement = this.settingsTree.lastVisibleElement;
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
						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;
	}
571

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

576 577
		this.tocTree = this._register(this.instantiationService.createInstance(TOCTree,
			DOM.append(this.tocTreeContainer, $('.settings-toc-wrapper')),
R
Rob Lourens 已提交
578
			this.viewState));
R
Rob Lourens 已提交
579

580
		this._register(this.tocTree.onDidChangeFocus(e => {
R
Rob Lourens 已提交
581
			const element: SettingsTreeGroupElement | null = e.elements[0];
R
Rob Lourens 已提交
582 583 584
			if (this.tocFocusedElement === element) {
				return;
			}
585

R
Rob Lourens 已提交
586 587 588 589
			this.tocFocusedElement = element;
			this.tocTree.setSelection(element ? [element] : []);
			if (this.searchResultModel) {
				if (this.viewState.filterToCategory !== element) {
590
					this.viewState.filterToCategory = withNullAsUndefined(element);
591 592
					this.renderTree();
					this.settingsTree.scrollTop = 0;
R
Rob Lourens 已提交
593
				}
R
Rob Lourens 已提交
594
			} else if (element && (!e.browserEvent || !(<IFocusEventFromScroll>e.browserEvent).fromScroll)) {
R
Rob Lourens 已提交
595 596
				this.settingsTree.reveal(element, 0);
			}
597 598 599 600 601 602 603 604
		}));

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

		this._register(this.tocTree.onDidBlur(() => {
			this.tocRowFocused.set(false);
R
Rob Lourens 已提交
605 606 607 608
		}));
	}

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

611 612 613 614 615 616 617 618
		// 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 已提交
619 620 621
		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 => {
622
			this.openSettingsFile(settingKey);
623
		}));
R
Rob Lourens 已提交
624 625
		this._register(this.settingRenderers.onDidClickSettingLink(settingName => this.onDidClickSetting(settingName)));
		this._register(this.settingRenderers.onDidFocusSetting(element => {
R
Rob Lourens 已提交
626
			this.lastFocusedSettingElement = element.setting.key;
627 628
			this.settingsTree.reveal(element);
		}));
R
Rob Lourens 已提交
629
		this._register(this.settingRenderers.onDidClickOverrideElement((element: ISettingOverrideClickEvent) => {
630
			if (element.scope.toLowerCase() === 'workspace') {
J
Jeremy Shore 已提交
631
				this.settingsTargetsWidget.updateTarget(ConfigurationTarget.WORKSPACE);
632
			} else if (element.scope.toLowerCase() === 'user') {
R
Rob Lourens 已提交
633
				this.settingsTargetsWidget.updateTarget(ConfigurationTarget.USER_LOCAL);
634
			} else if (element.scope.toLowerCase() === 'remote') {
R
Rob Lourens 已提交
635
				this.settingsTargetsWidget.updateTarget(ConfigurationTarget.USER_REMOTE);
J
Jeremy Shore 已提交
636 637 638 639
			}

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

641
		this.settingsTree = this._register(this.instantiationService.createInstance(SettingsTree,
642 643
			this.settingsTreeContainer,
			this.viewState,
R
Rob Lourens 已提交
644
			this.settingRenderers.allRenderers));
R
Rob Lourens 已提交
645
		this.settingsTree.getHTMLElement().attributes.removeNamedItem('tabindex');
646

647
		this._register(this.settingsTree.onDidScroll(() => {
648 649 650 651 652 653 654 655 656 657 658
			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);
659
		}));
660 661
	}

B
Benjamin Pasero 已提交
662 663
	private notifyNoSaveNeeded() {
		if (!this.storageService.getBoolean('hasNotifiedOfSettingsAutosave', StorageScope.GLOBAL, false)) {
B
Benjamin Pasero 已提交
664
			this.storageService.store('hasNotifiedOfSettingsAutosave', true, StorageScope.GLOBAL);
665 666
			this.notificationService.info(localize('settingsNoSaveNeeded', "Your changes are automatically saved as you edit."));
		}
J
Jackson Kearl 已提交
667 668
	}

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

672 673
		if (this.pendingSettingUpdate && this.pendingSettingUpdate.key !== key) {
			this.updateChangedSetting(key, value);
674 675
		}

676
		this.pendingSettingUpdate = { key, value };
677 678 679 680 681
		if (SettingsEditor2.shouldSettingUpdateFast(type)) {
			this.settingFastUpdateDelayer.trigger(() => this.updateChangedSetting(key, value));
		} else {
			this.settingSlowUpdateDelayer.trigger(() => this.updateChangedSetting(key, value));
		}
682 683
	}

684
	private updateTreeScrollSync(): void {
R
Rob Lourens 已提交
685
		this.settingRenderers.cancelSuggesters();
686 687 688 689
		if (this.searchResultModel) {
			return;
		}

R
Rob Lourens 已提交
690
		if (!this.tocTreeModel) {
691 692
			return;
		}
693

694
		const elementToSync = this.settingsTree.firstVisibleElement;
695 696 697 698
		const element = elementToSync instanceof SettingsTreeSettingElement ? elementToSync.parent :
			elementToSync instanceof SettingsTreeGroupElement ? elementToSync :
				null;

R
Rob Lourens 已提交
699 700 701 702 703 704 705 706
		// 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;
		}

707 708 709 710 711 712
		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 已提交
713 714 715 716
			if (typeof elementTop !== 'number') {
				return;
			}

717 718 719 720 721 722 723 724 725 726
			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 已提交
727

728
			this.tocTree.setSelection([element]);
729

730
			const fakeKeyboardEvent = new KeyboardEvent('keydown');
R
Rob Lourens 已提交
731
			(<IFocusEventFromScroll>fakeKeyboardEvent).fromScroll = true;
732 733 734
			this.tocTree.setFocus([element], fakeKeyboardEvent);
		}
	}
735

736 737 738 739 740 741 742 743 744 745
	private getAncestors(element: SettingsTreeElement): SettingsTreeElement[] {
		const ancestors: any[] = [];

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

			element = element.parent;
		}
746

747
		return ancestors.reverse();
748 749
	}

J
Johannes Rieken 已提交
750
	private updateChangedSetting(key: string, value: any): Promise<void> {
751 752
		// 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 已提交
753 754
		const settingsTarget = this.settingsTargetsWidget.settingsTarget;
		const resource = URI.isUri(settingsTarget) ? settingsTarget : undefined;
755
		const configurationTarget = <ConfigurationTarget>(resource ? ConfigurationTarget.WORKSPACE_FOLDER : settingsTarget);
R
Rob Lourens 已提交
756 757
		const overrides: IConfigurationOverrides = { resource };

758 759
		const isManualReset = value === undefined;

R
Rob Lourens 已提交
760 761 762 763 764 765 766
		// 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)
767
			.then(() => {
768
				this.renderTree(key, isManualReset);
769 770 771 772 773
				const reportModifiedProps = {
					key,
					query: this.searchWidget.getValue(),
					searchResults: this.searchResultModel && this.searchResultModel.getUniqueResults(),
					rawResults: this.searchResultModel && this.searchResultModel.getRawResults(),
774
					showConfiguredOnly: !!this.viewState.tagFilters && this.viewState.tagFilters.has(MODIFIED_SETTING_TAG),
775 776 777 778 779 780
					isReset: typeof value === 'undefined',
					settingsTarget: this.settingsTargetsWidget.settingsTarget as SettingsTarget
				};

				return this.reportModifiedSetting(reportModifiedProps);
			});
781 782
	}

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

R
Rob Lourens 已提交
786 787 788
		let groupId: string | undefined = undefined;
		let nlpIndex: number | undefined = undefined;
		let displayIndex: number | undefined = undefined;
789
		if (props.searchResults) {
R
Rob Lourens 已提交
790 791 792 793
			const remoteResult = props.searchResults[SearchResultIdx.Remote];
			const localResult = props.searchResults[SearchResultIdx.Local];

			const localIndex = arrays.firstIndex(localResult!.filterMatches, m => m.setting.key === props.key);
794 795 796 797 798 799 800 801
			groupId = localIndex >= 0 ?
				'local' :
				'remote';

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

802 803 804 805 806 807
			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;
				}
808 809 810
			}
		}

R
Rob Lourens 已提交
811 812 813 814
		const reportedTarget = props.settingsTarget === ConfigurationTarget.USER_LOCAL ? 'user' :
			props.settingsTarget === ConfigurationTarget.USER_REMOTE ? 'user_remote' :
				props.settingsTarget === ConfigurationTarget.WORKSPACE ? 'workspace' :
					'folder';
815 816 817 818 819 820 821 822 823 824 825 826 827

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

		/* __GDPR__
828
			"settingsEditor.settingModified" : {
829 830 831 832 833 834 835 836 837 838
				"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" }
			}
		*/
839
		this.telemetryService.publicLog('settingsEditor.settingModified', data);
R
Rob Lourens 已提交
840 841
	}

J
Johannes Rieken 已提交
842
	private render(token: CancellationToken): Promise<any> {
R
Rob Lourens 已提交
843 844
		if (this.input) {
			return this.input.resolve()
845
				.then((model: Settings2EditorModel) => {
846
					if (token.isCancellationRequested) {
R
Rob Lourens 已提交
847
						return undefined;
848 849
					}

850 851 852
					this._register(model.onDidChangeGroups(() => {
						this.onConfigUpdate(undefined, undefined, true);
					}));
853
					this.defaultSettingsEditorModel = model;
854
					return this.onConfigUpdate(undefined, true);
855
				});
R
Rob Lourens 已提交
856
		}
R
Rob Lourens 已提交
857
		return Promise.resolve(null);
R
Rob Lourens 已提交
858 859
	}

860
	private onSearchModeToggled(): void {
861
		DOM.removeClass(this.rootElement, 'no-toc-search');
862
		if (this.configurationService.getValue('workbench.settings.settingsSearchTocBehavior') === 'hide') {
863
			DOM.toggleClass(this.rootElement, 'no-toc-search', !!this.searchResultModel);
864
		}
865 866
	}

867 868
	private scheduleRefresh(element: HTMLElement, key = ''): void {
		if (key && this.scheduledRefreshes.has(key)) {
869 870 871
			return;
		}

872 873 874 875 876 877 878 879 880 881 882
		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]);
883 884 885
		});
	}

886
	private async onConfigUpdate(keys?: string[], forceRefresh = false, schemaChange = false): Promise<void> {
887
		if (keys && this.settingsTreeModel) {
888 889 890
			return this.updateElementsByKey(keys);
		}

891
		const groups = this.defaultSettingsEditorModel.settingsGroups.slice(1); // Without commonlyUsed
892
		const dividedGroups = collections.groupBy(groups, g => g.contributedByExtension ? 'extension' : 'core');
893 894 895 896 897
		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 已提交
898
			const settingKeyList: string[] = [];
899 900 901 902 903 904 905 906
			settingsResult.leftoverSettings.forEach(s => {
				settingKeyList.push(s.key);
			});

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

907
		const commonlyUsed = resolveSettingsTree(commonlyUsedData, dividedGroups.core);
R
Rob Lourens 已提交
908
		resolvedSettingsRoot.children!.unshift(commonlyUsed.tree);
909

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

912 913 914 915
		if (this.searchResultModel) {
			this.searchResultModel.updateChildren();
		}

916 917
		if (this.settingsTreeModel) {
			this.settingsTreeModel.update(resolvedSettingsRoot);
918

919 920 921
			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();
922
			}
923 924 925

			this.renderTree(undefined, forceRefresh);
			this.refreshTOCTree();
926
		} else {
927 928
			this.settingsTreeModel = this.instantiationService.createInstance(SettingsTreeModel, this.viewState);
			this.settingsTreeModel.update(resolvedSettingsRoot);
929
			this.tocTreeModel.settingsTreeRoot = this.settingsTreeModel.root as SettingsTreeGroupElement;
930

931 932 933 934 935 936 937 938
			const cachedState = this.restoreCachedState();
			if (cachedState && cachedState.searchQuery) {
				await this.onSearchInputChanged();
			} else {
				this.refreshTOCTree();
				this.refreshTree();
				this.tocTree.collapseAll();
			}
939 940 941
		}
	}

U
Ubuntu 已提交
942
	private updateElementsByKey(keys: string[]): void {
943 944
		if (keys.length) {
			if (this.searchResultModel) {
R
Rob Lourens 已提交
945
				keys.forEach(key => this.searchResultModel!.updateElementsByName(key));
946 947 948 949 950 951
			}

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

U
Ubuntu 已提交
952
			keys.forEach(key => this.renderTree(key));
953 954 955 956 957
		} else {
			return this.renderTree();
		}
	}

958 959 960 961 962 963
	private getActiveElementInSettingsTree(): HTMLElement | null {
		return (document.activeElement && DOM.isAncestor(document.activeElement, this.settingsTree.getHTMLElement())) ?
			<HTMLElement>document.activeElement :
			null;
	}

U
Ubuntu 已提交
964
	private renderTree(key?: string, force = false): void {
965
		if (!force && key && this.scheduledRefreshes.has(key)) {
966
			this.updateModifiedLabelForKey(key);
U
Ubuntu 已提交
967
			return;
968 969
		}

970 971
		// If the context view is focused, delay rendering settings
		if (this.contextViewFocused()) {
M
Matt Bierner 已提交
972 973 974 975
			const element = document.querySelector('.context-view');
			if (element) {
				this.scheduleRefresh(element as HTMLElement, key);
			}
U
Ubuntu 已提交
976
			return;
977 978
		}

979
		// If a setting control is currently focused, schedule a refresh for later
R
Rob Lourens 已提交
980 981
		const activeElement = this.getActiveElementInSettingsTree();
		const focusedSetting = activeElement && this.settingRenderers.getSettingDOMElementForDOMElement(activeElement);
982
		if (focusedSetting && !force) {
983 984
			// 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 已提交
985
				const focusedKey = focusedSetting.getAttribute(AbstractSettingRenderer.SETTING_KEY_ATTR);
P
Pine Wu 已提交
986
				if (focusedKey === key &&
P
Pine Wu 已提交
987 988 989
					// 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'))
				) {
990

991
					this.updateModifiedLabelForKey(key);
992
					this.scheduleRefresh(focusedSetting, key);
U
Ubuntu 已提交
993
					return;
994 995
				}
			} else {
996
				this.scheduleRefresh(focusedSetting);
U
Ubuntu 已提交
997
				return;
998
			}
999
		}
R
Rob Lourens 已提交
1000

R
Rob Lourens 已提交
1001 1002
		this.renderResultCountMessages();

1003
		if (key) {
1004
			const elements = this.currentSettingsModel.getElementsByName(key);
1005
			if (elements && elements.length) {
1006
				// TODO https://github.com/Microsoft/vscode/issues/57360
R
Rob Lourens 已提交
1007
				this.refreshTree();
1008 1009
			} else {
				// Refresh requested for a key that we don't know about
U
Ubuntu 已提交
1010
				return;
1011
			}
1012
		} else {
R
Rob Lourens 已提交
1013
			this.refreshTree();
1014 1015
		}

U
Ubuntu 已提交
1016
		return;
R
Rob Lourens 已提交
1017 1018
	}

1019 1020 1021 1022
	private contextViewFocused(): boolean {
		return !!DOM.findParentWithClass(<HTMLElement>document.activeElement, 'context-view');
	}

R
Rob Lourens 已提交
1023
	private refreshTree(): void {
1024 1025 1026
		if (this.isVisible()) {
			this.settingsTree.setChildren(null, createGroupIterator(this.currentSettingsModel.root));
		}
1027 1028
	}

R
Rob Lourens 已提交
1029
	private refreshTOCTree(): void {
1030
		if (this.isVisible()) {
R
Rob Lourens 已提交
1031
			this.tocTreeModel.update();
1032 1033
			this.tocTree.setChildren(null, createTOCIterator(this.tocTreeModel, this.tocTree));
		}
R
Rob Lourens 已提交
1034 1035
	}

1036
	private updateModifiedLabelForKey(key: string): void {
1037
		const dataElements = this.currentSettingsModel.getElementsByName(key);
1038
		const isModified = dataElements && dataElements[0] && dataElements[0].isConfigured; // all elements are either configured or not
R
Rob Lourens 已提交
1039
		const elements = this.settingRenderers.getDOMElementsForSettingKey(this.settingsTree.getHTMLElement(), key);
1040
		if (elements && elements[0]) {
R
Rob Lourens 已提交
1041
			DOM.toggleClass(elements[0], 'is-configured', !!isModified);
1042 1043 1044
		}
	}

1045
	private async onSearchInputChanged(): Promise<void> {
R
Rob Lourens 已提交
1046 1047
		const query = this.searchWidget.getValue().trim();
		this.delayedFilterLogging.cancel();
1048 1049 1050 1051 1052
		await this.triggerSearch(query.replace(/›/g, ' '));

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

R
Rob Lourens 已提交
1055
	private parseSettingFromJSON(query: string): string | null {
1056 1057 1058 1059
		const match = query.match(/"([a-zA-Z.]+)": /);
		return match && match[1];
	}

J
Johannes Rieken 已提交
1060
	private triggerSearch(query: string): Promise<void> {
1061
		this.viewState.tagFilters = new Set<string>();
P
Peng Lyu 已提交
1062
		this.viewState.extensionFilters = new Set<string>();
1063
		if (query) {
1064
			const parsedQuery = parseQuery(query);
R
Rob Lourens 已提交
1065
			query = parsedQuery.query;
R
Rob Lourens 已提交
1066
			parsedQuery.tags.forEach(tag => this.viewState.tagFilters!.add(tag));
P
Peng Lyu 已提交
1067
			parsedQuery.extensionFilters.forEach(extensionId => this.viewState.extensionFilters!.add(extensionId));
1068
		}
1069 1070

		if (query && query !== '@') {
1071
			query = this.parseSettingFromJSON(query) || query;
1072
			return this.triggerFilterPreferences(query);
R
Rob Lourens 已提交
1073
		} else {
P
Peng Lyu 已提交
1074
			if ((this.viewState.tagFilters && this.viewState.tagFilters.size) || (this.viewState.extensionFilters && this.viewState.extensionFilters.size)) {
1075 1076 1077 1078 1079
				this.searchResultModel = this.createFilterModel();
			} else {
				this.searchResultModel = null;
			}

R
Rob Lourens 已提交
1080 1081
			this.localSearchDelayer.cancel();
			this.remoteSearchThrottle.cancel();
1082 1083 1084 1085
			if (this.searchInProgress) {
				this.searchInProgress.cancel();
				this.searchInProgress.dispose();
				this.searchInProgress = null;
R
Rob Lourens 已提交
1086
			}
R
Rob Lourens 已提交
1087

1088
			this.tocTree.setFocus([]);
R
Rob Lourens 已提交
1089
			this.viewState.filterToCategory = undefined;
1090
			this.tocTreeModel.currentSearchModel = this.searchResultModel;
1091
			this.onSearchModeToggled();
1092 1093

			if (this.searchResultModel) {
1094 1095
				// Added a filter model
				this.tocTree.setSelection([]);
R
Rob Lourens 已提交
1096
				this.tocTree.expandAll();
R
Rob Lourens 已提交
1097
				this.renderResultCountMessages();
R
Rob Lourens 已提交
1098
				this.refreshTree();
1099
			} else {
1100
				// Leaving search mode
R
Rob Lourens 已提交
1101
				this.tocTree.collapseAll();
R
Rob Lourens 已提交
1102
				this.renderResultCountMessages();
R
Rob Lourens 已提交
1103
				this.refreshTree();
1104
			}
1105 1106

			this.refreshTOCTree();
R
Rob Lourens 已提交
1107
		}
R
Rob Lourens 已提交
1108

R
Rob Lourens 已提交
1109
		return Promise.resolve();
R
Rob Lourens 已提交
1110 1111
	}

1112 1113 1114 1115 1116 1117 1118 1119 1120
	/**
	 * 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 已提交
1121 1122 1123
		for (const g of this.defaultSettingsEditorModel.settingsGroups.slice(1)) {
			for (const sect of g.sections) {
				for (const setting of sect.settings) {
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
					fullResult.filterMatches.push({ setting, matches: [], score: 0 });
				}
			}
		}

		filterModel.setResult(0, fullResult);

		return filterModel;
	}

1134 1135 1136 1137
	private reportFilteringUsed(query: string, results: ISearchResult[]): void {
		const nlpResult = results[SearchResultIdx.Remote];
		const nlpMetadata = nlpResult && nlpResult.metadata;

1138 1139 1140
		const durations = {
			nlpResult: nlpMetadata && nlpMetadata.duration
		};
1141 1142

		// Count unique results
1143
		const counts: { nlpResult?: number, filterResult?: number } = {};
1144
		const filterResult = results[SearchResultIdx.Local];
1145 1146 1147 1148
		if (filterResult) {
			counts['filterResult'] = filterResult.filterMatches.length;
		}

1149 1150
		if (nlpResult) {
			counts['nlpResult'] = nlpResult.filterMatches.length;
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
		}

		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 }
			}
		*/
1171
		this.telemetryService.publicLog('settingsEditor.filter', data);
1172 1173
	}

J
Johannes Rieken 已提交
1174
	private triggerFilterPreferences(query: string): Promise<void> {
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
		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 => {
1185
					if (result && !result.exactMatch) {
1186 1187
						this.remoteSearchThrottle.trigger(() => {
							return searchInProgress && !searchInProgress.token.isCancellationRequested ?
R
Rob Lourens 已提交
1188 1189
								this.remoteSearchPreferences(query, this.searchInProgress!.token) :
								Promise.resolve();
1190 1191
						});
					}
1192
				});
1193
			} else {
R
Rob Lourens 已提交
1194
				return Promise.resolve();
1195 1196 1197 1198
			}
		});
	}

R
Rob Lourens 已提交
1199
	private localFilterPreferences(query: string, token?: CancellationToken): Promise<ISearchResult | null> {
1200
		const localSearchProvider = this.preferencesSearchService.getLocalSearchProvider(query);
1201
		return this.filterOrSearchPreferences(query, SearchResultIdx.Local, localSearchProvider, token);
R
Rob Lourens 已提交
1202 1203
	}

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

R
Rob Lourens 已提交
1208
		return Promise.all([
1209 1210
			this.filterOrSearchPreferences(query, SearchResultIdx.Remote, remoteSearchProvider, token),
			this.filterOrSearchPreferences(query, SearchResultIdx.NewExtensions, newExtSearchProvider, token)
R
Rob Lourens 已提交
1211
		]).then(() => { });
R
Rob Lourens 已提交
1212 1213
	}

R
Rob Lourens 已提交
1214
	private filterOrSearchPreferences(query: string, type: SearchResultIdx, searchProvider?: ISearchProvider, token?: CancellationToken): Promise<ISearchResult | null> {
1215 1216 1217 1218 1219
		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;
			}
1220

1221 1222 1223 1224
			if (!this.searchResultModel) {
				this.searchResultModel = this.instantiationService.createInstance(SearchResultModel, this.viewState);
				this.searchResultModel.setResult(type, result);
				this.tocTreeModel.currentSearchModel = this.searchResultModel;
1225
				this.onSearchModeToggled();
1226 1227
			} else {
				this.searchResultModel.setResult(type, result);
1228
				this.tocTreeModel.update();
1229
			}
R
Rob Lourens 已提交
1230

1231
			this.tocTree.setFocus([]);
R
Rob Lourens 已提交
1232
			this.viewState.filterToCategory = undefined;
R
Rob Lourens 已提交
1233
			this.tocTree.expandAll();
1234

U
Ubuntu 已提交
1235
			this.renderTree(undefined, true);
1236
			this.refreshTOCTree();
U
Ubuntu 已提交
1237
			return result;
R
Rob Lourens 已提交
1238 1239 1240
		});
	}

1241
	private renderResultCountMessages() {
1242
		if (!this.currentSettingsModel) {
1243 1244 1245
			return;
		}

R
Rob Lourens 已提交
1246 1247 1248 1249
		this.clearFilterLinkContainer.style.display = this.viewState.tagFilters && this.viewState.tagFilters.size > 0
			? 'initial'
			: 'none';

1250
		if (!this.searchResultModel) {
1251 1252 1253 1254 1255
			if (this.countElement.style.display !== 'none') {
				this.countElement.style.display = 'none';
				this.layout(this.dimension);
			}

R
Rob Lourens 已提交
1256 1257
			DOM.removeClass(this.rootElement, 'no-results');
			return;
1258 1259
		}

1260 1261 1262 1263 1264 1265 1266
		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);
			}
1267

1268 1269 1270 1271
			if (this.countElement.style.display !== 'block') {
				this.countElement.style.display = 'block';
				this.layout(this.dimension);
			}
R
Rob Lourens 已提交
1272
			DOM.toggleClass(this.rootElement, 'no-results', count === 0);
1273
		}
1274 1275
	}

R
Rob Lourens 已提交
1276
	private _filterOrSearchPreferencesModel(filter: string, model: ISettingsEditorModel, provider?: ISearchProvider, token?: CancellationToken): Promise<ISearchResult | null> {
R
Rob Lourens 已提交
1277
		const searchP = provider ? provider.searchModel(model, token) : Promise.resolve(null);
R
Rob Lourens 已提交
1278 1279 1280
		return searchP
			.then<ISearchResult>(null, err => {
				if (isPromiseCanceledError(err)) {
R
Rob Lourens 已提交
1281
					return Promise.reject(err);
R
Rob Lourens 已提交
1282 1283
				} else {
					/* __GDPR__
1284
						"settingsEditor.searchError" : {
R
Rob Lourens 已提交
1285 1286 1287 1288 1289 1290 1291
							"message": { "classification": "CallstackOrException", "purpose": "FeatureInsight" },
							"filter": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
						}
					*/
					const message = getErrorMessage(err).trim();
					if (message && message !== 'Error') {
						// "Error" = any generic network error
1292
						this.telemetryService.publicLog('settingsEditor.searchError', { message, filter });
R
Rob Lourens 已提交
1293 1294
						this.logService.info('Setting search error: ' + message);
					}
R
Rob Lourens 已提交
1295
					return Promise.resolve(null);
R
Rob Lourens 已提交
1296 1297 1298 1299
				}
			});
	}

1300
	private layoutTrees(dimension: DOM.Dimension): void {
1301
		const listHeight = dimension.height - (76 + 11 /* header height + padding*/);
1302 1303
		const settingsTreeHeight = listHeight - 14;
		this.settingsTreeContainer.style.height = `${settingsTreeHeight}px`;
1304
		this.settingsTree.layout(settingsTreeHeight, dimension.width);
1305

1306 1307
		const tocTreeHeight = listHeight - 16;
		this.tocTreeContainer.style.height = `${tocTreeHeight}px`;
R
Rob Lourens 已提交
1308
		this.tocTree.layout(tocTreeHeight);
1309
	}
1310

B
Benjamin Pasero 已提交
1311
	protected saveState(): void {
1312 1313 1314
		if (this.isVisible()) {
			const searchQuery = this.searchWidget.getValue().trim();
			const target = this.settingsTargetsWidget.settingsTarget as SettingsTarget;
R
Rob Lourens 已提交
1315 1316 1317
			if (this.group && this.input) {
				this.editorMemento.saveEditorState(this.group, this.input, { searchQuery, target });
			}
1318
		}
B
Benjamin Pasero 已提交
1319 1320

		super.saveState();
1321
	}
R
Rob Lourens 已提交
1322
}
1323

1324 1325 1326 1327
interface ISettingsEditor2State {
	searchQuery: string;
	target: SettingsTarget;
}