anythingQuickAccess.ts 18.3 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 } from 'vs/platform/quickinput/common/quickInput';
8
import { IPickerQuickAccessItem, PickerQuickAccessProvider, TriggerAction, FastAndSlowPicksType } from 'vs/platform/quickinput/browser/pickerQuickAccess';
9 10 11 12 13 14 15 16 17
import { prepareQuery, IPreparedQuery, compareItemsByScore, scoreItem } from 'vs/base/common/fuzzyScorer';
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';
import { ISearchService, IFileMatch } from 'vs/workbench/services/search/common/search';
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 22 23 24 25 26 27 28 29
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IFileService } from 'vs/platform/files/common/files';
import { CancellationToken } from 'vs/base/common/cancellation';
import { DisposableStore } from 'vs/base/common/lifecycle';
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, ISymbolsQuickPickItem } 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 53 54 55 56 57 58 59 60 61 62 63 64
}

export class AnythingQuickAccessProvider extends PickerQuickAccessProvider<IAnythingQuickPickItem> {

	static PREFIX = '';

	private static readonly MAX_RESULTS = 512;

	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,
65 66 67
		@IEditorService private readonly editorService: IEditorService,
		@IHistoryService private readonly historyService: IHistoryService,
		@IFilesConfigurationService private readonly filesConfigurationService: IFilesConfigurationService
68 69 70 71 72 73 74 75 76 77 78
	) {
		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,
79 80 81
			includeSymbols: searchConfig.search.quickOpen.includeSymbols,
			includeHistory: searchConfig.search.quickOpen.includeHistory,
			shortAutoSaveDelay: this.filesConfigurationService.getAutoSaveMode() === AutoSaveMode.AFTER_SHORT_DELAY
82 83 84
		};
	}

85
	protected getPicks(filter: string, disposables: DisposableStore, token: CancellationToken): FastAndSlowPicksType<IAnythingQuickPickItem | IQuickPickSeparator> {
86 87 88 89 90 91 92 93 94 95 96 97 98 99

		// TODO this should run just once when picker opens
		this.warmUpFileQueryCache();

		// Find a suitable range from the pattern looking for ":", "#" or ","
		let range: IRange | undefined = undefined;
		const filterWithRange = extractRangeFromFilter(filter);
		if (filterWithRange) {
			filter = filterWithRange.filter;
			range = filterWithRange.range;
		}

		const query = prepareQuery(filter);

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
		const historyEditorPicks = this.getEditorHistoryPicks(query, range);

		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);
					}
				}

				const additionalPicks = await this.getAdditionalPicks(query, range, additionalPicksExcludes, token);
				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
				] : [];
			})()
		};
	}

	private async getAdditionalPicks(query: IPreparedQuery, range: IRange | undefined, excludes: ResourceMap<boolean>, token: CancellationToken): Promise<Array<IAnythingQuickPickItem>> {
136 137 138

		// Resolve file and symbol picks (if enabled)
		const [filePicks, symbolPicks] = await Promise.all([
139
			this.getFilePicks(query, range, excludes, token),
140
			this.getSymbolPicks(query, range, token)
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
		]);

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

		// Sort top 512 items by score
		const scorerCache = Object.create(null); // TODO should keep this for as long as the picker is opened (also check other pickers)
		const sortedAnythingPicks = top(
			[...filePicks, ...symbolPicks],
			(anyPickA, anyPickB) => compareItemsByScore(anyPickA, anyPickB, query, true, quickPickItemScorerAccessor, scorerCache),
			AnythingQuickAccessProvider.MAX_RESULTS
		);

		// Adjust highlights
		for (const anythingPick of sortedAnythingPicks) {
			const { labelMatch, descriptionMatch } = scoreItem(anythingPick, query, true, quickPickItemScorerAccessor, scorerCache);

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

		return sortedAnythingPicks;
	}

168

169 170
	//#region Editor History

171 172
	private readonly labelOnlyEditorHistoryPickAccessor = new QuickPickItemScorerAccessor({ skipDescription: true });

173 174 175 176 177 178 179 180 181 182
	protected getEditorHistoryPicks(query: IPreparedQuery, range: IRange | undefined): Array<IAnythingQuickPickItem> {
		if (!this.configuration.includeHistory) {
			return []; // disabled
		}

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

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

186 187 188 189 190 191 192 193 194 195 196
		// Otherwise filter and sort by query
		const editorHistoryPicks: Array<IAnythingQuickPickItem> = [];
		const scorerCache = Object.create(null); // TODO should keep this for as long as the picker is opened (also check other pickers)
		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
			}

			const editorHistoryPick = this.createAnythingPick(editor, range);

197
			const { score, labelMatch, descriptionMatch } = scoreItem(editorHistoryPick, query, false, editorHistoryScorerAccessor, scorerCache);
198 199 200 201 202 203 204 205 206 207 208 209
			if (!score) {
				continue; // exclude editors not matching query
			}

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

			editorHistoryPicks.push(editorHistoryPick);
		}

210
		return editorHistoryPicks.sort((editorA, editorB) => compareItemsByScore(editorA, editorB, query, false, editorHistoryScorerAccessor, scorerCache, () => -1));
211 212 213 214 215
	}

	//#endregion


216
	//#region File Search
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234

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

	private fileQueryDelayer = this._register(new ThrottledDelayer<IFileMatch[]>(AnythingQuickAccessProvider.FILE_QUERY_DELAY));

	private fileQueryBuilder = this.instantiationService.createInstance(QueryBuilder);
	private fileQueryCacheState: FileQueryCacheState | undefined;

	private warmUpFileQueryCache(): void {
		this.fileQueryCacheState = new FileQueryCacheState(
			cacheKey => this.fileQueryBuilder.file(this.contextService.getWorkspace().folders, this.getFileQueryOptions({ cacheKey })),
			query => this.searchService.fileSearch(query),
			cacheKey => this.searchService.clearCache(cacheKey),
			this.fileQueryCacheState
		);
		this.fileQueryCacheState.load();
	}

235
	protected async getFilePicks(query: IPreparedQuery, range: IRange | undefined, excludes: ResourceMap<boolean>, token: CancellationToken): Promise<Array<IAnythingQuickPickItem>> {
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
		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
		let fileMatches: Array<IFileMatch<URI>>;
		if (absolutePathResult) {
			fileMatches = [{ resource: absolutePathResult }];
		}

		// Otherwise run the file search (with a delayer if cache is not ready yet)
		else {
			if (this.fileQueryCacheState?.isLoaded) {
				fileMatches = await this.doFileSearch(query, token);
			} else {
				fileMatches = await this.fileQueryDelayer.trigger(() => this.doFileSearch(query, token));
			}
		}

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

265 266 267 268
		// Filter excludes & convert to picks
		return fileMatches
			.filter(fileMatch => !excludes.has(fileMatch.resource))
			.map(fileMatch => this.createAnythingPick(fileMatch.resource, range));
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 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
	}

	private async doFileSearch(query: IPreparedQuery, token: CancellationToken): Promise<IFileMatch[]> {
		if (token.isCancellationRequested) {
			return [];
		}

		const { results } = await this.searchService.fileSearch(
			this.fileQueryBuilder.file(
				this.contextService.getWorkspace().folders,
				this.getFileQueryOptions({
					filePattern: query.original,
					cacheKey: this.fileQueryCacheState?.cacheKey,
					maxResults: AnythingQuickAccessProvider.MAX_RESULTS
				})
			), token);

		return results;
	}

	private getFileQueryOptions(input: { filePattern?: string, cacheKey?: string, maxResults?: number }): IFileQueryBuilderOptions {
		const fileQueryOptions: IFileQueryBuilderOptions = {
			_reason: 'openFileHandler',
			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> {
		const detildifiedQuery = untildify(query.original, (await this.remotePathService.userHome).path);
		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 {
				return (await this.fileService.resolve(resource)).isDirectory ? undefined : resource;
			} catch (error) {
				// ignore
			}
		}

		return;
	}

	//#endregion


	//#region Symbols (if enabled)

338 339 340
	private symbolsQuickAccess = this._register(this.instantiationService.createInstance(SymbolsQuickAccessProvider));

	protected async getSymbolPicks(query: IPreparedQuery, range: IRange | undefined, token: CancellationToken): Promise<Array<ISymbolsQuickPickItem>> {
341 342 343 344 345 346 347 348
		if (
			!query.value ||							// we need a value for search for
			!this.configuration.includeSymbols ||	// we need to enable symbols in search
			range									// a range is an indicator for just searching for files
		) {
			return [];
		}

349 350
		// Delegate to the existing symbols quick access
		return this.symbolsQuickAccess.getSymbolPicks(query.value, token, { skipLocal: true, skipSorting: true, skipMatching: true });
351 352 353
	}

	//#endregion
354 355 356 357 358 359 360 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 394 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 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457


	//#region Helpers

	private createAnythingPick(resourceOrEditor: URI | IEditorInput | IResourceEditorInput, range: IRange | undefined): IAnythingQuickPickItem {
		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,
			iconClasses: getIconClasses(this.modelService, this.modeService, resource), // TODO force 'file' icon if symbols are merged in for better looks
			buttonsAlwaysVisible: isDirty,
			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',
						tooltip: localize('closeEditor', "Remove from Recently Opened")
					});
				}

				// Dirty indicator
				else if (isDirty) {
					buttons.push({
						iconClass: 'codicon-circle-filled',
						tooltip: localize('dirtyFile', "Dirty File")
					});
				}

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

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

					// Remove from History / Dirty Indicator
					case 1:
						if (!URI.isUri(resourceOrEditor)) {
							this.historyService.remove(resourceOrEditor);

							return TriggerAction.REFRESH_PICKER;
						}
				}

				return TriggerAction.NO_ACTION;
			},
			accept: (keyMods, event) => this.openAnything(resourceOrEditor, { keyMods, range, preserveFocus: event.inBackground })
		};
	}

	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
458
}