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.
 *--------------------------------------------------------------------------------------------*/

6
import { Emitter, Event } from 'vs/base/common/event';
7
import * as network from 'vs/base/common/network';
8 9
import { basename } from 'vs/base/common/path';
import { isEqual, joinPath, toLocalResource } from 'vs/base/common/resources';
10 11
import { URI } from 'vs/base/common/uri';
import 'vs/css!./media/searchEditor';
12
import type { ICodeEditorViewState } from 'vs/editor/common/editorCommon';
13
import { IModelDeltaDecoration, ITextModel, DefaultEndOfLine } from 'vs/editor/common/model';
14 15
import { IModelService } from 'vs/editor/common/services/modelService';
import { IModeService } from 'vs/editor/common/services/modeService';
16
import { localize } from 'vs/nls';
17
import { IFileDialogService } from 'vs/platform/dialogs/common/dialogs';
18
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
19
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
20 21 22 23 24 25 26
import { EditorInput, GroupIdentifier, IEditorInput, IRevertOptions, ISaveOptions } from 'vs/workbench/common/editor';
import { extractSearchQuery, serializeSearchConfiguration } from 'vs/workbench/contrib/searchEditor/browser/searchEditorSerialization';
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { AutoSaveMode, IFilesConfigurationService } from 'vs/workbench/services/filesConfiguration/common/filesConfigurationService';
27
import { ITextFileSaveOptions, ITextFileService, snapshotToString, stringToSnapshot } from 'vs/workbench/services/textfile/common/textfiles';
28 29
import { IWorkingCopy, IWorkingCopyBackup, IWorkingCopyService, WorkingCopyCapabilities } from 'vs/workbench/services/workingCopy/common/workingCopyService';
import { SearchEditorScheme } from 'vs/workbench/contrib/searchEditor/browser/constants';
30

31

32 33 34 35 36 37 38 39 40 41 42 43
export type SearchConfiguration = {
	query: string,
	includes: string,
	excludes: string
	contextLines: number,
	wholeWord: boolean,
	caseSensitive: boolean,
	regexp: boolean,
	useIgnores: boolean,
	showIncludesExcludes: boolean,
};

J
Jackson Kearl 已提交
44 45 46 47
type SearchEditorViewState =
	| { focused: 'input' }
	| { focused: 'editor', state: ICodeEditorViewState };

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

	private dirty: boolean = false;
52 53 54
	private readonly contentsModel: Promise<ITextModel>;
	private readonly headerModel: Promise<ITextModel>;
	private _cachedConfig?: SearchConfiguration;
55

56 57 58
	private readonly _onDidChangeContent = new Emitter<void>();
	readonly onDidChangeContent: Event<void> = this._onDidChangeContent.event;

J
Jackson Kearl 已提交
59
	viewState: SearchEditorViewState = { focused: 'input' };
60

61 62
	private _highlights: IModelDeltaDecoration[] | undefined;

63 64
	constructor(
		public readonly resource: URI,
65
		getModel: () => Promise<{ contentsModel: ITextModel, headerModel: ITextModel }>,
66
		startingConfig: Partial<SearchConfiguration> | undefined,
67 68 69 70 71 72 73 74
		@IModelService private readonly modelService: IModelService,
		@IEditorService protected readonly editorService: IEditorService,
		@IEditorGroupsService protected readonly editorGroupService: IEditorGroupsService,
		@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,
75 76
		@IFilesConfigurationService private readonly filesConfigurationService: IFilesConfigurationService,
		@ITelemetryService private readonly telemetryService: ITelemetryService,
77
		@IModeService readonly modeService: IModeService,
78 79 80
	) {
		super();

81 82 83
		// Dummy model to set file icon
		this._register(modelService.createModel('', modeService.create('search-result'), this.resource));

84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
		const modelLoader = getModel()
			.then(({ contentsModel, headerModel }) => {
				this._register(contentsModel.onDidChangeContent(() => this._onDidChangeContent.fire()));
				this._register(headerModel.onDidChangeContent(() => {
					this._cachedConfig = extractSearchQuery(headerModel);
					this._onDidChangeContent.fire();
					this._onDidChangeLabel.fire();
				}));

				this._cachedConfig = extractSearchQuery(headerModel);

				this._register(contentsModel);
				this._register(headerModel);

				return { contentsModel, headerModel };
99
			});
100

101 102 103 104
		this.contentsModel = modelLoader.then(({ contentsModel }) => contentsModel);
		this.headerModel = modelLoader.then(({ headerModel }) => headerModel);


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

		this.workingCopyService.registerWorkingCopy(workingCopyAdapter);
	}

121 122 123 124
	getResource() {
		return this.resource;
	}

125
	async save(group: GroupIdentifier, options?: ITextFileSaveOptions): Promise<IEditorInput | undefined> {
126

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

136 137 138 139 140 141 142 143 144 145
	private async serializeForDisk() {
		return (await this.headerModel).getValue() + '\n' + (await this.contentsModel).getValue();
	}

	async getModels() {
		const header = await this.headerModel;
		const body = await this.contentsModel;
		return { header, body };
	}

B
Benjamin Pasero 已提交
146 147 148
	async saveAs(group: GroupIdentifier, options?: ITextFileSaveOptions): Promise<IEditorInput | undefined> {
		const path = await this.fileDialogService.pickFileToSave(await this.suggestFileName(), options?.availableFileSystems);
		if (path) {
149
			this.telemetryService.publicLog2('searchEditor/saveSearchResults');
150
			if (await this.textFileService.create(path, await this.serializeForDisk())) {
B
Benjamin Pasero 已提交
151 152
				this.setDirty(false);
				if (!isEqual(path, this.resource)) {
153 154 155
					const input = this.instantiationService.invokeFunction(getOrMakeSearchEditorInput, { uri: path });
					input.setHighlights(this.highlights);
					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)}...`);

B
Benjamin Pasero 已提交
170
		if (this.isUntitled()) {
171
			const query = this._cachedConfig?.query?.trim();
172 173 174 175
			if (query) {
				return localize('searchTitle.withQuery', "Search: {0}", trimToMax(query));
			}
			return localize('searchTitle', "Search");
176 177 178 179 180 181
		}

		return localize('searchTitle.withQuery', "Search: {0}", basename(this.resource.path, '.code-search'));
	}

	getConfigSync() {
182
		return this._cachedConfig;
183 184 185 186 187 188
	}

	async resolve() {
		return null;
	}

189
	setDirty(dirty: boolean) {
190 191 192 193 194 195 196 197
		this.dirty = dirty;
		this._onDidChangeDirty.fire();
	}

	isDirty() {
		return this.dirty;
	}

B
Benjamin Pasero 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
	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() {
219
		return this.resource.scheme === SearchEditorScheme;
B
Benjamin Pasero 已提交
220 221
	}

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
	dispose() {
		this.modelService.destroyModel(this.resource);
		super.dispose();
	}

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

		if (other instanceof SearchEditorInput) {
			if (
				(other.resource.path && other.resource.path === this.resource.path) ||
				(other.resource.fragment && other.resource.fragment === this.resource.fragment)
			) {
				return true;
			}
		}
		return false;
	}

241 242 243 244 245 246
	public get highlights(): IModelDeltaDecoration[] {
		return (this._highlights ?? []).map(({ range, options }) => ({ range, options }));
	}

	public async setHighlights(value: IModelDeltaDecoration[]) {
		if (!value) { return; }
247
		const model = await this.contentsModel;
248 249 250 251
		model.deltaDecorations([], value);
		this._highlights = value;
	}

252 253 254 255
	public saveHighlights(value: IModelDeltaDecoration[]) {
		this._highlights = value;
	}

B
Benjamin Pasero 已提交
256
	async revert(group: GroupIdentifier, options?: IRevertOptions) {
257
		// TODO: this should actually revert the contents. But it needs to set dirty false.
B
Benjamin Pasero 已提交
258
		super.revert(group, options);
259 260 261 262 263
		this.setDirty(false);
		return true;
	}

	private async backup(): Promise<IWorkingCopyBackup> {
264
		const content = stringToSnapshot(await this.serializeForDisk());
265 266 267 268 269 270
		return { content };
	}

	// Bringing this over from textFileService because it only suggests for untitled scheme.
	// In the future I may just use the untitled scheme. I dont get particular benefit from using search-editor...
	private async suggestFileName(): Promise<URI> {
271
		const query = extractSearchQuery(await this.headerModel).query;
272 273 274 275 276 277

		const searchFileName = (query.replace(/[^\w \-_]+/g, '_') || 'Search') + '.code-search';

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

278 279 280
		const defaultFilePath = this.fileDialogService.defaultFilePath(schemeFilter);
		if (defaultFilePath) {
			return joinPath(defaultFilePath, searchFileName);
281 282
		}

B
Benjamin Pasero 已提交
283
		return toLocalResource(URI.from({ scheme: schemeFilter, path: searchFileName }), remoteAuthority);
284 285 286 287 288 289
	}
}

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

296
	const uri = existingData.uri ?? URI.from({ scheme: SearchEditorScheme, fragment: `${Math.random()}` });
297 298 299 300 301 302 303 304 305 306 307 308

	const instantiationService = accessor.get(IInstantiationService);
	const modelService = accessor.get(IModelService);
	const textFileService = accessor.get(ITextFileService);
	const backupService = accessor.get(IBackupFileService);
	const modeService = accessor.get(IModeService);

	const existing = inputs.get(uri.toString());
	if (existing) {
		return existing;
	}

309
	const config = existingData.config ?? (existingData.text ? extractSearchQuery(existingData.text) : {});
310 311

	const getModel = async () => {
312
		let contents: string;
313

314 315
		const backup = await backupService.resolve(uri);
		if (backup) {
316 317
			// this way of stringifying a TextBufferFactory seems needlessly complicated...
			contents = snapshotToString(backup.value.create(DefaultEndOfLine.LF).createSnapshot(true));
318
		} else if (uri.scheme !== SearchEditorScheme) {
319
			contents = (await textFileService.read(uri)).value;
320 321 322 323
		} else if (existingData.text) {
			contents = existingData.text;
		} else if (existingData.config) {
			contents = serializeSearchConfiguration(existingData.config);
324
		} else {
325
			throw new Error('no initial contents for search editor');
326
		}
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
		backupService.discardBackup(uri);

		const lines = contents.split(/\r?\n/);

		const headerlines = [];
		const bodylines = [];
		let inHeader = true;
		for (const line of lines) {
			if (inHeader) {
				headerlines.push(line);
				if (line === '') {
					inHeader = false;
				}
			} else {
				bodylines.push(line);
			}
		}

		const contentsModelURI = uri.with({ scheme: 'search-editor-body' });
		const headerModelURI = uri.with({ scheme: 'search-editor-header' });
		const contentsModel = modelService.getModel(contentsModelURI) ?? modelService.createModel('', modeService.create('search-result'), contentsModelURI);
		const headerModel = modelService.getModel(headerModelURI) ?? modelService.createModel('', modeService.create('search-result'), headerModelURI);

		contentsModel.setValue(bodylines.join('\n'));
		headerModel.setValue(headerlines.join('\n'));
352

353
		return { contentsModel, headerModel };
354 355
	};

356
	const input = instantiationService.createInstance(SearchEditorInput, uri, getModel, config);
357 358 359 360 361 362

	inputs.set(uri.toString(), input);
	input.onDispose(() => inputs.delete(uri.toString()));

	return input;
};