preferencesSearch.ts 15.5 KB
Newer Older
R
Rob Lourens 已提交
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import { TPromise } from 'vs/base/common/winjs.base';
7
import * as errors from 'vs/base/common/errors';
8
import Event, { Emitter } from 'vs/base/common/event';
9
import { ISettingsEditorModel, IFilterResult, ISetting, ISettingsGroup, IWorkbenchSettingsConfiguration, IFilterMetadata, IPreferencesSearchService } from 'vs/workbench/parts/preferences/common/preferences';
R
Rob Lourens 已提交
10 11 12 13 14 15 16
import { IRange, Range } from 'vs/editor/common/core/range';
import { distinct } from 'vs/base/common/arrays';
import * as strings from 'vs/base/common/strings';
import { IJSONSchema } from 'vs/base/common/jsonSchema';
import { Registry } from 'vs/platform/registry/common/platform';
import { IConfigurationRegistry, Extensions } from 'vs/platform/configuration/common/configurationRegistry';
import { IMatch, or, matchesContiguousSubString, matchesPrefix, matchesCamelCase, matchesWords } from 'vs/base/common/filters';
17
import { IWorkspaceConfigurationService } from 'vs/workbench/services/configuration/common/configuration';
R
Rob Lourens 已提交
18
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
19 20 21 22
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IRequestService } from 'vs/platform/request/node/request';
import { asJson } from 'vs/base/node/request';
import { Disposable } from 'vs/base/common/lifecycle';
23
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
R
Rob Lourens 已提交
24

25 26
export interface IEndpointDetails {
	urlBase: string;
27
	key?: string;
28 29
}

30 31 32
export class PreferencesSearchService extends Disposable implements IPreferencesSearchService {
	_serviceBrand: any;

33 34
	private _onRemoteSearchEnablementChanged = new Emitter<boolean>();
	public onRemoteSearchEnablementChanged: Event<boolean> = this._onRemoteSearchEnablementChanged.event;
R
Rob Lourens 已提交
35

R
Rob Lourens 已提交
36 37
	constructor(
		@IWorkspaceConfigurationService private configurationService: IWorkspaceConfigurationService,
38 39
		@IEnvironmentService private environmentService: IEnvironmentService,
		@IInstantiationService private instantiationService: IInstantiationService
R
Rob Lourens 已提交
40
	) {
41 42
		super();
		this._register(configurationService.onDidChangeConfiguration(() => this._onRemoteSearchEnablementChanged.fire(this.remoteSearchAllowed)));
R
Rob Lourens 已提交
43 44
	}

45
	get remoteSearchAllowed(): boolean {
R
Rob Lourens 已提交
46 47 48 49
		if (this.environmentService.appQuality === 'stable') {
			return false;
		}

50 51 52 53 54 55
		const workbenchSettings = this.configurationService.getValue<IWorkbenchSettingsConfiguration>().workbench.settings;
		if (!workbenchSettings.enableNaturalLanguageSearch) {
			return false;
		}

		return !!this.endpoint.urlBase;
56 57 58
	}

	get endpoint(): IEndpointDetails {
59
		const workbenchSettings = this.configurationService.getValue<IWorkbenchSettingsConfiguration>().workbench.settings;
60
		if (workbenchSettings.naturalLanguageSearchEndpoint) {
61
			return {
62 63
				urlBase: workbenchSettings.naturalLanguageSearchEndpoint,
				key: workbenchSettings.naturalLanguageSearchKey
64 65 66 67 68 69
			};
		} else {
			return {
				urlBase: this.environmentService.settingsSearchUrl
			};
		}
R
Rob Lourens 已提交
70 71
	}

72
	startSearch(filter: string, remote: boolean): PreferencesSearchModel {
73
		return this.instantiationService.createInstance(PreferencesSearchModel, this, filter, remote);
R
Rob Lourens 已提交
74 75 76
	}
}

77
export class PreferencesSearchModel {
R
Rob Lourens 已提交
78 79 80
	private _localProvider: LocalSearchProvider;
	private _remoteProvider: RemoteSearchProvider;

81 82
	constructor(
		private provider: IPreferencesSearchService, private filter: string, remote: boolean,
83 84
		@IInstantiationService instantiationService: IInstantiationService,
		@ITelemetryService private telemetryService: ITelemetryService
85
	) {
R
Rob Lourens 已提交
86
		this._localProvider = new LocalSearchProvider(filter);
87

88
		if (remote && filter) {
89
			this._remoteProvider = instantiationService.createInstance(RemoteSearchProvider, filter, this.provider.endpoint);
90
		}
R
Rob Lourens 已提交
91 92 93
	}

	filterPreferences(preferencesModel: ISettingsEditorModel): TPromise<IFilterResult> {
94 95 96 97
		if (!this.filter) {
			return TPromise.wrap(null);
		}

98 99
		if (this._remoteProvider) {
			return this._remoteProvider.filterPreferences(preferencesModel).then(null, err => {
100 101 102 103 104 105 106 107 108
				const message = errors.getErrorMessage(err);

				/* __GDPR__
					"defaultSettings.searchError" : {
						"message": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
					}
				*/
				this.telemetryService.publicLog('defaultSettings.searchError', { message });

109 110 111
				return this._localProvider.filterPreferences(preferencesModel);
			});
		} else {
R
Rob Lourens 已提交
112
			return this._localProvider.filterPreferences(preferencesModel);
113
		}
R
Rob Lourens 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
	}
}

class LocalSearchProvider {
	private _filter: string;

	constructor(filter: string) {
		this._filter = filter;
	}

	filterPreferences(preferencesModel: ISettingsEditorModel): TPromise<IFilterResult> {
		const regex = strings.createRegExp(this._filter, false, { global: true });

		const groupFilter = (group: ISettingsGroup) => {
			return regex.test(group.title);
		};

131 132
		const settingMatcher = (setting: ISetting) => {
			return new SettingMatches(this._filter, setting, true, (filter, setting) => preferencesModel.findValueMatches(filter, setting)).matches;
R
Rob Lourens 已提交
133 134
		};

135
		return TPromise.wrap(preferencesModel.filterSettings(this._filter, groupFilter, settingMatcher));
R
Rob Lourens 已提交
136 137 138 139 140
	}
}

class RemoteSearchProvider {
	private _filter: string;
141
	private _remoteSearchP: TPromise<IFilterMetadata>;
R
Rob Lourens 已提交
142

143 144 145 146
	constructor(filter: string, endpoint: IEndpointDetails,
		@IEnvironmentService private environmentService: IEnvironmentService,
		@IRequestService private requestService: IRequestService
	) {
R
Rob Lourens 已提交
147
		this._filter = filter;
148
		this._remoteSearchP = filter ? this.getSettingsFromBing(filter, endpoint) : TPromise.wrap(null);
R
Rob Lourens 已提交
149 150 151
	}

	filterPreferences(preferencesModel: ISettingsEditorModel): TPromise<IFilterResult> {
152 153
		return this._remoteSearchP.then(remoteResult => {
			if (remoteResult) {
154 155 156 157 158 159
				let sortedNames = Object.keys(remoteResult.scoredResults).sort((a, b) => remoteResult.scoredResults[b] - remoteResult.scoredResults[a]);
				if (sortedNames.length) {
					const highScore = remoteResult.scoredResults[sortedNames[0]];
					sortedNames = sortedNames.filter(name => remoteResult.scoredResults[name] >= highScore / 2);
				}

160 161
				const settingMatcher = this.getRemoteSettingMatcher(sortedNames, preferencesModel);
				const result = preferencesModel.filterSettings(this._filter, group => null, settingMatcher, sortedNames);
162
				result.metadata = remoteResult;
163 164 165 166
				return result;
			} else {
				return null;
			}
R
Rob Lourens 已提交
167 168 169
		});
	}

170 171 172
	private getSettingsFromBing(filter: string, endpoint: IEndpointDetails): TPromise<IFilterMetadata> {
		const url = prepareUrl(filter, endpoint, this.environmentService.settingsSearchBuildId);
		const start = Date.now();
173 174 175
		const p = this.requestService.request({
			url,
			headers: {
176 177 178
				'User-Agent': 'request',
				'Content-Type': 'application/json; charset=utf-8',
				'api-key': endpoint.key
179
			},
R
Rob Lourens 已提交
180
			timeout: 5000
181
		})
182 183 184 185 186 187 188 189
			.then(context => {
				if (context.res.statusCode >= 300) {
					throw new Error(`${url} returned status code: ${context.res.statusCode}`);
				}

				return asJson(context);
			})
			.then((result: any) => {
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
				const timestamp = Date.now();
				const duration = timestamp - start;
				const suggestions = (result.value || [])
					.map(r => ({
						name: r.setting || r.Setting,
						score: r['@search.score']
					}));

				const scoredResults = Object.create(null);
				suggestions.forEach(s => {
					const name = s.name
						.replace(/^"/, '')
						.replace(/"$/, '');
					scoredResults[name] = s.score;
				});

				return <IFilterMetadata>{
					remoteUrl: url,
					duration,
					timestamp,
210 211
					scoredResults,
					context: result['@odata.context']
212
				};
R
Rob Lourens 已提交
213 214
			});

215 216
		return TPromise.as(p as any);
	}
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232

	private getRemoteSettingMatcher(names: string[], preferencesModel: ISettingsEditorModel): any {
		const resultSet = new Set();
		names.forEach(name => resultSet.add(name));

		return (setting: ISetting) => {
			if (resultSet.has(setting.key)) {
				const settingMatches = new SettingMatches(this._filter, setting, false, (filter, setting) => preferencesModel.findValueMatches(filter, setting)).matches;
				if (settingMatches.length) {
					return settingMatches;
				}
			}

			return [];
		};
	}
R
Rob Lourens 已提交
233 234
}

235
const API_VERSION = 'api-version=2016-09-01-Preview';
R
Rob Lourens 已提交
236
const QUERY_TYPE = 'querytype=full';
237
const SCORING_PROFILE = 'scoringProfile=ranking';
R
Rob Lourens 已提交
238 239 240 241 242 243 244 245

function escapeSpecialChars(query: string): string {
	return query.replace(/\./g, ' ')
		.replace(/[\\/+\-&|!"~*?:(){}\[\]\^]/g, '\\$&')
		.replace(/  /g, ' ') // collapse spaces
		.trim();
}

246
function prepareUrl(query: string, endpoint: IEndpointDetails, buildNumber: number): string {
R
Rob Lourens 已提交
247
	query = escapeSpecialChars(query);
248
	const boost = 10;
249
	const userQuery = `(${query})^${boost}`;
R
Rob Lourens 已提交
250
	const encodedQuery = encodeURIComponent(userQuery + ' || ' + query);
R
Rob Lourens 已提交
251 252 253 254

	// Appending Fuzzy after each word.
	query = query.replace(/\ +/g, '~ ') + '~';

R
Rob Lourens 已提交
255
	let url = `${endpoint.urlBase}?`;
256
	if (endpoint.key) {
R
Rob Lourens 已提交
257
		url += `search=${encodedQuery}`;
258
		url += `&${API_VERSION}&${QUERY_TYPE}&${SCORING_PROFILE}`;
R
Rob Lourens 已提交
259 260 261 262 263 264 265 266 267 268

		if (buildNumber) {
			url += `&$filter startbuildno le ${buildNumber} and endbuildno ge ${buildNumber}`;
		}
	} else {
		url += `query=${encodedQuery}`;

		if (buildNumber) {
			url += `&build=${buildNumber}`;
		}
269 270
	}

271
	return url;
R
Rob Lourens 已提交
272
}
273 274 275 276 277 278 279 280 281

class SettingMatches {

	private readonly descriptionMatchingWords: Map<string, IRange[]> = new Map<string, IRange[]>();
	private readonly keyMatchingWords: Map<string, IRange[]> = new Map<string, IRange[]>();
	private readonly valueMatchingWords: Map<string, IRange[]> = new Map<string, IRange[]>();

	public readonly matches: IRange[];

282
	constructor(searchString: string, setting: ISetting, private requireFullQueryMatch: boolean, private valuesMatcher: (filter: string, setting: ISetting) => IRange[]) {
283 284 285 286 287 288 289
		this.matches = distinct(this._findMatchesInSetting(searchString, setting), (match) => `${match.startLineNumber}_${match.startColumn}_${match.endLineNumber}_${match.endColumn}_`);
	}

	private _findMatchesInSetting(searchString: string, setting: ISetting): IRange[] {
		const result = this._doFindMatchesInSetting(searchString, setting);
		if (setting.overrides && setting.overrides.length) {
			for (const subSetting of setting.overrides) {
290
				const subSettingMatches = new SettingMatches(searchString, subSetting, this.requireFullQueryMatch, this.valuesMatcher);
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
				let words = searchString.split(' ');
				const descriptionRanges: IRange[] = this.getRangesForWords(words, this.descriptionMatchingWords, [subSettingMatches.descriptionMatchingWords, subSettingMatches.keyMatchingWords, subSettingMatches.valueMatchingWords]);
				const keyRanges: IRange[] = this.getRangesForWords(words, this.keyMatchingWords, [subSettingMatches.descriptionMatchingWords, subSettingMatches.keyMatchingWords, subSettingMatches.valueMatchingWords]);
				const subSettingKeyRanges: IRange[] = this.getRangesForWords(words, subSettingMatches.keyMatchingWords, [this.descriptionMatchingWords, this.keyMatchingWords, subSettingMatches.valueMatchingWords]);
				const subSettinValueRanges: IRange[] = this.getRangesForWords(words, subSettingMatches.valueMatchingWords, [this.descriptionMatchingWords, this.keyMatchingWords, subSettingMatches.keyMatchingWords]);
				result.push(...descriptionRanges, ...keyRanges, ...subSettingKeyRanges, ...subSettinValueRanges);
				result.push(...subSettingMatches.matches);
			}
		}
		return result;
	}

	private _doFindMatchesInSetting(searchString: string, setting: ISetting): IRange[] {
		const registry: { [qualifiedKey: string]: IJSONSchema } = Registry.as<IConfigurationRegistry>(Extensions.Configuration).getConfigurationProperties();
		const schema: IJSONSchema = registry[setting.key];

		let words = searchString.split(' ');
		const settingKeyAsWords: string = setting.key.split('.').join(' ');

		for (const word of words) {
			for (let lineIndex = 0; lineIndex < setting.description.length; lineIndex++) {
				const descriptionMatches = matchesWords(word, setting.description[lineIndex], true);
				if (descriptionMatches) {
					this.descriptionMatchingWords.set(word, descriptionMatches.map(match => this.toDescriptionRange(setting, match, lineIndex)));
				}
			}

			const keyMatches = or(matchesWords, matchesCamelCase)(word, settingKeyAsWords);
			if (keyMatches) {
				this.keyMatchingWords.set(word, keyMatches.map(match => this.toKeyRange(setting, match)));
			}

			const valueMatches = typeof setting.value === 'string' ? matchesContiguousSubString(word, setting.value) : null;
			if (valueMatches) {
				this.valueMatchingWords.set(word, valueMatches.map(match => this.toValueRange(setting, match)));
			} else if (schema && schema.enum && schema.enum.some(enumValue => typeof enumValue === 'string' && !!matchesContiguousSubString(word, enumValue))) {
				this.valueMatchingWords.set(word, []);
			}
		}

		const descriptionRanges: IRange[] = [];
		for (let lineIndex = 0; lineIndex < setting.description.length; lineIndex++) {
			const matches = or(matchesContiguousSubString)(searchString, setting.description[lineIndex] || '') || [];
			descriptionRanges.push(...matches.map(match => this.toDescriptionRange(setting, match, lineIndex)));
		}
		if (descriptionRanges.length === 0) {
			descriptionRanges.push(...this.getRangesForWords(words, this.descriptionMatchingWords, [this.keyMatchingWords, this.valueMatchingWords]));
		}

		const keyMatches = or(matchesPrefix, matchesContiguousSubString)(searchString, setting.key);
		const keyRanges: IRange[] = keyMatches ? keyMatches.map(match => this.toKeyRange(setting, match)) : this.getRangesForWords(words, this.keyMatchingWords, [this.descriptionMatchingWords, this.valueMatchingWords]);

		let valueRanges: IRange[] = [];
		if (setting.value && typeof setting.value === 'string') {
			const valueMatches = or(matchesPrefix, matchesContiguousSubString)(searchString, setting.value);
			valueRanges = valueMatches ? valueMatches.map(match => this.toValueRange(setting, match)) : this.getRangesForWords(words, this.valueMatchingWords, [this.keyMatchingWords, this.descriptionMatchingWords]);
		} else {
			valueRanges = this.valuesMatcher(searchString, setting);
		}

		return [...descriptionRanges, ...keyRanges, ...valueRanges];
	}

	private getRangesForWords(words: string[], from: Map<string, IRange[]>, others: Map<string, IRange[]>[]): IRange[] {
		const result: IRange[] = [];
		for (const word of words) {
			const ranges = from.get(word);
			if (ranges) {
				result.push(...ranges);
360
			} else if (this.requireFullQueryMatch && others.every(o => !o.has(word))) {
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
				return [];
			}
		}
		return result;
	}

	private toKeyRange(setting: ISetting, match: IMatch): IRange {
		return {
			startLineNumber: setting.keyRange.startLineNumber,
			startColumn: setting.keyRange.startColumn + match.start,
			endLineNumber: setting.keyRange.startLineNumber,
			endColumn: setting.keyRange.startColumn + match.end
		};
	}

	private toDescriptionRange(setting: ISetting, match: IMatch, lineIndex: number): IRange {
		return {
			startLineNumber: setting.descriptionRanges[lineIndex].startLineNumber,
			startColumn: setting.descriptionRanges[lineIndex].startColumn + match.start,
			endLineNumber: setting.descriptionRanges[lineIndex].endLineNumber,
			endColumn: setting.descriptionRanges[lineIndex].startColumn + match.end
		};
	}

	private toValueRange(setting: ISetting, match: IMatch): IRange {
		return {
			startLineNumber: setting.valueRange.startLineNumber,
			startColumn: setting.valueRange.startColumn + match.start + 1,
			endLineNumber: setting.valueRange.startLineNumber,
			endColumn: setting.valueRange.startColumn + match.end + 1
		};
	}
}