searchEditorInput.ts 12.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 { Emitter, Event } from 'vs/base/common/event';
7
import * as network from 'vs/base/common/network';
8
import { basename } from 'vs/base/common/path';
9
import { extname, isEqual, joinPath } from 'vs/base/common/resources';
10 11
import { URI } from 'vs/base/common/uri';
import 'vs/css!./media/searchEditor';
12
import { Range } from 'vs/editor/common/core/range';
13
import { ITextModel, TrackedRangeStickiness } from 'vs/editor/common/model';
14
import { IModelService } from 'vs/editor/common/services/modelService';
15
import { localize } from 'vs/nls';
16
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
17
import { IFileDialogService } from 'vs/platform/dialogs/common/dialogs';
18
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
19
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
20
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
21
import { EditorInput, GroupIdentifier, IEditorInput, IMoveResult, IRevertOptions, ISaveOptions } from 'vs/workbench/common/editor';
22
import { Memento } from 'vs/workbench/common/memento';
23 24
import { FileEditorInput } from 'vs/workbench/contrib/files/common/editors/fileEditorInput';
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 47
const SEARCH_EDITOR_EXT = '.code-search';

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 73 74 75 76

	get resource() {
		return this.backingUri || this.modelUri;
	}

77
	constructor(
78 79
		public readonly modelUri: URI,
		public readonly backingUri: URI | undefined,
80
		private searchEditorModel: SearchEditorModel,
81 82 83 84 85 86
		@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,
87 88
		@IFilesConfigurationService private readonly filesConfigurationService: IFilesConfigurationService,
		@ITelemetryService private readonly telemetryService: ITelemetryService,
89
		@IPathService private readonly pathService: IPathService,
90
		@IStorageService storageService: IStorageService,
91 92 93
	) {
		super();

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

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

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

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

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

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

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

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

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

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

163 164 165 166
	getTypeId(): string {
		return SearchEditorInput.ID;
	}

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

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

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

	async resolve() {
		return null;
	}

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

	isDirty() {
		return this.dirty;
	}

B
Benjamin Pasero 已提交
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
	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() {
215
		return !this.backingUri;
B
Benjamin Pasero 已提交
216 217
	}

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

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

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

		if (other instanceof SearchEditorInput) {
237 238 239
			return !!(other.modelUri.fragment && other.modelUri.fragment === this.modelUri.fragment);
		} else if (other instanceof FileEditorInput) {
			return other.resource?.toString() === this.backingUri?.toString();
240 241 242 243
		}
		return false;
	}

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

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

B
Benjamin Pasero 已提交
256
	async revert(group: GroupIdentifier, options?: IRevertOptions) {
257 258 259 260 261 262 263
		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 已提交
264
		super.revert(group, options);
265 266 267
		this.setDirty(false);
	}

268 269 270 271
	supportsSplitEditor() {
		return false;
	}

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

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

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

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

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

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

	const instantiationService = accessor.get(IInstantiationService);
299 300 301
	const storageService = accessor.get(IStorageService);
	const configurationService = accessor.get(IConfigurationService);

302 303
	const searchEditorSettings = configurationService.getValue<ISearchConfigurationProperties>('search').searchEditor;

304 305
	const reuseOldSettings = searchEditorSettings.reusePriorSearchConfiguration;
	const defaultShowContextValue = searchEditorSettings.defaultShowContextValue;
306

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

310 311
	let config = { ...defaultConfig, ...priorConfig, ...existingData.config };

312 313 314 315
	if (defaultShowContextValue !== null && defaultShowContextValue !== undefined) {
		config.contextLines = defaultShowContextValue;
	}

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

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

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

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

	return input;
};