openAnythingHandler.ts 12.0 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8 9 10 11 12
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

import {Promise, TPromise} from 'vs/base/common/winjs.base';
import nls = require('vs/nls');
import {ThrottledDelayer} from 'vs/base/common/async';
import types = require('vs/base/common/types');
import strings = require('vs/base/common/strings');
13
import scorer = require('vs/base/common/scorer');
14
import paths = require('vs/base/common/paths');
E
Erich Gamma 已提交
15
import filters = require('vs/base/common/filters');
16
import labels = require('vs/base/common/labels');
E
Erich Gamma 已提交
17
import {IRange} from 'vs/editor/common/editorCommon';
18
import {ListenerUnbind} from 'vs/base/common/eventEmitter';
E
Erich Gamma 已提交
19 20 21 22 23 24 25
import {IAutoFocus} from 'vs/base/parts/quickopen/browser/quickOpen';
import {QuickOpenEntry, QuickOpenModel} from 'vs/base/parts/quickopen/browser/quickOpenModel';
import {QuickOpenHandler} from 'vs/workbench/browser/quickopen';
import {FileEntry, OpenFileHandler} from 'vs/workbench/parts/search/browser/openFileHandler';
import {OpenSymbolHandler as _OpenSymbolHandler} from 'vs/workbench/parts/search/browser/openSymbolHandler';
import {IMessageService, Severity} from 'vs/platform/message/common/message';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
26 27 28
import {IWorkspaceContextService} from 'vs/workbench/services/workspace/common/contextService';
import {ISearchConfiguration} from 'vs/platform/search/common/search';
import {IConfigurationService, IConfigurationServiceEvent, ConfigurationServiceEventTypes} from 'vs/platform/configuration/common/configuration';
E
Erich Gamma 已提交
29 30 31 32 33 34 35 36 37

// OpenSymbolHandler is used from an extension and must be in the main bundle file so it can load
export const OpenSymbolHandler = _OpenSymbolHandler

export class OpenAnythingHandler extends QuickOpenHandler {
	private static LINE_COLON_PATTERN = /[#|:](\d*)([#|:](\d*))?$/;

	private static SYMBOL_SEARCH_INITIAL_TIMEOUT = 500; // Ignore symbol search after a timeout to not block search results
	private static SYMBOL_SEARCH_SUBSEQUENT_TIMEOUT = 100;
38
	private static SEARCH_DELAY = 300; // This delay accommodates for the user typing a word and then stops typing to start searching
E
Erich Gamma 已提交
39

40
	private static MAX_DISPLAYED_RESULTS = 2048;
41

E
Erich Gamma 已提交
42 43 44
	private openSymbolHandler: _OpenSymbolHandler;
	private openFileHandler: OpenFileHandler;
	private resultsToSearchCache: { [searchValue: string]: QuickOpenEntry[]; };
J
Joao Moreno 已提交
45
	private delayer: ThrottledDelayer<QuickOpenModel>;
46
	private pendingSearch: TPromise<QuickOpenModel>;
E
Erich Gamma 已提交
47
	private isClosed: boolean;
48 49
	private fuzzyMatchingEnabled: boolean;
	private configurationListenerUnbind: ListenerUnbind;
E
Erich Gamma 已提交
50 51 52

	constructor(
		@IMessageService private messageService: IMessageService,
53
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
54
		@IInstantiationService instantiationService: IInstantiationService,
55
		@IConfigurationService private configurationService: IConfigurationService
E
Erich Gamma 已提交
56 57 58 59 60 61 62 63 64 65
	) {
		super();

		// Instantiate delegate handlers
		this.openSymbolHandler = instantiationService.createInstance(_OpenSymbolHandler);
		this.openFileHandler = instantiationService.createInstance(OpenFileHandler);

		this.openSymbolHandler.setStandalone(false);
		this.openFileHandler.setStandalone(false);

66
		this.resultsToSearchCache = Object.create(null);
J
Joao Moreno 已提交
67
		this.delayer = new ThrottledDelayer<QuickOpenModel>(OpenAnythingHandler.SEARCH_DELAY);
68 69 70 71 72 73 74 75 76 77 78 79 80

		this.updateFuzzyMatching(contextService.getOptions().globalSettings.settings);

		this.registerListeners();
	}

	private registerListeners(): void {
		this.configurationListenerUnbind = this.configurationService.addListener(ConfigurationServiceEventTypes.UPDATED, (e: IConfigurationServiceEvent) => this.updateFuzzyMatching(e.config));
	}

	private updateFuzzyMatching(configuration: ISearchConfiguration): void {
		this.fuzzyMatchingEnabled = configuration.search && configuration.search.fuzzyFilePicker;
		this.openFileHandler.setFuzzyMatchingEnabled(this.fuzzyMatchingEnabled);
E
Erich Gamma 已提交
81 82 83 84 85
	}

	public getResults(searchValue: string): TPromise<QuickOpenModel> {
		searchValue = searchValue.trim();

86 87 88
		// Cancel any pending search
		this.cancelPendingSearch();

E
Erich Gamma 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
		// Treat this call as the handler being in use
		this.isClosed = false;

		// Respond directly to empty search
		if (!searchValue) {
			return TPromise.as(new QuickOpenModel());
		}

		// Find a suitable range from the pattern looking for ":" and "#"
		let range = this.findRange(searchValue);
		if (range) {
			let rangePrefix = searchValue.indexOf('#') >= 0 ? searchValue.indexOf('#') : searchValue.indexOf(':');
			if (rangePrefix >= 0) {
				searchValue = searchValue.substring(0, rangePrefix);
			}
		}

		// Check Cache first
		let cachedResults = this.getResultsFromCache(searchValue, range);
		if (cachedResults) {
			return TPromise.as(new QuickOpenModel(cachedResults));
		}

		// The throttler needs a factory for its promises
		let promiseFactory = () => {
			let receivedFileResults = false;

			// Symbol Results (unless a range is specified)
			let resultPromises: TPromise<QuickOpenModel>[] = [];
			if (!range) {
				let symbolSearchTimeoutPromiseFn: (timeout: number) => Promise = (timeout) => {
					return TPromise.timeout(timeout).then(() => {

						// As long as the file search query did not return, push out the symbol timeout
						// so that the symbol search has a chance to return results at least as long as
						// the file search did not return.
						if (!receivedFileResults) {
							return symbolSearchTimeoutPromiseFn(OpenAnythingHandler.SYMBOL_SEARCH_SUBSEQUENT_TIMEOUT);
						}

						// Empty result since timeout was reached and file results are in
						return Promise.as(new QuickOpenModel());
					});
				};

				let lookupPromise = this.openSymbolHandler.getResults(searchValue);
				let timeoutPromise = symbolSearchTimeoutPromiseFn(OpenAnythingHandler.SYMBOL_SEARCH_INITIAL_TIMEOUT);

				// Timeout lookup after N seconds to not block file search results
				resultPromises.push(Promise.any([lookupPromise, timeoutPromise]).then((result) => {
					return result.value;
				}));
			} else {
				resultPromises.push(Promise.as(new QuickOpenModel())); // We need this empty promise because we are using the throttler below!
			}

			// File Results
			resultPromises.push(this.openFileHandler.getResults(searchValue).then((results: QuickOpenModel) => {
				receivedFileResults = true;

				return results;
			}));

			// Join and sort unified
153
			this.pendingSearch = TPromise.join(resultPromises).then((results: QuickOpenModel[]) => {
154
				this.pendingSearch = null;
E
Erich Gamma 已提交
155 156 157 158 159 160 161 162 163 164

				// If the quick open widget has been closed meanwhile, ignore the result
				if (this.isClosed) {
					return TPromise.as<QuickOpenModel>(new QuickOpenModel());
				}

				// Combine symbol results and file results
				let result = [...results[0].entries, ...results[1].entries];

				// Sort
165
				result.sort((elementA, elementB) => this.sort(elementA, elementB, searchValue, this.fuzzyMatchingEnabled));
E
Erich Gamma 已提交
166 167 168 169 170 171 172 173 174 175 176

				// Apply Range
				result.forEach((element) => {
					if (element instanceof FileEntry) {
						(<FileEntry>element).setRange(range);
					}
				});

				// Cache for fast lookup
				this.resultsToSearchCache[searchValue] = result;

177
				// Cap the number of results to make the view snappy
178
				const viewResults = result.length > OpenAnythingHandler.MAX_DISPLAYED_RESULTS ? result.slice(0, OpenAnythingHandler.MAX_DISPLAYED_RESULTS) : result;
179 180

				return TPromise.as<QuickOpenModel>(new QuickOpenModel(viewResults));
E
Erich Gamma 已提交
181
			}, (error: Error) => {
182
				this.pendingSearch = null;
E
Erich Gamma 已提交
183 184
				this.messageService.show(Severity.Error, error);
			});
185 186

			return this.pendingSearch;
E
Erich Gamma 已提交
187 188 189
		};

		// Trigger through delayer to prevent accumulation while the user is typing
190
		return this.delayer.trigger(promiseFactory);
E
Erich Gamma 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
	}

	private findRange(value: string): IRange {
		let range: IRange = null;

		// Find Line/Column number from search value using RegExp
		let patternMatch = OpenAnythingHandler.LINE_COLON_PATTERN.exec(value);
		if (patternMatch && patternMatch.length > 1) {
			let startLineNumber = parseInt(patternMatch[1], 10);

			// Line Number
			if (types.isNumber(startLineNumber)) {
				range = {
					startLineNumber: startLineNumber,
					startColumn: 1,
					endLineNumber: startLineNumber,
					endColumn: 1
				};

				// Column Number
				if (patternMatch.length > 3) {
					let startColumn = parseInt(patternMatch[3], 10);
					if (types.isNumber(startColumn)) {
						range.startColumn = startColumn;
						range.endColumn = startColumn;
					}
				}
			}

			// User has typed "something:" or "something#" without a line number, in this case treat as start of file
			else if (patternMatch[1] === '') {
				range = {
					startLineNumber: 1,
					startColumn: 1,
					endLineNumber: 1,
					endColumn: 1
				};
			}
		}

		return range;
	}

	public getResultsFromCache(searchValue: string, range: IRange = null): QuickOpenEntry[] {

		// Find cache entries by prefix of search value
		let cachedEntries: QuickOpenEntry[];
		for (let previousSearch in this.resultsToSearchCache) {
239 240

			// If we narrow down, we might be able to reuse the cached results
241
			if (searchValue.indexOf(previousSearch) === 0) {
242 243 244 245
				if (searchValue.indexOf(paths.nativeSep) >= 0 && previousSearch.indexOf(paths.nativeSep) < 0) {
					continue; // since a path character widens the search for potential more matches, require it in previous search too
				}

E
Erich Gamma 已提交
246 247 248 249 250 251 252 253 254 255 256
				cachedEntries = this.resultsToSearchCache[previousSearch];
				break;
			}
		}

		if (!cachedEntries) {
			return null;
		}

		// Pattern match on results and adjust highlights
		let results: QuickOpenEntry[] = [];
B
Benjamin Pasero 已提交
257
		const searchInPath = searchValue.indexOf(paths.nativeSep) >= 0;
E
Erich Gamma 已提交
258 259 260 261 262 263 264 265
		for (let i = 0; i < cachedEntries.length; i++) {
			let entry = cachedEntries[i];

			// Check for file entries if range is used
			if (range && !(entry instanceof FileEntry)) {
				continue;
			}

266
			// Check if this entry is a match for the search value
B
Benjamin Pasero 已提交
267
			let targetToMatch = searchInPath ? labels.getPathLabel(entry.getResource(), this.contextService) : entry.getLabel();
268
			if (!filters.matchesFuzzy(searchValue, targetToMatch, this.fuzzyMatchingEnabled)) {
269 270 271
				continue;
			}

272
			// Apply highlights
273
			const {labelHighlights, descriptionHighlights} = QuickOpenEntry.highlight(entry, searchValue, this.fuzzyMatchingEnabled);
274 275 276
			entry.setHighlights(labelHighlights, descriptionHighlights);

			results.push(entry);
E
Erich Gamma 已提交
277 278 279
		}

		// Sort
280
		results.sort((elementA, elementB) => this.sort(elementA, elementB, searchValue, this.fuzzyMatchingEnabled));
E
Erich Gamma 已提交
281 282 283 284 285 286 287 288 289 290 291

		// Apply Range
		results.forEach((element) => {
			if (element instanceof FileEntry) {
				(<FileEntry>element).setRange(range);
			}
		});

		return results;
	}

292 293 294 295
	private sort(elementA: QuickOpenEntry, elementB: QuickOpenEntry, lookFor: string, enableFuzzyScoring): number {

		// Fuzzy scoring is special
		if (enableFuzzyScoring) {
296 297
			const labelAScore = scorer.score(elementA.getLabel(), lookFor);
			const labelBScore = scorer.score(elementB.getLabel(), lookFor);
298 299 300 301 302

			if (labelAScore !== labelBScore) {
				return labelAScore > labelBScore ? -1 : 1;
			}

303 304
			const descriptionAScore = scorer.score(elementA.getDescription(), lookFor);
			const descriptionBScore = scorer.score(elementB.getDescription(), lookFor);
305 306 307 308 309 310 311 312 313

			if (descriptionAScore !== descriptionBScore) {
				return descriptionAScore > descriptionBScore ? -1 : 1;
			}
		}

		return QuickOpenEntry.compare(elementA, elementB, lookFor);
	}

E
Erich Gamma 已提交
314 315 316 317 318 319 320 321 322 323 324 325 326
	public getGroupLabel(): string {
		return nls.localize('fileAndTypeResults', "file and symbol results");
	}

	public getAutoFocus(searchValue: string): IAutoFocus {
		return {
			autoFocusFirstEntry: true
		};
	}

	public onClose(canceled: boolean): void {
		this.isClosed = true;

327 328 329
		// Cancel any pending search
		this.cancelPendingSearch();

E
Erich Gamma 已提交
330
		// Clear Cache
331
		this.resultsToSearchCache = Object.create(null);
E
Erich Gamma 已提交
332 333 334 335 336

		// Propagate
		this.openSymbolHandler.onClose(canceled);
		this.openFileHandler.onClose(canceled);
	}
337 338 339 340 341 342 343

	private cancelPendingSearch(): void {
		if (this.pendingSearch) {
			this.pendingSearch.cancel();
			this.pendingSearch = null;
		}
	}
E
Erich Gamma 已提交
344
}