anythingQuickAccess.ts 20.8 KB
Newer Older
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

6
import 'vs/css!./media/anythingQuickAccess';
7
import { IQuickPickSeparator, IQuickInputButton, IKeyMods, quickPickItemScorerAccessor, QuickPickItemScorerAccessor, IQuickPick } from 'vs/platform/quickinput/common/quickInput';
8
import { IPickerQuickAccessItem, PickerQuickAccessProvider, TriggerAction, FastAndSlowPicksType } from 'vs/platform/quickinput/browser/pickerQuickAccess';
9
import { prepareQuery, IPreparedQuery, compareItemsByScore, scoreItem, ScorerCache } from 'vs/base/common/fuzzyScorer';
10 11 12
import { IFileQueryBuilderOptions, QueryBuilder } from 'vs/workbench/contrib/search/common/queryBuilder';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { getOutOfWorkspaceEditorResources, extractRangeFromFilter, IWorkbenchSearchConfiguration } from 'vs/workbench/contrib/search/common/search';
13
import { ISearchService } from 'vs/workbench/services/search/common/search';
14 15 16 17
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { untildify } from 'vs/base/common/labels';
import { IRemotePathService } from 'vs/workbench/services/path/common/remotePathService';
import { URI } from 'vs/base/common/uri';
18
import { toLocalResource, dirname, basenameOrAuthority } from 'vs/base/common/resources';
19 20 21
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IFileService } from 'vs/platform/files/common/files';
import { CancellationToken } from 'vs/base/common/cancellation';
22
import { DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
23 24 25 26 27 28 29
import { ILabelService } from 'vs/platform/label/common/label';
import { getIconClasses } from 'vs/editor/common/services/getIconClasses';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { localize } from 'vs/nls';
import { IWorkingCopyService } from 'vs/workbench/services/workingCopy/common/workingCopyService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
30
import { IWorkbenchEditorConfiguration, IEditorInput, EditorInput } from 'vs/workbench/common/editor';
31 32 33 34 35
import { IEditorService, SIDE_GROUP, ACTIVE_GROUP } from 'vs/workbench/services/editor/common/editorService';
import { Range, IRange } from 'vs/editor/common/core/range';
import { ThrottledDelayer } from 'vs/base/common/async';
import { top } from 'vs/base/common/arrays';
import { FileQueryCacheState } from 'vs/workbench/contrib/search/common/cacheState';
36 37 38 39 40
import { IHistoryService } from 'vs/workbench/services/history/common/history';
import { IResourceEditorInput, ITextEditorOptions } from 'vs/platform/editor/common/editor';
import { Schemas } from 'vs/base/common/network';
import { IFilesConfigurationService, AutoSaveMode } from 'vs/workbench/services/filesConfiguration/common/filesConfigurationService';
import { ResourceMap } from 'vs/base/common/map';
41
import { SymbolsQuickAccessProvider } from 'vs/workbench/contrib/search/browser/symbolsQuickAccess';
42 43

interface IAnythingQuickPickItem extends IPickerQuickAccessItem {
44
	resource: URI | undefined;
45 46 47 48 49 50 51 52
}

export class AnythingQuickAccessProvider extends PickerQuickAccessProvider<IAnythingQuickPickItem> {

	static PREFIX = '';

	private static readonly MAX_RESULTS = 512;

53
	private static readonly TYPING_SEARCH_DELAY = 200; // this delay accommodates for the user typing a word and then stops typing to start searching
54

55 56
	private readonly pickState = new class {
		scorerCache: ScorerCache = Object.create(null);
57
		fileQueryCache: FileQueryCacheState | undefined = undefined;
58

59 60 61
		lastOriginalFilter: string | undefined = undefined;
		lastFilter: string | undefined = undefined;
		lastRange: IRange | undefined = undefined;
62

63 64 65
		constructor(private readonly provider: AnythingQuickAccessProvider) { }

		reset(): void {
66 67

			// Caches
68 69
			this.fileQueryCache = this.provider.createFileQueryCache();
			this.scorerCache = Object.create(null);
70 71

			// Other
72
			this.lastOriginalFilter = undefined;
73 74
			this.lastFilter = undefined;
			this.lastRange = undefined;
75 76 77
		}
	}(this);

78 79 80 81 82 83 84 85 86 87 88 89
	constructor(
		@IInstantiationService private readonly instantiationService: IInstantiationService,
		@ISearchService private readonly searchService: ISearchService,
		@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
		@IRemotePathService private readonly remotePathService: IRemotePathService,
		@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
		@IFileService private readonly fileService: IFileService,
		@ILabelService private readonly labelService: ILabelService,
		@IModelService private readonly modelService: IModelService,
		@IModeService private readonly modeService: IModeService,
		@IWorkingCopyService private readonly workingCopyService: IWorkingCopyService,
		@IConfigurationService private readonly configurationService: IConfigurationService,
90 91 92
		@IEditorService private readonly editorService: IEditorService,
		@IHistoryService private readonly historyService: IHistoryService,
		@IFilesConfigurationService private readonly filesConfigurationService: IFilesConfigurationService
93 94 95 96 97 98 99 100 101 102 103
	) {
		super(AnythingQuickAccessProvider.PREFIX, { canAcceptInBackground: true });
	}

	private get configuration() {
		const editorConfig = this.configurationService.getValue<IWorkbenchEditorConfiguration>().workbench.editor;
		const searchConfig = this.configurationService.getValue<IWorkbenchSearchConfiguration>();

		return {
			openEditorPinned: !editorConfig.enablePreviewFromQuickOpen,
			openSideBySideDirection: editorConfig.openSideBySideDirection,
104 105 106
			includeSymbols: searchConfig.search.quickOpen.includeSymbols,
			includeHistory: searchConfig.search.quickOpen.includeHistory,
			shortAutoSaveDelay: this.filesConfigurationService.getAutoSaveMode() === AutoSaveMode.AFTER_SHORT_DELAY
107 108 109
		};
	}

110
	provide(picker: IQuickPick<IAnythingQuickPickItem>, token: CancellationToken): IDisposable {
111

112 113
		// Reset the pick state for this run
		this.pickState.reset();
114

115
		// Start picker
116 117 118
		return super.provide(picker, token);
	}

119
	protected getPicks(originalFilter: string, disposables: DisposableStore, token: CancellationToken): FastAndSlowPicksType<IAnythingQuickPickItem> | null {
120 121

		// Find a suitable range from the pattern looking for ":", "#" or ","
122 123 124 125
		const filterWithRange = extractRangeFromFilter(originalFilter);

		// Update filter with normalized values
		let filter: string;
126 127
		if (filterWithRange) {
			filter = filterWithRange.filter;
128 129
		} else {
			filter = originalFilter;
130 131
		}

132 133 134
		// Remember as last range
		this.pickState.lastRange = filterWithRange?.range;

135 136 137 138 139
		// If the original filter value has changed but the normalized
		// one has not, we return early with a `null` result indicating
		// that the results should preserve because the range information
		// (:<line>:<column>) does not need to trigger any re-sorting.
		if (originalFilter !== this.pickState.lastOriginalFilter && filter === this.pickState.lastFilter) {
140 141 142 143
			return null;
		}

		// Remember as last filter
144
		this.pickState.lastOriginalFilter = originalFilter;
145 146
		this.pickState.lastFilter = filter;

147 148
		const query = prepareQuery(filter);

149
		const historyEditorPicks = this.getEditorHistoryPicks(query);
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170

		return {

			// Fast picks: editor history
			picks: historyEditorPicks.length > 0 ?
				[
					{ type: 'separator', label: localize('recentlyOpenedSeparator', "recently opened") },
					...historyEditorPicks
				] : [],

			// Slow picks: files and symbols
			additionalPicks: (async (): Promise<Array<IAnythingQuickPickItem | IQuickPickSeparator>> => {

				// Exclude any result that is already present in editor history
				const additionalPicksExcludes = new ResourceMap<boolean>();
				for (const historyEditorPick of historyEditorPicks) {
					if (historyEditorPick.resource) {
						additionalPicksExcludes.set(historyEditorPick.resource, true);
					}
				}

171
				const additionalPicks = await this.getAdditionalPicks(query, additionalPicksExcludes, token);
172 173 174 175 176 177 178 179 180 181 182 183
				if (token.isCancellationRequested) {
					return [];
				}

				return additionalPicks.length > 0 ? [
					{ type: 'separator', label: this.configuration.includeSymbols ? localize('fileAndSymbolResultsSeparator', "file and symbol results") : localize('fileResultsSeparator', "file results") },
					...additionalPicks
				] : [];
			})()
		};
	}

184
	private async getAdditionalPicks(query: IPreparedQuery, excludes: ResourceMap<boolean>, token: CancellationToken): Promise<Array<IAnythingQuickPickItem>> {
185 186 187

		// Resolve file and symbol picks (if enabled)
		const [filePicks, symbolPicks] = await Promise.all([
188 189
			this.getFilePicks(query, excludes, token),
			this.getSymbolPicks(query, token)
190 191 192 193 194 195 196 197 198
		]);

		if (token.isCancellationRequested) {
			return [];
		}

		// Sort top 512 items by score
		const sortedAnythingPicks = top(
			[...filePicks, ...symbolPicks],
199
			(anyPickA, anyPickB) => compareItemsByScore(anyPickA, anyPickB, query, true, quickPickItemScorerAccessor, this.pickState.scorerCache),
200 201 202 203 204
			AnythingQuickAccessProvider.MAX_RESULTS
		);

		// Adjust highlights
		for (const anythingPick of sortedAnythingPicks) {
205 206 207 208
			if (anythingPick.highlights) {
				continue; // preserve any highlights we got already (e.g. symbols)
			}

209
			const { labelMatch, descriptionMatch } = scoreItem(anythingPick, query, true, quickPickItemScorerAccessor, this.pickState.scorerCache);
210 211 212 213 214 215 216 217 218 219

			anythingPick.highlights = {
				label: labelMatch,
				description: descriptionMatch
			};
		}

		return sortedAnythingPicks;
	}

220

221 222
	//#region Editor History

223 224
	private readonly labelOnlyEditorHistoryPickAccessor = new QuickPickItemScorerAccessor({ skipDescription: true });

225
	protected getEditorHistoryPicks(query: IPreparedQuery): Array<IAnythingQuickPickItem> {
226 227 228

		// Just return all history entries if not searching
		if (!query.value) {
229
			return this.historyService.getHistory().map(editor => this.createAnythingPick(editor));
230 231
		}

232 233 234 235
		if (!this.configuration.includeHistory) {
			return []; // disabled when searching
		}

236 237 238
		// Only match on label of the editor unless the search includes path separators
		const editorHistoryScorerAccessor = query.containsPathSeparator ? quickPickItemScorerAccessor : this.labelOnlyEditorHistoryPickAccessor;

239 240 241 242 243 244 245 246
		// Otherwise filter and sort by query
		const editorHistoryPicks: Array<IAnythingQuickPickItem> = [];
		for (const editor of this.historyService.getHistory()) {
			const resource = editor.resource;
			if (!resource || (!this.fileService.canHandleResource(resource) && resource.scheme !== Schemas.untitled)) {
				continue; // exclude editors without file resource if we are searching by pattern
			}

247
			const editorHistoryPick = this.createAnythingPick(editor);
248

249
			const { score, labelMatch, descriptionMatch } = scoreItem(editorHistoryPick, query, false, editorHistoryScorerAccessor, this.pickState.scorerCache);
250 251 252 253 254 255 256 257 258 259 260 261
			if (!score) {
				continue; // exclude editors not matching query
			}

			editorHistoryPick.highlights = {
				label: labelMatch,
				description: descriptionMatch
			};

			editorHistoryPicks.push(editorHistoryPick);
		}

262
		return editorHistoryPicks.sort((editorA, editorB) => compareItemsByScore(editorA, editorB, query, false, editorHistoryScorerAccessor, this.pickState.scorerCache, () => -1));
263 264 265 266 267
	}

	//#endregion


268
	//#region File Search
269

270
	private fileQueryDelayer = this._register(new ThrottledDelayer<URI[]>(AnythingQuickAccessProvider.TYPING_SEARCH_DELAY));
271 272 273

	private fileQueryBuilder = this.instantiationService.createInstance(QueryBuilder);

274 275
	private createFileQueryCache(): FileQueryCacheState {
		return new FileQueryCacheState(
276 277 278
			cacheKey => this.fileQueryBuilder.file(this.contextService.getWorkspace().folders, this.getFileQueryOptions({ cacheKey })),
			query => this.searchService.fileSearch(query),
			cacheKey => this.searchService.clearCache(cacheKey),
279
			this.pickState.fileQueryCache
280
		).load();
281 282
	}

283
	protected async getFilePicks(query: IPreparedQuery, excludes: ResourceMap<boolean>, token: CancellationToken): Promise<Array<IAnythingQuickPickItem>> {
284 285 286 287 288 289 290 291 292 293 294
		if (!query.value) {
			return [];
		}

		// Absolute path result
		const absolutePathResult = await this.getAbsolutePathFileResult(query, token);
		if (token.isCancellationRequested) {
			return [];
		}

		// Use absolute path result as only results if present
295
		let fileMatches: Array<URI>;
296
		if (absolutePathResult) {
297
			fileMatches = [absolutePathResult];
298 299 300 301
		}

		// Otherwise run the file search (with a delayer if cache is not ready yet)
		else {
302
			if (this.pickState.fileQueryCache?.isLoaded) {
303 304
				fileMatches = await this.doFileSearch(query, token);
			} else {
305 306 307 308 309 310 311
				fileMatches = await this.fileQueryDelayer.trigger(async () => {
					if (token.isCancellationRequested) {
						return [];
					}

					return this.doFileSearch(query, token);
				});
312 313 314 315 316 317 318
			}
		}

		if (token.isCancellationRequested) {
			return [];
		}

319 320
		// Filter excludes & convert to picks
		return fileMatches
321 322
			.filter(resource => !excludes.has(resource))
			.map(resource => this.createAnythingPick(resource));
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
	private async doFileSearch(query: IPreparedQuery, token: CancellationToken): Promise<URI[]> {
		const [fileSearchResults, relativePathFileResults] = await Promise.all([

			// File search: this is a search over all files of the workspace using the provided pattern
			this.searchService.fileSearch(
				this.fileQueryBuilder.file(
					this.contextService.getWorkspace().folders,
					this.getFileQueryOptions({
						filePattern: query.original,
						cacheKey: this.pickState.fileQueryCache?.cacheKey,
						maxResults: AnythingQuickAccessProvider.MAX_RESULTS
					})
				), token),

			// Relative path search: we also want to consider results that match files inside the workspace
			// by looking for relative paths that the user typed as query. This allows to return even excluded
			// results into the picker if found (e.g. helps for opening compilation results that are otherwise
			// excluded)
			this.getRelativePathFileResults(query, token)
		]);

		return [
			...fileSearchResults.results.map(result => result.resource),
			...(relativePathFileResults || [])
		];
350 351 352 353
	}

	private getFileQueryOptions(input: { filePattern?: string, cacheKey?: string, maxResults?: number }): IFileQueryBuilderOptions {
		const fileQueryOptions: IFileQueryBuilderOptions = {
354
			_reason: 'openFileHandler', // used for telemetry - do not change
355 356 357 358 359 360 361 362 363 364 365
			extraFileResources: this.instantiationService.invokeFunction(getOutOfWorkspaceEditorResources),
			filePattern: input.filePattern || '',
			cacheKey: input.cacheKey,
			maxResults: input.maxResults || 0,
			sortByScore: true
		};

		return fileQueryOptions;
	}

	private async getAbsolutePathFileResult(query: IPreparedQuery, token: CancellationToken): Promise<URI | undefined> {
366 367 368 369 370
		if (!query.containsPathSeparator) {
			return;
		}

		const detildifiedQuery = untildify(query.value, (await this.remotePathService.userHome).path);
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
		if (token.isCancellationRequested) {
			return;
		}

		const isAbsolutePathQuery = (await this.remotePathService.path).isAbsolute(detildifiedQuery);
		if (token.isCancellationRequested) {
			return;
		}

		if (isAbsolutePathQuery) {
			const resource = toLocalResource(
				await this.remotePathService.fileURI(detildifiedQuery),
				this.environmentService.configuration.remoteAuthority
			);

			if (token.isCancellationRequested) {
				return;
			}

			try {
391 392 393
				if ((await this.fileService.resolve(resource)).isFile) {
					return resource;
				}
394
			} catch (error) {
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
				// ignore if file does not exist
			}
		}

		return;
	}

	private async getRelativePathFileResults(query: IPreparedQuery, token: CancellationToken): Promise<URI[] | undefined> {
		if (!query.containsPathSeparator) {
			return;
		}

		// Convert relative paths to absolute paths over all folders of the workspace
		// and return them as results if the absolute paths exist
		const isAbsolutePathQuery = (await this.remotePathService.path).isAbsolute(query.value);
		if (!isAbsolutePathQuery) {
			const resources: URI[] = [];
			for (const folder of this.contextService.getWorkspace().folders) {
				if (token.isCancellationRequested) {
					break;
				}

				const resource = toLocalResource(
					folder.toResource(query.value),
					this.environmentService.configuration.remoteAuthority
				);

				try {
					if ((await this.fileService.resolve(resource)).isFile) {
						resources.push(resource);
					}
				} catch (error) {
					// ignore if file does not exist
				}
429
			}
430 431

			return resources;
432 433 434 435 436 437 438 439 440 441
		}

		return;
	}

	//#endregion


	//#region Symbols (if enabled)

442 443
	private symbolsQuickAccess = this._register(this.instantiationService.createInstance(SymbolsQuickAccessProvider));

444
	protected async getSymbolPicks(query: IPreparedQuery, token: CancellationToken): Promise<Array<IAnythingQuickPickItem>> {
445 446 447
		if (
			!query.value ||							// we need a value for search for
			!this.configuration.includeSymbols ||	// we need to enable symbols in search
448
			this.pickState.lastRange				// a range is an indicator for just searching for files
449 450 451 452
		) {
			return [];
		}

453
		// Delegate to the existing symbols quick access
454 455
		// but skip local results and also do not sort
		return this.symbolsQuickAccess.getSymbolPicks(query.value, { skipLocal: true, skipSorting: true, delay: AnythingQuickAccessProvider.TYPING_SEARCH_DELAY }, token);
456 457 458
	}

	//#endregion
459 460 461 462


	//#region Helpers

463
	private createAnythingPick(resourceOrEditor: URI | IEditorInput | IResourceEditorInput): IAnythingQuickPickItem {
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
		const isEditorHistoryEntry = !URI.isUri(resourceOrEditor);

		let resource: URI | undefined;
		let label: string;
		let description: string | undefined = undefined;
		let isDirty: boolean | undefined = undefined;

		if (resourceOrEditor instanceof EditorInput) {
			resource = resourceOrEditor.resource;
			label = resourceOrEditor.getName();
			description = resourceOrEditor.getDescription();
			isDirty = resourceOrEditor.isDirty() && !resourceOrEditor.isSaving();
		} else {
			resource = URI.isUri(resourceOrEditor) ? resourceOrEditor : (resourceOrEditor as IResourceEditorInput).resource;
			label = basenameOrAuthority(resource);
			description = this.labelService.getUriLabel(dirname(resource), { relative: true });
			isDirty = this.workingCopyService.isDirty(resource) && !this.configuration.shortAutoSaveDelay;
		}

		return {
			resource,
			label,
			ariaLabel: isEditorHistoryEntry ?
				localize('historyPickAriaLabel', "{0}, recently opened", label) :
				localize('filePickAriaLabel', "{0}, file picker", label),
			description,
490
			iconClasses: getIconClasses(this.modelService, this.modeService, resource),
491 492 493 494 495 496 497 498 499 500 501 502 503 504
			buttons: (() => {
				const openSideBySideDirection = this.configuration.openSideBySideDirection;
				const buttons: IQuickInputButton[] = [];

				// Open to side / below
				buttons.push({
					iconClass: openSideBySideDirection === 'right' ? 'codicon-split-horizontal' : 'codicon-split-vertical',
					tooltip: openSideBySideDirection === 'right' ? localize('openToSide', "Open to the Side") : localize('openToBottom', "Open to the Bottom")
				});

				// Remove from History
				if (isEditorHistoryEntry) {
					buttons.push({
						iconClass: isDirty ? 'dirty-anything codicon-circle-filled' : 'codicon-close',
505 506
						tooltip: localize('closeEditor', "Remove from Recently Opened"),
						alwaysVisible: isDirty
507 508 509 510 511 512 513 514 515 516
					});
				}

				return buttons;
			})(),
			trigger: async (buttonIndex, keyMods) => {
				switch (buttonIndex) {

					// Open to side / below
					case 0:
517
						this.openAnything(resourceOrEditor, { keyMods, range: this.pickState.lastRange, forceOpenSideBySide: true });
518 519
						return TriggerAction.CLOSE_PICKER;

520
					// Remove from History
521 522 523 524 525 526 527 528 529 530
					case 1:
						if (!URI.isUri(resourceOrEditor)) {
							this.historyService.remove(resourceOrEditor);

							return TriggerAction.REFRESH_PICKER;
						}
				}

				return TriggerAction.NO_ACTION;
			},
531
			accept: (keyMods, event) => this.openAnything(resourceOrEditor, { keyMods, range: this.pickState.lastRange, preserveFocus: event.inBackground })
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
		};
	}

	private async openAnything(resourceOrEditor: URI | IEditorInput | IResourceEditorInput, options: { keyMods?: IKeyMods, preserveFocus?: boolean, range?: IRange, forceOpenSideBySide?: boolean }): Promise<void> {
		const editorOptions: ITextEditorOptions = {
			preserveFocus: options.preserveFocus,
			pinned: options.keyMods?.alt || this.configuration.openEditorPinned,
			selection: options.range ? Range.collapseToStart(options.range) : undefined
		};

		const targetGroup = options.keyMods?.ctrlCmd || options.forceOpenSideBySide ? SIDE_GROUP : ACTIVE_GROUP;

		if (resourceOrEditor instanceof EditorInput) {
			await this.editorService.openEditor(resourceOrEditor, editorOptions);
		} else {
			await this.editorService.openEditor({
				resource: URI.isUri(resourceOrEditor) ? resourceOrEditor : resourceOrEditor.resource,
				options: editorOptions
			}, targetGroup);
		}
	}

	//#endregion
555
}