textFileService.ts 33.9 KB
Newer Older
B
Benjamin Pasero 已提交
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 7
import * as nls from 'vs/nls';
import { URI } from 'vs/base/common/uri';
8
import { Emitter, AsyncEmitter } from 'vs/base/common/event';
9 10
import * as platform from 'vs/base/common/platform';
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
11
import { IResult, ITextFileOperationResult, ITextFileService, ITextFileStreamContent, ITextFileEditorModelManager, ITextFileEditorModel, ModelState, ITextFileContent, IResourceEncodings, IReadTextFileOptions, IWriteTextFileOptions, toBufferOrReadable, TextFileOperationError, TextFileOperationResult, FileOperationWillRunEvent, FileOperationDidRunEvent, ITextFileSaveOptions } from 'vs/workbench/services/textfile/common/textfiles';
12
import { SaveReason, IRevertOptions } from 'vs/workbench/common/editor';
13 14
import { ILifecycleService, ShutdownReason, LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
15
import { IFileService, FileOperationError, FileOperationResult, HotExitConfiguration, IFileStatWithMetadata, ICreateFileOptions, FileOperation } from 'vs/platform/files/common/files';
16 17
import { Disposable } from 'vs/base/common/lifecycle';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
18 19
import { IUntitledTextEditorService } from 'vs/workbench/services/untitled/common/untitledTextEditorService';
import { UntitledTextEditorModel } from 'vs/workbench/common/editor/untitledTextEditorModel';
20 21 22
import { TextFileEditorModelManager } from 'vs/workbench/services/textfile/common/textFileEditorModelManager';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ResourceMap } from 'vs/base/common/map';
23
import { Schemas } from 'vs/base/common/network';
24 25 26
import { IHistoryService } from 'vs/workbench/services/history/common/history';
import { createTextBufferFactoryFromSnapshot, createTextBufferFactoryFromStream } from 'vs/editor/common/model/textModel';
import { IModelService } from 'vs/editor/common/services/modelService';
27
import { INotificationService } from 'vs/platform/notification/common/notification';
28
import { isEqualOrParent, isEqual, joinPath, dirname, extname, basename, toLocalResource } from 'vs/base/common/resources';
29
import { IDialogService, IFileDialogService, ISaveDialogOptions, IConfirmation, ConfirmResult } from 'vs/platform/dialogs/common/dialogs';
30 31 32 33 34 35 36 37
import { IModeService } from 'vs/editor/common/services/modeService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { coalesce } from 'vs/base/common/arrays';
import { trim } from 'vs/base/common/strings';
import { VSBuffer } from 'vs/base/common/buffer';
import { ITextSnapshot } from 'vs/editor/common/model';
import { ITextResourceConfigurationService } from 'vs/editor/common/services/resourceConfiguration';
import { PLAINTEXT_MODE_ID } from 'vs/editor/common/modes/modesRegistry';
38
import { IFilesConfigurationService, AutoSaveMode } from 'vs/workbench/services/filesConfiguration/common/filesConfigurationService';
39
import { CancellationToken } from 'vs/base/common/cancellation';
B
Benjamin Pasero 已提交
40

41 42 43 44
/**
 * The workbench file service implementation implements the raw file service spec and adds additional methods on top.
 */
export abstract class AbstractTextFileService extends Disposable implements ITextFileService {
B
Benjamin Pasero 已提交
45

46 47
	_serviceBrand: undefined;

48
	//#region events
49

50 51 52 53 54 55
	private _onWillRunOperation = this._register(new AsyncEmitter<FileOperationWillRunEvent>());
	readonly onWillRunOperation = this._onWillRunOperation.event;

	private _onDidRunOperation = this._register(new Emitter<FileOperationDidRunEvent>());
	readonly onDidRunOperation = this._onDidRunOperation.event;

56
	//#endregion
57

58 59 60 61 62 63 64 65
	private _models: TextFileEditorModelManager;
	get models(): ITextFileEditorModelManager { return this._models; }

	abstract get encoding(): IResourceEncodings;

	constructor(
		@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
		@IFileService protected readonly fileService: IFileService,
66
		@IUntitledTextEditorService protected readonly untitledTextEditorService: IUntitledTextEditorService,
67
		@ILifecycleService private readonly lifecycleService: ILifecycleService,
68
		@IInstantiationService protected readonly instantiationService: IInstantiationService,
69 70 71 72 73 74 75 76 77
		@IModeService private readonly modeService: IModeService,
		@IModelService private readonly modelService: IModelService,
		@IWorkbenchEnvironmentService protected readonly environmentService: IWorkbenchEnvironmentService,
		@INotificationService private readonly notificationService: INotificationService,
		@IBackupFileService private readonly backupFileService: IBackupFileService,
		@IHistoryService private readonly historyService: IHistoryService,
		@IDialogService private readonly dialogService: IDialogService,
		@IFileDialogService private readonly fileDialogService: IFileDialogService,
		@IEditorService private readonly editorService: IEditorService,
78
		@ITextResourceConfigurationService protected readonly textResourceConfigurationService: ITextResourceConfigurationService,
79
		@IFilesConfigurationService protected readonly filesConfigurationService: IFilesConfigurationService
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
	) {
		super();

		this._models = this._register(instantiationService.createInstance(TextFileEditorModelManager));

		this.registerListeners();
	}

	//#region event handling

	private registerListeners(): void {

		// Lifecycle
		this.lifecycleService.onBeforeShutdown(event => event.veto(this.onBeforeShutdown(event.reason)));
		this.lifecycleService.onShutdown(this.dispose, this);

96
		// Auto save changes
97
		this._register(this.filesConfigurationService.onAutoSaveConfigurationChange(() => this.onAutoSaveConfigurationChange()));
98 99 100 101 102
	}

	private onAutoSaveConfigurationChange(): void {

		// save all dirty when enabling auto save
103
		if (this.filesConfigurationService.getAutoSaveMode() !== AutoSaveMode.OFF) {
104 105
			this.saveAll();
		}
106 107 108 109 110 111 112 113 114 115
	}

	protected onBeforeShutdown(reason: ShutdownReason): boolean | Promise<boolean> {

		// Dirty files need treatment on shutdown
		const dirty = this.getDirty();
		if (dirty.length) {

			// If auto save is enabled, save all files and then check again for dirty files
			// We DO NOT run any save participant if we are in the shutdown phase for performance reasons
116
			if (this.filesConfigurationService.getAutoSaveMode() !== AutoSaveMode.OFF) {
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
				return this.saveAll(false /* files only */, { skipSaveParticipants: true }).then(() => {

					// If we still have dirty files, we either have untitled ones or files that cannot be saved
					const remainingDirty = this.getDirty();
					if (remainingDirty.length) {
						return this.handleDirtyBeforeShutdown(remainingDirty, reason);
					}

					return false;
				});
			}

			// Auto save is not enabled
			return this.handleDirtyBeforeShutdown(dirty, reason);
		}

		// No dirty files: no veto
		return this.noVeto({ cleanUpBackups: true });
	}

	private handleDirtyBeforeShutdown(dirty: URI[], reason: ShutdownReason): boolean | Promise<boolean> {

		// If hot exit is enabled, backup dirty files and allow to exit without confirmation
140
		if (this.filesConfigurationService.isHotExitEnabled) {
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
			return this.backupBeforeShutdown(dirty, reason).then(didBackup => {
				if (didBackup) {
					return this.noVeto({ cleanUpBackups: false }); // no veto and no backup cleanup (since backup was successful)
				}

				// since a backup did not happen, we have to confirm for the dirty files now
				return this.confirmBeforeShutdown();
			}, error => {
				this.notificationService.error(nls.localize('files.backup.failSave', "Files that are dirty could not be written to the backup location (Error: {0}). Try saving your files first and then exit.", error.message));

				return true; // veto, the backups failed
			});
		}

		// Otherwise just confirm from the user what to do with the dirty files
		return this.confirmBeforeShutdown();
	}

	private async backupBeforeShutdown(dirtyToBackup: URI[], reason: ShutdownReason): Promise<boolean> {
		// When quit is requested skip the confirm callback and attempt to backup all workspaces.
		// When quit is not requested the confirm callback should be shown when the window being
		// closed is the only VS Code window open, except for on Mac where hot exit is only
		// ever activated when quit is requested.

		let doBackup: boolean | undefined;
		switch (reason) {
			case ShutdownReason.CLOSE:
168
				if (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY && this.filesConfigurationService.hotExitConfiguration === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
169
					doBackup = true; // backup if a folder is open and onExitAndWindowClose is configured
170
				} else if (await this.getWindowCount() > 1 || platform.isMacintosh) {
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
					doBackup = false; // do not backup if a window is closed that does not cause quitting of the application
				} else {
					doBackup = true; // backup if last window is closed on win/linux where the application quits right after
				}
				break;

			case ShutdownReason.QUIT:
				doBackup = true; // backup because next start we restore all backups
				break;

			case ShutdownReason.RELOAD:
				doBackup = true; // backup because after window reload, backups restore
				break;

			case ShutdownReason.LOAD:
186
				if (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY && this.filesConfigurationService.hotExitConfiguration === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
					doBackup = true; // backup if a folder is open and onExitAndWindowClose is configured
				} else {
					doBackup = false; // do not backup because we are switching contexts
				}
				break;
		}

		if (!doBackup) {
			return false;
		}

		await this.backupAll(dirtyToBackup);

		return true;
	}

203 204
	protected abstract getWindowCount(): Promise<number>;

205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
	private backupAll(dirtyToBackup: URI[]): Promise<void> {

		// split up between files and untitled
		const filesToBackup: ITextFileEditorModel[] = [];
		const untitledToBackup: URI[] = [];
		dirtyToBackup.forEach(dirty => {
			if (this.fileService.canHandleResource(dirty)) {
				const model = this.models.get(dirty);
				if (model) {
					filesToBackup.push(model);
				}
			} else if (dirty.scheme === Schemas.untitled) {
				untitledToBackup.push(dirty);
			}
		});

		return this.doBackupAll(filesToBackup, untitledToBackup);
	}

	private async doBackupAll(dirtyFileModels: ITextFileEditorModel[], untitledResources: URI[]): Promise<void> {

		// Handle file resources first
		await Promise.all(dirtyFileModels.map(model => model.backup()));

		// Handle untitled resources
		await Promise.all(untitledResources
231 232
			.filter(untitled => this.untitledTextEditorService.exists(untitled))
			.map(async untitled => (await this.untitledTextEditorService.loadOrCreate({ resource: untitled })).backup()));
233 234 235
	}

	private async confirmBeforeShutdown(): Promise<boolean> {
236
		const confirm = await this.fileDialogService.showSaveConfirm(this.getDirty());
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253

		// Save
		if (confirm === ConfirmResult.SAVE) {
			const result = await this.saveAll(true /* includeUntitled */, { skipSaveParticipants: true });

			if (result.results.some(r => !r.success)) {
				return true; // veto if some saves failed
			}

			return this.noVeto({ cleanUpBackups: true });
		}

		// Don't Save
		else if (confirm === ConfirmResult.DONT_SAVE) {

			// Make sure to revert untitled so that they do not restore
			// see https://github.com/Microsoft/vscode/issues/29572
254
			this.untitledTextEditorService.revertAll();
255 256 257 258 259 260 261 262 263 264 265 266 267 268 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

			return this.noVeto({ cleanUpBackups: true });
		}

		// Cancel
		else if (confirm === ConfirmResult.CANCEL) {
			return true; // veto
		}

		return false;
	}

	private noVeto(options: { cleanUpBackups: boolean }): boolean | Promise<boolean> {
		if (!options.cleanUpBackups) {
			return false;
		}

		if (this.lifecycleService.phase < LifecyclePhase.Restored) {
			return false; // if editors have not restored, we are not up to speed with backups and thus should not clean them
		}

		return this.cleanupBackupsBeforeShutdown().then(() => false, () => false);
	}

	protected async cleanupBackupsBeforeShutdown(): Promise<void> {
		if (this.environmentService.isExtensionDevelopment) {
			return;
		}

		await this.backupFileService.discardAllWorkspaceBackups();
	}

	//#endregion

	//#region primitives (read, create, move, delete, update)

	async read(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileContent> {
		const content = await this.fileService.readFile(resource, options);

		// in case of acceptTextOnly: true, we check the first
		// chunk for possibly being binary by looking for 0-bytes
		// we limit this check to the first 512 bytes
		this.validateBinary(content.value, options);

		return {
			...content,
			encoding: 'utf8',
			value: content.value.toString()
		};
	}

	async readStream(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileStreamContent> {
		const stream = await this.fileService.readFileStream(resource, options);

		// in case of acceptTextOnly: true, we check the first
		// chunk for possibly being binary by looking for 0-bytes
		// we limit this check to the first 512 bytes
		let checkedForBinary = false;
		const throwOnBinary = (data: VSBuffer): Error | undefined => {
			if (!checkedForBinary) {
				checkedForBinary = true;

				this.validateBinary(data, options);
			}

			return undefined;
		};

		return {
			...stream,
			encoding: 'utf8',
B
Benjamin Pasero 已提交
326
			value: await createTextBufferFactoryFromStream(stream.value, undefined, options?.acceptTextOnly ? throwOnBinary : undefined)
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
		};
	}

	private validateBinary(buffer: VSBuffer, options?: IReadTextFileOptions): void {
		if (!options || !options.acceptTextOnly) {
			return; // no validation needed
		}

		// in case of acceptTextOnly: true, we check the first
		// chunk for possibly being binary by looking for 0-bytes
		// we limit this check to the first 512 bytes
		for (let i = 0; i < buffer.byteLength && i < 512; i++) {
			if (buffer.readUInt8(i) === 0) {
				throw new TextFileOperationError(nls.localize('fileBinaryError', "File seems to be binary and cannot be opened as text"), TextFileOperationResult.FILE_IS_BINARY, options);
			}
		}
	}

	async create(resource: URI, value?: string | ITextSnapshot, options?: ICreateFileOptions): Promise<IFileStatWithMetadata> {
346 347

		// before event
J
Johannes Rieken 已提交
348
		await this._onWillRunOperation.fireAsync({ operation: FileOperation.CREATE, target: resource }, CancellationToken.None);
349

350 351 352 353 354 355 356 357 358 359 360
		const stat = await this.doCreate(resource, value, options);

		// If we had an existing model for the given resource, load
		// it again to make sure it is up to date with the contents
		// we just wrote into the underlying resource by calling
		// revert()
		const existingModel = this.models.get(resource);
		if (existingModel && !existingModel.isDisposed()) {
			await existingModel.revert();
		}

361 362 363
		// after event
		this._onDidRunOperation.fire(new FileOperationDidRunEvent(FileOperation.CREATE, resource));

364 365 366 367 368 369 370 371 372 373 374 375 376
		return stat;
	}

	protected doCreate(resource: URI, value?: string | ITextSnapshot, options?: ICreateFileOptions): Promise<IFileStatWithMetadata> {
		return this.fileService.createFile(resource, toBufferOrReadable(value), options);
	}

	async write(resource: URI, value: string | ITextSnapshot, options?: IWriteTextFileOptions): Promise<IFileStatWithMetadata> {
		return this.fileService.writeFile(resource, toBufferOrReadable(value), options);
	}

	async delete(resource: URI, options?: { useTrash?: boolean, recursive?: boolean }): Promise<void> {

377
		// before event
J
Johannes Rieken 已提交
378
		await this._onWillRunOperation.fireAsync({ operation: FileOperation.DELETE, target: resource }, CancellationToken.None);
379 380

		const dirtyFiles = this.getDirty().filter(dirty => isEqualOrParent(dirty, resource));
381 382
		await this.revertAll(dirtyFiles, { soft: true });

383
		await this.fileService.del(resource, options);
384 385

		// after event
386
		this._onDidRunOperation.fire(new FileOperationDidRunEvent(FileOperation.DELETE, resource));
387 388 389 390
	}

	async move(source: URI, target: URI, overwrite?: boolean): Promise<IFileStatWithMetadata> {

391
		// before event
J
Johannes Rieken 已提交
392
		await this._onWillRunOperation.fireAsync({ operation: FileOperation.MOVE, target, source }, CancellationToken.None);
393

394 395 396 397
		// find all models that related to either source or target (can be many if resource is a folder)
		const sourceModels: ITextFileEditorModel[] = [];
		const conflictingModels: ITextFileEditorModel[] = [];
		for (const model of this.getFileModels()) {
398
			const resource = model.resource;
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413

			if (isEqualOrParent(resource, target, false /* do not ignorecase, see https://github.com/Microsoft/vscode/issues/56384 */)) {
				conflictingModels.push(model);
			}

			if (isEqualOrParent(resource, source)) {
				sourceModels.push(model);
			}
		}

		// remember each source model to load again after move is done
		// with optional content to restore if it was dirty
		type ModelToRestore = { resource: URI; snapshot?: ITextSnapshot };
		const modelsToRestore: ModelToRestore[] = [];
		for (const sourceModel of sourceModels) {
414
			const sourceModelResource = sourceModel.resource;
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438

			// If the source is the actual model, just use target as new resource
			let modelToRestoreResource: URI;
			if (isEqual(sourceModelResource, source)) {
				modelToRestoreResource = target;
			}

			// Otherwise a parent folder of the source is being moved, so we need
			// to compute the target resource based on that
			else {
				modelToRestoreResource = joinPath(target, sourceModelResource.path.substr(source.path.length + 1));
			}

			const modelToRestore: ModelToRestore = { resource: modelToRestoreResource };
			if (sourceModel.isDirty()) {
				modelToRestore.snapshot = sourceModel.createSnapshot();
			}

			modelsToRestore.push(modelToRestore);
		}

		// in order to move, we need to soft revert all dirty models,
		// both from the source as well as the target if any
		const dirtyModels = [...sourceModels, ...conflictingModels].filter(model => model.isDirty());
439
		await this.revertAll(dirtyModels.map(dirtyModel => dirtyModel.resource), { soft: true });
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470

		// now we can rename the source to target via file operation
		let stat: IFileStatWithMetadata;
		try {
			stat = await this.fileService.move(source, target, overwrite);
		} catch (error) {

			// in case of any error, ensure to set dirty flag back
			dirtyModels.forEach(dirtyModel => dirtyModel.makeDirty());

			throw error;
		}

		// finally, restore models that we had loaded previously
		await Promise.all(modelsToRestore.map(async modelToRestore => {

			// restore the model, forcing a reload. this is important because
			// we know the file has changed on disk after the move and the
			// model might have still existed with the previous state. this
			// ensures we are not tracking a stale state.
			const restoredModel = await this.models.loadOrCreate(modelToRestore.resource, { reload: { async: false } });

			// restore previous dirty content if any and ensure to mark
			// the model as dirty
			if (modelToRestore.snapshot && restoredModel.isResolved()) {
				this.modelService.updateModel(restoredModel.textEditorModel, createTextBufferFactoryFromSnapshot(modelToRestore.snapshot));

				restoredModel.makeDirty();
			}
		}));

471 472 473
		// after event
		this._onDidRunOperation.fire(new FileOperationDidRunEvent(FileOperation.MOVE, target, source));

474 475 476 477 478 479 480
		return stat;
	}

	//#endregion

	//#region save/revert

481
	async save(resource: URI, options?: ITextFileSaveOptions): Promise<boolean> {
482 483

		// Run a forced save if we detect the file is not dirty so that save participants can still run
B
Benjamin Pasero 已提交
484
		if (options?.force && this.fileService.canHandleResource(resource) && !this.isDirty(resource)) {
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
			const model = this._models.get(resource);
			if (model) {
				options.reason = SaveReason.EXPLICIT;

				await model.save(options);

				return !model.isDirty();
			}
		}

		const result = await this.saveAll([resource], options);

		return result.results.length === 1 && !!result.results[0].success;
	}

500 501 502
	saveAll(includeUntitled?: boolean, options?: ITextFileSaveOptions): Promise<ITextFileOperationResult>;
	saveAll(resources: URI[], options?: ITextFileSaveOptions): Promise<ITextFileOperationResult>;
	saveAll(arg1?: boolean | URI[], options?: ITextFileSaveOptions): Promise<ITextFileOperationResult> {
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525

		// get all dirty
		let toSave: URI[] = [];
		if (Array.isArray(arg1)) {
			toSave = this.getDirty(arg1);
		} else {
			toSave = this.getDirty();
		}

		// split up between files and untitled
		const filesToSave: URI[] = [];
		const untitledToSave: URI[] = [];
		toSave.forEach(resourceToSave => {
			if ((Array.isArray(arg1) || arg1 === true /* includeUntitled */) && resourceToSave.scheme === Schemas.untitled) {
				untitledToSave.push(resourceToSave);
			} else {
				filesToSave.push(resourceToSave);
			}
		});

		return this.doSaveAll(filesToSave, untitledToSave, options);
	}

526
	private async doSaveAll(fileResources: URI[], untitledResources: URI[], options?: ITextFileSaveOptions): Promise<ITextFileOperationResult> {
527 528 529 530 531 532 533

		// Handle files first that can just be saved
		const result = await this.doSaveAllFiles(fileResources, options);

		// Preflight for untitled to handle cancellation from the dialog
		const targetsForUntitled: URI[] = [];
		for (const untitled of untitledResources) {
534
			if (this.untitledTextEditorService.exists(untitled)) {
535 536 537
				let targetUri: URI;

				// Untitled with associated file path don't need to prompt
538
				if (this.untitledTextEditorService.hasAssociatedFilePath(untitled)) {
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
					targetUri = toLocalResource(untitled, this.environmentService.configuration.remoteAuthority);
				}

				// Otherwise ask user
				else {
					const targetPath = await this.promptForPath(untitled, this.suggestFileName(untitled));
					if (!targetPath) {
						return { results: [...fileResources, ...untitledResources].map(r => ({ source: r })) };
					}

					targetUri = targetPath;
				}

				targetsForUntitled.push(targetUri);
			}
		}

		// Handle untitled
		await Promise.all(targetsForUntitled.map(async (target, index) => {
			const uri = await this.saveAs(untitledResources[index], target);

			result.results.push({
				source: untitledResources[index],
				target: uri,
				success: !!uri
			});
		}));

		return result;
	}

570
	protected async promptForPath(resource: URI, defaultUri: URI, availableFileSystems?: readonly string[]): Promise<URI | undefined> {
571 572 573 574 575 576 577

		// Help user to find a name for the file by opening it first
		await this.editorService.openEditor({ resource, options: { revealIfOpened: true, preserveFocus: true } });

		return this.fileDialogService.pickFileToSave(this.getSaveDialogOptions(defaultUri, availableFileSystems));
	}

578
	private getSaveDialogOptions(defaultUri: URI, availableFileSystems?: readonly string[]): ISaveDialogOptions {
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
		const options: ISaveDialogOptions = {
			defaultUri,
			title: nls.localize('saveAsTitle', "Save As"),
			availableFileSystems,
		};

		// Filters are only enabled on Windows where they work properly
		if (!platform.isWindows) {
			return options;
		}

		interface IFilter { name: string; extensions: string[]; }

		// Build the file filter by using our known languages
		const ext: string | undefined = defaultUri ? extname(defaultUri) : undefined;
		let matchingFilter: IFilter | undefined;
		const filters: IFilter[] = coalesce(this.modeService.getRegisteredLanguageNames().map(languageName => {
			const extensions = this.modeService.getExtensions(languageName);
			if (!extensions || !extensions.length) {
				return null;
			}

			const filter: IFilter = { name: languageName, extensions: extensions.slice(0, 10).map(e => trim(e, '.')) };

			if (ext && extensions.indexOf(ext) >= 0) {
				matchingFilter = filter;

				return null; // matching filter will be added last to the top
			}

			return filter;
		}));

		// Filters are a bit weird on Windows, based on having a match or not:
		// Match: we put the matching filter first so that it shows up selected and the all files last
		// No match: we put the all files filter first
		const allFilesFilter = { name: nls.localize('allFiles', "All Files"), extensions: ['*'] };
		if (matchingFilter) {
			filters.unshift(matchingFilter);
			filters.unshift(allFilesFilter);
		} else {
			filters.unshift(allFilesFilter);
		}

		// Allow to save file without extension
		filters.push({ name: nls.localize('noExt', "No Extension"), extensions: [''] });

		options.filters = filters;

		return options;
	}

631
	private async doSaveAllFiles(resources?: URI[], options: ITextFileSaveOptions = Object.create(null)): Promise<ITextFileOperationResult> {
632 633 634 635 636 637 638 639 640 641
		const dirtyFileModels = this.getDirtyFileModels(Array.isArray(resources) ? resources : undefined /* Save All */)
			.filter(model => {
				if ((model.hasState(ModelState.CONFLICT) || model.hasState(ModelState.ERROR)) && (options.reason === SaveReason.AUTO || options.reason === SaveReason.FOCUS_CHANGE || options.reason === SaveReason.WINDOW_CHANGE)) {
					return false; // if model is in save conflict or error, do not save unless save reason is explicit or not provided at all
				}

				return true;
			});

		const mapResourceToResult = new ResourceMap<IResult>();
642 643 644
		dirtyFileModels.forEach(dirtyModel => {
			mapResourceToResult.set(dirtyModel.resource, {
				source: dirtyModel.resource
645 646 647 648 649 650 651
			});
		});

		await Promise.all(dirtyFileModels.map(async model => {
			await model.save(options);

			if (!model.isDirty()) {
652
				const result = mapResourceToResult.get(model.resource);
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
				if (result) {
					result.success = true;
				}
			}
		}));

		return { results: mapResourceToResult.values() };
	}

	private getFileModels(arg1?: URI | URI[]): ITextFileEditorModel[] {
		if (Array.isArray(arg1)) {
			const models: ITextFileEditorModel[] = [];
			arg1.forEach(resource => {
				models.push(...this.getFileModels(resource));
			});

			return models;
		}

		return this._models.getAll(arg1);
	}

	private getDirtyFileModels(resources?: URI | URI[]): ITextFileEditorModel[] {
		return this.getFileModels(resources).filter(model => model.isDirty());
	}

679
	async saveAs(resource: URI, targetResource?: URI, options?: ITextFileSaveOptions): Promise<URI | undefined> {
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699

		// Get to target resource
		if (!targetResource) {
			let dialogPath = resource;
			if (resource.scheme === Schemas.untitled) {
				dialogPath = this.suggestFileName(resource);
			}

			targetResource = await this.promptForPath(resource, dialogPath, options ? options.availableFileSystems : undefined);
		}

		if (!targetResource) {
			return; // user canceled
		}

		// Just save if target is same as models own resource
		if (resource.toString() === targetResource.toString()) {
			await this.save(resource, options);

			return resource;
B
Benjamin Pasero 已提交
700
		}
701

702 703
		// Do it
		return this.doSaveAs(resource, targetResource, options);
704 705
	}

706
	private async doSaveAs(resource: URI, target: URI, options?: ITextFileSaveOptions): Promise<URI> {
707 708

		// Retrieve text model from provided resource if any
709
		let model: ITextFileEditorModel | UntitledTextEditorModel | undefined;
710 711
		if (this.fileService.canHandleResource(resource)) {
			model = this._models.get(resource);
712 713
		} else if (resource.scheme === Schemas.untitled && this.untitledTextEditorService.exists(resource)) {
			model = await this.untitledTextEditorService.loadOrCreate({ resource });
714 715 716 717 718 719
		}

		// We have a model: Use it (can be null e.g. if this file is binary and not a text file or was never opened before)
		let result: boolean;
		if (model) {
			result = await this.doSaveTextFileAs(model, resource, target, options);
720 721
		}

722 723 724 725 726
		// Otherwise we can only copy
		else {
			await this.fileService.copy(resource, target);

			result = true;
727 728
		}

729 730 731
		// Return early if the operation was not running
		if (!result) {
			return target;
732 733
		}

734 735 736 737 738
		// Revert the source
		await this.revert(resource);

		return target;
	}
739

740
	private async doSaveTextFileAs(sourceModel: ITextFileEditorModel | UntitledTextEditorModel, resource: URI, target: URI, options?: ITextFileSaveOptions): Promise<boolean> {
741 742 743 744

		// Prefer an existing model if it is already loaded for the given target resource
		let targetExists: boolean = false;
		let targetModel = this.models.get(target);
B
Benjamin Pasero 已提交
745
		if (targetModel?.isResolved()) {
746 747 748 749 750 751 752 753 754 755
			targetExists = true;
		}

		// Otherwise create the target file empty if it does not exist already and resolve it from there
		else {
			targetExists = await this.fileService.exists(target);

			// create target model adhoc if file does not exist yet
			if (!targetExists) {
				await this.create(target, '');
756
			}
757

758 759 760 761 762 763 764 765 766 767
			targetModel = await this.models.loadOrCreate(target);
		}

		try {

			// Confirm to overwrite if we have an untitled file with associated file where
			// the file actually exists on disk and we are instructed to save to that file
			// path. This can happen if the file was created after the untitled file was opened.
			// See https://github.com/Microsoft/vscode/issues/67946
			let write: boolean;
768
			if (sourceModel instanceof UntitledTextEditorModel && sourceModel.hasAssociatedFilePath && targetExists && isEqual(target, toLocalResource(sourceModel.resource, this.environmentService.configuration.remoteAuthority))) {
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
				write = await this.confirmOverwrite(target);
			} else {
				write = true;
			}

			if (!write) {
				return false;
			}

			// take over model value, encoding and mode (only if more specific) from source model
			targetModel.updatePreferredEncoding(sourceModel.getEncoding());
			if (sourceModel.isResolved() && targetModel.isResolved()) {
				this.modelService.updateModel(targetModel.textEditorModel, createTextBufferFactoryFromSnapshot(sourceModel.createSnapshot()));

				const sourceMode = sourceModel.textEditorModel.getLanguageIdentifier();
				const targetMode = targetModel.textEditorModel.getLanguageIdentifier();
				if (sourceMode.language !== PLAINTEXT_MODE_ID && targetMode.language === PLAINTEXT_MODE_ID) {
					targetModel.textEditorModel.setMode(sourceMode); // only use if more specific than plain/text
				}
			}

			// save model
			await targetModel.save(options);

			return true;
		} catch (error) {

			// binary model: delete the file and run the operation again
			if (
				(<TextFileOperationError>error).textFileOperationResult === TextFileOperationResult.FILE_IS_BINARY ||
				(<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_TOO_LARGE
			) {
				await this.fileService.del(target);

				return this.doSaveTextFileAs(sourceModel, resource, target, options);
			}

			throw error;
		}
	}

810 811 812
	private async confirmOverwrite(resource: URI): Promise<boolean> {
		const confirm: IConfirmation = {
			message: nls.localize('confirmOverwrite', "'{0}' already exists. Do you want to replace it?", basename(resource)),
I
isidor 已提交
813
			detail: nls.localize('irreversible', "A file or folder with the name '{0}' already exists in the folder '{1}'. Replacing it will overwrite its current contents.", basename(resource), basename(dirname(resource))),
814 815 816 817 818 819 820
			primaryButton: nls.localize({ key: 'replaceButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Replace"),
			type: 'warning'
		};

		return (await this.dialogService.confirm(confirm)).confirmed;
	}

821
	private suggestFileName(untitledResource: URI): URI {
822
		const untitledFileName = this.untitledTextEditorService.suggestFileName(untitledResource);
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
		const remoteAuthority = this.environmentService.configuration.remoteAuthority;
		const schemeFilter = remoteAuthority ? Schemas.vscodeRemote : Schemas.file;

		const lastActiveFile = this.historyService.getLastActiveFile(schemeFilter);
		if (lastActiveFile) {
			const lastDir = dirname(lastActiveFile);
			return joinPath(lastDir, untitledFileName);
		}

		const lastActiveFolder = this.historyService.getLastActiveWorkspaceRoot(schemeFilter);
		if (lastActiveFolder) {
			return joinPath(lastActiveFolder, untitledFileName);
		}

		return untitledResource.with({ path: untitledFileName });
	}

	async revert(resource: URI, options?: IRevertOptions): Promise<boolean> {
		const result = await this.revertAll([resource], options);

		return result.results.length === 1 && !!result.results[0].success;
	}

	async revertAll(resources?: URI[], options?: IRevertOptions): Promise<ITextFileOperationResult> {

		// Revert files first
		const revertOperationResult = await this.doRevertAllFiles(resources, options);

		// Revert untitled
852
		const untitledReverted = this.untitledTextEditorService.revertAll(resources);
853 854 855 856 857 858
		untitledReverted.forEach(untitled => revertOperationResult.results.push({ source: untitled, success: true }));

		return revertOperationResult;
	}

	private async doRevertAllFiles(resources?: URI[], options?: IRevertOptions): Promise<ITextFileOperationResult> {
B
Benjamin Pasero 已提交
859
		const fileModels = options?.force ? this.getFileModels(resources) : this.getDirtyFileModels(resources);
860 861

		const mapResourceToResult = new ResourceMap<IResult>();
862 863 864
		fileModels.forEach(fileModel => {
			mapResourceToResult.set(fileModel.resource, {
				source: fileModel.resource
865 866 867 868 869
			});
		});

		await Promise.all(fileModels.map(async model => {
			try {
870
				await model.revert(options);
871 872

				if (!model.isDirty()) {
873
					const result = mapResourceToResult.get(model.resource);
874 875 876 877 878 879 880 881
					if (result) {
						result.success = true;
					}
				}
			} catch (error) {

				// FileNotFound means the file got deleted meanwhile, so still record as successful revert
				if ((<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
882
					const result = mapResourceToResult.get(model.resource);
883 884 885 886 887 888 889 890 891
					if (result) {
						result.success = true;
					}
				}

				// Otherwise bubble up the error
				else {
					throw error;
				}
892
			}
893 894 895 896 897 898 899 900
		}));

		return { results: mapResourceToResult.values() };
	}

	getDirty(resources?: URI[]): URI[] {

		// Collect files
901
		const dirty = this.getDirtyFileModels(resources).map(dirtyFileModel => dirtyFileModel.resource);
902 903

		// Add untitled ones
904
		dirty.push(...this.untitledTextEditorService.getDirty(resources));
905 906 907 908 909 910 911 912 913

		return dirty;
	}

	isDirty(resource?: URI): boolean {

		// Check for dirty file
		if (this._models.getAll(resource).some(model => model.isDirty())) {
			return true;
914 915
		}

916
		// Check for dirty untitled
917
		return this.untitledTextEditorService.getDirty().some(dirty => !resource || dirty.toString() === resource.toString());
918 919 920 921 922 923 924 925 926 927 928 929
	}

	//#endregion

	dispose(): void {

		// Clear all caches
		this._models.clear();

		super.dispose();
	}
}