searchEditorInput.ts 13.1 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.
 *--------------------------------------------------------------------------------------------*/

B
Benjamin Pasero 已提交
6
import { Registry } from 'vs/platform/registry/common/platform';
7
import { Emitter, Event } from 'vs/base/common/event';
8
import * as network from 'vs/base/common/network';
9
import { basename } from 'vs/base/common/path';
10
import { extname, isEqual, joinPath } from 'vs/base/common/resources';
11 12
import { URI } from 'vs/base/common/uri';
import 'vs/css!./media/searchEditor';
13
import { Range } from 'vs/editor/common/core/range';
14
import { ITextModel, TrackedRangeStickiness } from 'vs/editor/common/model';
15
import { IModelService } from 'vs/editor/common/services/modelService';
16
import { localize } from 'vs/nls';
17
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
18
import { IFileDialogService } from 'vs/platform/dialogs/common/dialogs';
19
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
20
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
21
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
B
Benjamin Pasero 已提交
22
import { EditorInput, GroupIdentifier, IEditorInput, IMoveResult, IRevertOptions, ISaveOptions, IEditorInputFactoryRegistry, Extensions as EditorInputExtensions } from 'vs/workbench/common/editor';
23
import { Memento } from 'vs/workbench/common/memento';
24
import { SearchEditorFindMatchClass, SearchEditorScheme } from 'vs/workbench/contrib/searchEditor/browser/constants';
25
import { SearchEditorModel } from 'vs/workbench/contrib/searchEditor/browser/searchEditorModel';
26
import { defaultSearchConfig, extractSearchQueryFromModel, parseSavedSearchEditor, serializeSearchConfiguration } from 'vs/workbench/contrib/searchEditor/browser/searchEditorSerialization';
27 28
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { AutoSaveMode, IFilesConfigurationService } from 'vs/workbench/services/filesConfiguration/common/filesConfigurationService';
29
import { IPathService } from 'vs/workbench/services/path/common/pathService';
30
import { ISearchConfigurationProperties } from 'vs/workbench/services/search/common/search';
31
import { ITextFileSaveOptions, ITextFileService, stringToSnapshot } from 'vs/workbench/services/textfile/common/textfiles';
32
import { IWorkingCopy, IWorkingCopyBackup, IWorkingCopyService, WorkingCopyCapabilities } from 'vs/workbench/services/workingCopy/common/workingCopyService';
33 34 35 36

export type SearchConfiguration = {
	query: string,
	includes: string,
J
Jackson Kearl 已提交
37
	excludes: string,
38 39 40 41 42 43 44 45
	contextLines: number,
	wholeWord: boolean,
	caseSensitive: boolean,
	regexp: boolean,
	useIgnores: boolean,
	showIncludesExcludes: boolean,
};

46
export const SEARCH_EDITOR_EXT = '.code-search';
47

48 49 50
export class SearchEditorInput extends EditorInput {
	static readonly ID: string = 'workbench.editorinputs.searchEditorInput';

51 52
	private memento: Memento;

53
	private dirty: boolean = false;
54 55 56 57
	private get model(): Promise<ITextModel> {
		return this.searchEditorModel.resolve();
	}

58
	private _cachedModel: ITextModel | undefined;
59

60
	private readonly _onDidChangeContent = this._register(new Emitter<void>());
61 62
	readonly onDidChangeContent: Event<void> = this._onDidChangeContent.event;

J
Jackson Kearl 已提交
63
	private oldDecorationsIDs: string[] = [];
64

65 66
	private _config: Readonly<SearchConfiguration>;
	public get config(): Readonly<SearchConfiguration> { return this._config; }
67 68 69 70 71
	public set config(value: Readonly<SearchConfiguration>) {
		this._config = value;
		this.memento.getMemento(StorageScope.WORKSPACE).searchConfig = value;
		this._onDidChangeLabel.fire();
	}
72

B
Benjamin Pasero 已提交
73 74
	private readonly fileEditorInputFactory = Registry.as<IEditorInputFactoryRegistry>(EditorInputExtensions.EditorInputFactories).getFileEditorInputFactory();

75 76 77 78
	get resource() {
		return this.backingUri || this.modelUri;
	}

79
	constructor(
80 81
		public readonly modelUri: URI,
		public readonly backingUri: URI | undefined,
82
		private searchEditorModel: SearchEditorModel,
83 84 85 86 87 88
		@IModelService private readonly modelService: IModelService,
		@ITextFileService protected readonly textFileService: ITextFileService,
		@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
		@IFileDialogService private readonly fileDialogService: IFileDialogService,
		@IInstantiationService private readonly instantiationService: IInstantiationService,
		@IWorkingCopyService private readonly workingCopyService: IWorkingCopyService,
89 90
		@IFilesConfigurationService private readonly filesConfigurationService: IFilesConfigurationService,
		@ITelemetryService private readonly telemetryService: ITelemetryService,
91
		@IPathService private readonly pathService: IPathService,
92
		@IStorageService storageService: IStorageService,
93 94 95
	) {
		super();

96 97
		this._config = searchEditorModel.config;
		searchEditorModel.onModelResolved
98 99 100 101
			.then(model => {
				this._register(model.onDidChangeContent(() => this._onDidChangeContent.fire()));
				this._register(model);
				this._cachedModel = model;
102
			});
103

104 105 106
		if (this.modelUri.scheme !== SearchEditorScheme) {
			throw Error('SearchEditorInput must be invoked with a SearchEditorScheme uri');
		}
107

108 109 110
		this.memento = new Memento(SearchEditorInput.ID, storageService);
		storageService.onWillSaveState(() => this.memento.saveMemento());

B
Benjamin Pasero 已提交
111 112
		const input = this;
		const workingCopyAdapter = new class implements IWorkingCopy {
113
			readonly resource = input.modelUri;
B
Benjamin Pasero 已提交
114
			get name() { return input.getName(); }
115
			readonly capabilities = input.isUntitled() ? WorkingCopyCapabilities.Untitled : WorkingCopyCapabilities.None;
B
Benjamin Pasero 已提交
116
			readonly onDidChangeDirty = input.onDidChangeDirty;
117
			readonly onDidChangeContent = input.onDidChangeContent;
B
Benjamin Pasero 已提交
118 119 120
			isDirty(): boolean { return input.isDirty(); }
			backup(): Promise<IWorkingCopyBackup> { return input.backup(); }
			save(options?: ISaveOptions): Promise<boolean> { return input.save(0, options).then(editor => !!editor); }
121
			revert(options?: IRevertOptions): Promise<void> { return input.revert(0, options); }
122 123
		};

J
Jackson Kearl 已提交
124
		this._register(this.workingCopyService.registerWorkingCopy(workingCopyAdapter));
125 126
	}

127
	async save(group: GroupIdentifier, options?: ITextFileSaveOptions): Promise<IEditorInput | undefined> {
128
		if ((await this.model).isDisposed()) { return; }
129

130 131
		if (this.backingUri) {
			await this.textFileService.write(this.backingUri, await this.serializeForDisk(), options);
132
			this.setDirty(false);
J
Jackson Kearl 已提交
133
			return this;
134 135
		} else {
			return this.saveAs(group, options);
136 137 138
		}
	}

139
	private async serializeForDisk() {
140
		return serializeSearchConfiguration(this.config) + '\n' + (await this.model).getValue();
141 142 143
	}

	async getModels() {
144
		return { config: this.config, body: await this.model };
145 146
	}

B
Benjamin Pasero 已提交
147 148 149
	async saveAs(group: GroupIdentifier, options?: ITextFileSaveOptions): Promise<IEditorInput | undefined> {
		const path = await this.fileDialogService.pickFileToSave(await this.suggestFileName(), options?.availableFileSystems);
		if (path) {
150
			this.telemetryService.publicLog2('searchEditor/saveSearchResults');
151 152
			const toWrite = await this.serializeForDisk();
			if (await this.textFileService.create(path, toWrite, { overwrite: true })) {
B
Benjamin Pasero 已提交
153
				this.setDirty(false);
154 155
				if (!isEqual(path, this.modelUri)) {
					const input = this.instantiationService.invokeFunction(getOrMakeSearchEditorInput, { config: this.config, backingUri: path });
156
					input.setMatchRanges(this.getMatchRanges());
157
					return input;
B
Benjamin Pasero 已提交
158 159 160 161 162 163 164
				}
				return this;
			}
		}
		return undefined;
	}

165 166 167 168
	getTypeId(): string {
		return SearchEditorInput.ID;
	}

169 170 171
	getName(maxLength = 12): string {
		const trimToMax = (label: string) => (label.length < maxLength ? label : `${label.slice(0, maxLength - 3)}...`);

172 173
		if (this.backingUri) {
			return localize('searchTitle.withQuery', "Search: {0}", basename(this.backingUri?.path, SEARCH_EDITOR_EXT));
174 175
		}

176 177 178 179 180
		const query = this.config.query?.trim();
		if (query) {
			return localize('searchTitle.withQuery', "Search: {0}", trimToMax(query));
		}
		return localize('searchTitle', "Search");
181 182
	}

183
	setDirty(dirty: boolean) {
184 185 186 187 188 189 190 191
		this.dirty = dirty;
		this._onDidChangeDirty.fire();
	}

	isDirty() {
		return this.dirty;
	}

B
Benjamin Pasero 已提交
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
	isSaving(): boolean {
		if (!this.isDirty()) {
			return false; // the editor needs to be dirty for being saved
		}

		if (this.isUntitled()) {
			return false; // untitled are not saving automatically
		}

		if (this.filesConfigurationService.getAutoSaveMode() === AutoSaveMode.AFTER_SHORT_DELAY) {
			return true; // a short auto save is configured, treat this as being saved
		}

		return false;
	}

	isReadonly() {
		return false;
	}

	isUntitled() {
213
		return !this.backingUri;
B
Benjamin Pasero 已提交
214 215
	}

216
	rename(group: GroupIdentifier, target: URI): IMoveResult | undefined {
217
		if (this._cachedModel && extname(target) === SEARCH_EDITOR_EXT) {
218
			return {
219
				editor: this.instantiationService.invokeFunction(getOrMakeSearchEditorInput, { config: this.config, text: this._cachedModel.getValue(), backingUri: target })
220 221 222 223 224 225
			};
		}
		// Ignore move if editor was renamed to a different file extension
		return undefined;
	}

226
	dispose() {
227
		this.modelService.destroyModel(this.modelUri);
228 229 230 231 232 233 234
		super.dispose();
	}

	matches(other: unknown) {
		if (this === other) { return true; }

		if (other instanceof SearchEditorInput) {
235
			return !!(other.modelUri.fragment && other.modelUri.fragment === this.modelUri.fragment);
B
Benjamin Pasero 已提交
236
		} else if (this.fileEditorInputFactory.isFileEditorInput(other)) {
237
			return other.resource?.toString() === this.backingUri?.toString();
238 239 240 241
		}
		return false;
	}

242 243
	getMatchRanges(): Range[] {
		return (this._cachedModel?.getAllDecorations() ?? [])
244
			.filter(decoration => decoration.options.className === SearchEditorFindMatchClass)
J
Jackson Kearl 已提交
245
			.filter(({ range }) => !(range.startColumn === 1 && range.endColumn === 1))
246
			.map(({ range }) => range);
247 248
	}

249
	async setMatchRanges(ranges: Range[]) {
250
		this.oldDecorationsIDs = (await this.searchEditorModel.onModelResolved).deltaDecorations(this.oldDecorationsIDs, ranges.map(range =>
251
			({ range, options: { className: SearchEditorFindMatchClass, stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges } })));
252 253
	}

B
Benjamin Pasero 已提交
254
	async revert(group: GroupIdentifier, options?: IRevertOptions) {
255 256 257 258 259 260 261
		if (this.backingUri) {
			const { config, text } = await this.instantiationService.invokeFunction(parseSavedSearchEditor, this.backingUri);
			(await this.model).setValue(text);
			this.config = config;
		} else {
			(await this.model).setValue('');
		}
B
Benjamin Pasero 已提交
262
		super.revert(group, options);
263 264 265
		this.setDirty(false);
	}

266 267 268 269
	supportsSplitEditor() {
		return false;
	}

270
	private async backup(): Promise<IWorkingCopyBackup> {
271
		const content = stringToSnapshot((await this.model).getValue());
272 273 274 275
		return { content };
	}

	private async suggestFileName(): Promise<URI> {
276
		const query = extractSearchQueryFromModel(await this.model).query;
277

278
		const searchFileName = (query.replace(/[^\w \-_]+/g, '_') || 'Search') + SEARCH_EDITOR_EXT;
279 280 281 282

		const remoteAuthority = this.environmentService.configuration.remoteAuthority;
		const schemeFilter = remoteAuthority ? network.Schemas.vscodeRemote : network.Schemas.file;

283
		return joinPath(this.fileDialogService.defaultFilePath(schemeFilter) || (await this.pathService.userHome()), searchFileName);
284 285 286 287 288 289
	}
}

const inputs = new Map<string, SearchEditorInput>();
export const getOrMakeSearchEditorInput = (
	accessor: ServicesAccessor,
290 291 292 293
	existingData: ({ config: Partial<SearchConfiguration>, backingUri?: URI } &
		({ modelUri: URI, text?: never, } |
		{ text: string, modelUri?: never, } |
		{ backingUri: URI, text?: never, modelUri?: never }))
294 295 296
): SearchEditorInput => {

	const instantiationService = accessor.get(IInstantiationService);
297 298 299
	const storageService = accessor.get(IStorageService);
	const configurationService = accessor.get(IConfigurationService);

300 301
	const searchEditorSettings = configurationService.getValue<ISearchConfigurationProperties>('search').searchEditor;

302
	const reuseOldSettings = searchEditorSettings.reusePriorSearchConfiguration;
303
	const defaultNumberOfContextLines = searchEditorSettings.defaultNumberOfContextLines;
304

305 306
	const priorConfig: SearchConfiguration = reuseOldSettings ? new Memento(SearchEditorInput.ID, storageService).getMemento(StorageScope.WORKSPACE).searchConfig : {};
	const defaultConfig = defaultSearchConfig();
307

R
Rob Lourens 已提交
308
	const config = { ...defaultConfig, ...priorConfig, ...existingData.config };
309

310
	if (defaultNumberOfContextLines !== null && defaultNumberOfContextLines !== undefined) {
311
		config.contextLines = existingData.config.contextLines ?? defaultNumberOfContextLines;
312 313 314 315
	}

	if (existingData.text) {
		config.contextLines = 0;
316 317
	}

318 319
	const modelUri = existingData.modelUri ?? URI.from({ scheme: SearchEditorScheme, fragment: `${Math.random()}` });

320 321
	const cacheKey = existingData.backingUri?.toString() ?? modelUri.toString();
	const existing = inputs.get(cacheKey);
322 323 324 325
	if (existing) {
		return existing;
	}

326 327
	const model = instantiationService.createInstance(SearchEditorModel, modelUri, config, existingData);
	const input = instantiationService.createInstance(SearchEditorInput, modelUri, existingData.backingUri, model);
328

329 330
	inputs.set(cacheKey, input);
	input.onDispose(() => inputs.delete(cacheKey));
331 332 333

	return input;
};