textFileService.ts 22.1 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

J
Johannes Rieken 已提交
7
import { TPromise } from 'vs/base/common/winjs.base';
E
Erich Gamma 已提交
8
import URI from 'vs/base/common/uri';
9
import paths = require('vs/base/common/paths');
10
import DOM = require('vs/base/browser/dom');
11
import errors = require('vs/base/common/errors');
12
import objects = require('vs/base/common/objects');
J
Johannes Rieken 已提交
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
import Event, { Emitter } from 'vs/base/common/event';
import { IResult, ITextFileOperationResult, ITextFileService, IRawTextContent, IAutoSaveConfiguration, AutoSaveMode, SaveReason, ITextFileEditorModelManager, ITextFileEditorModel, ISaveOptions } from 'vs/workbench/services/textfile/common/textfiles';
import { ConfirmResult } from 'vs/workbench/common/editor';
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IFileService, IResolveContentOptions, IFilesConfiguration, IFileOperationResult, FileOperationResult, AutoSaveConfiguration } from 'vs/platform/files/common/files';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService';
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { UntitledEditorModel } from 'vs/workbench/common/editor/untitledEditorModel';
import { BinaryEditorModel } from 'vs/workbench/common/editor/binaryEditorModel';
import { TextFileEditorModelManager } from 'vs/workbench/services/textfile/common/textFileEditorModelManager';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
29
import { IBackupService } from 'vs/platform/backup/common/backup';
E
Erich Gamma 已提交
30 31 32 33 34 35 36

/**
 * The workbench file service implementation implements the raw file service spec and adds additional methods on top.
 *
 * It also adds diagnostics and logging around file system operations.
 */
export abstract class TextFileService implements ITextFileService {
37

38
	public _serviceBrand: any;
E
Erich Gamma 已提交
39

B
Benjamin Pasero 已提交
40
	private toUnbind: IDisposable[];
41 42
	private _models: TextFileEditorModelManager;

43 44 45
	private _onFilesAssociationChange: Emitter<void>;
	private currentFilesAssociationConfig: { [key: string]: string; };

D
Daniel Imms 已提交
46
	private configuredHotExit: boolean;
47

48
	private _onAutoSaveConfigurationChange: Emitter<IAutoSaveConfiguration>;
49
	private configuredAutoSaveDelay: number;
50 51
	private configuredAutoSaveOnFocusChange: boolean;
	private configuredAutoSaveOnWindowChange: boolean;
E
Erich Gamma 已提交
52 53

	constructor(
54 55
		@ILifecycleService private lifecycleService: ILifecycleService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
56
		@IConfigurationService private configurationService: IConfigurationService,
57
		@ITelemetryService private telemetryService: ITelemetryService,
58
		@IEditorGroupService private editorGroupService: IEditorGroupService,
59
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
B
Benjamin Pasero 已提交
60
		@IFileService protected fileService: IFileService,
61
		@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
62 63
		@IInstantiationService private instantiationService: IInstantiationService,
		@IBackupService private backupService: IBackupService
E
Erich Gamma 已提交
64
	) {
B
Benjamin Pasero 已提交
65
		this.toUnbind = [];
66

67
		this._onAutoSaveConfigurationChange = new Emitter<IAutoSaveConfiguration>();
68 69 70 71 72
		this.toUnbind.push(this._onAutoSaveConfigurationChange);

		this._onFilesAssociationChange = new Emitter<void>();
		this.toUnbind.push(this._onFilesAssociationChange);

73
		this._models = this.instantiationService.createInstance(TextFileEditorModelManager);
74 75

		const configuration = this.configurationService.getConfiguration<IFilesConfiguration>();
76 77
		this.currentFilesAssociationConfig = configuration && configuration.files && configuration.files.associations;

78 79 80
		this.onConfigurationChange(configuration);

		this.telemetryService.publicLog('autoSave', this.getAutoSaveConfiguration());
81 82

		this.registerListeners();
E
Erich Gamma 已提交
83 84
	}

85 86 87 88
	public get models(): ITextFileEditorModelManager {
		return this._models;
	}

89
	abstract resolveTextContent(resource: URI, options?: IResolveContentOptions): TPromise<IRawTextContent>;
A
Alex Dima 已提交
90

91
	abstract promptForPath(defaultPath?: string): string;
92

93
	abstract confirmSave(resources?: URI[]): ConfirmResult;
94

95 96 97 98
	public get onAutoSaveConfigurationChange(): Event<IAutoSaveConfiguration> {
		return this._onAutoSaveConfigurationChange.event;
	}

99 100 101 102
	public get onFilesAssociationChange(): Event<void> {
		return this._onFilesAssociationChange.event;
	}

103
	private registerListeners(): void {
104

105 106 107 108
		// Lifecycle
		this.lifecycleService.onWillShutdown(event => event.veto(this.beforeShutdown()));
		this.lifecycleService.onShutdown(this.dispose, this);

109
		// Configuration changes
B
Benjamin Pasero 已提交
110
		this.toUnbind.push(this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationChange(e.config)));
111 112

		// Application & Editor focus change
113 114
		this.toUnbind.push(DOM.addDisposableListener(window, 'blur', () => this.onWindowFocusLost()));
		this.toUnbind.push(DOM.addDisposableListener(window, 'blur', () => this.onEditorFocusChanged(), true));
B
Benjamin Pasero 已提交
115
		this.toUnbind.push(this.editorGroupService.onEditorsChanged(() => this.onEditorFocusChanged()));
116 117
	}

118 119
	private beforeShutdown(): boolean | TPromise<boolean> {

120 121 122
		// If hot exit is enabled then save the dirty files in the workspace and then exit
		if (this.configuredHotExit) {
			// Only remove the workspace from the backup service if it's not the last one or it's not dirty
123 124
			if (this.backupService.getWorkspaceBackupPaths().length > 1 || this.getDirty().length === 0) {
				this.backupService.removeWorkspaceBackupPath(this.contextService.getWorkspace().resource.fsPath);
125
			} else {
126 127
				// TODO: Better error handling here? Perhaps present confirm if there was an error?
				return this.backupAll().then(() => false); // the backup will be restored, no veto
128
			}
129
		}
130

131 132
		// Dirty files need treatment on shutdown
		if (this.getDirty().length) {
133 134 135 136 137 138 139
			// If auto save is enabled, save all files and then check again for dirty files
			if (this.getAutoSaveMode() !== AutoSaveMode.OFF) {
				return this.saveAll(false /* files only */).then(() => {
					if (this.getDirty().length) {
						return this.confirmBeforeShutdown(); // we still have dirty files around, so confirm normally
					}

D
Daniel Imms 已提交
140 141 142
					return this.fileService.discardBackups().then(() => {
						return false; // all good, no veto
					});
143 144 145 146 147 148 149
				});
			}

			// Otherwise just confirm what to do
			return this.confirmBeforeShutdown();
		}

D
Daniel Imms 已提交
150 151 152
		return this.fileService.discardBackups().then(() => {
			return false; // no veto
		});
153 154
	}

155 156 157 158 159 160 161 162 163 164
	private confirmBeforeShutdown(): boolean | TPromise<boolean> {
		const confirm = this.confirmSave();

		// Save
		if (confirm === ConfirmResult.SAVE) {
			return this.saveAll(true /* includeUntitled */).then(result => {
				if (result.results.some(r => !r.success)) {
					return true; // veto if some saves failed
				}

D
Daniel Imms 已提交
165 166 167
				return this.fileService.discardBackups().then(() => {
					return false; // no veto
				});
168 169 170 171 172
			});
		}

		// Don't Save
		else if (confirm === ConfirmResult.DONT_SAVE) {
D
Daniel Imms 已提交
173 174 175
			return this.fileService.discardBackups().then(() => {
				return false; // no veto
			});
176 177 178 179 180 181 182 183
		}

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

184 185
	private onWindowFocusLost(): void {
		if (this.configuredAutoSaveOnWindowChange && this.isDirty()) {
B
Benjamin Pasero 已提交
186
			this.saveAll(void 0, SaveReason.WINDOW_CHANGE).done(null, errors.onUnexpectedError);
187 188 189 190 191
		}
	}

	private onEditorFocusChanged(): void {
		if (this.configuredAutoSaveOnFocusChange && this.isDirty()) {
B
Benjamin Pasero 已提交
192
			this.saveAll(void 0, SaveReason.FOCUS_CHANGE).done(null, errors.onUnexpectedError);
193
		}
E
Erich Gamma 已提交
194 195
	}

196
	private onConfigurationChange(configuration: IFilesConfiguration): void {
197
		const wasAutoSaveEnabled = (this.getAutoSaveMode() !== AutoSaveMode.OFF);
198

199
		const autoSaveMode = (configuration && configuration.files && configuration.files.autoSave) || AutoSaveConfiguration.OFF;
200
		switch (autoSaveMode) {
201
			case AutoSaveConfiguration.AFTER_DELAY:
202 203
				this.configuredAutoSaveDelay = configuration && configuration.files && configuration.files.autoSaveDelay;
				this.configuredAutoSaveOnFocusChange = false;
204
				this.configuredAutoSaveOnWindowChange = false;
205 206
				break;

207
			case AutoSaveConfiguration.ON_FOCUS_CHANGE:
208 209
				this.configuredAutoSaveDelay = void 0;
				this.configuredAutoSaveOnFocusChange = true;
210 211 212 213 214 215 216
				this.configuredAutoSaveOnWindowChange = false;
				break;

			case AutoSaveConfiguration.ON_WINDOW_CHANGE:
				this.configuredAutoSaveDelay = void 0;
				this.configuredAutoSaveOnFocusChange = false;
				this.configuredAutoSaveOnWindowChange = true;
217 218 219 220 221
				break;

			default:
				this.configuredAutoSaveDelay = void 0;
				this.configuredAutoSaveOnFocusChange = false;
222
				this.configuredAutoSaveOnWindowChange = false;
223 224
				break;
		}
225

226 227
		// Emit as event
		this._onAutoSaveConfigurationChange.fire(this.getAutoSaveConfiguration());
228

229
		// save all dirty when enabling auto save
230
		if (!wasAutoSaveEnabled && this.getAutoSaveMode() !== AutoSaveMode.OFF) {
231
			this.saveAll().done(null, errors.onUnexpectedError);
232
		}
233

234 235
		// Hot exit is disabled for empty workspaces
		this.configuredHotExit = this.contextService.getWorkspace() && configuration && configuration.files && configuration.files.hotExit;
236

237 238 239 240 241 242
		// Check for change in files associations
		const filesAssociation = configuration && configuration.files && configuration.files.associations;
		if (!objects.equals(this.currentFilesAssociationConfig, filesAssociation)) {
			this.currentFilesAssociationConfig = filesAssociation;
			this._onFilesAssociationChange.fire();
		}
E
Erich Gamma 已提交
243 244
	}

245
	public getDirty(resources?: URI[]): URI[] {
246 247 248 249 250 251 252 253 254 255 256 257 258

		// Collect files
		const dirty = this.getDirtyFileModels(resources).map(m => m.getResource());

		// Add untitled ones
		if (!resources) {
			dirty.push(...this.untitledEditorService.getDirty());
		} else {
			const dirtyUntitled = resources.map(r => this.untitledEditorService.get(r)).filter(u => u && u.isDirty()).map(u => u.getResource());
			dirty.push(...dirtyUntitled);
		}

		return dirty;
E
Erich Gamma 已提交
259 260 261
	}

	public isDirty(resource?: URI): boolean {
262 263

		// Check for dirty file
264
		if (this._models.getAll(resource).some(model => model.isDirty())) {
265 266 267 268 269
			return true;
		}

		// Check for dirty untitled
		return this.untitledEditorService.getDirty().some(dirty => !resource || dirty.toString() === resource.toString());
E
Erich Gamma 已提交
270 271
	}

272 273 274 275 276 277 278
	public save(resource: URI, options?: ISaveOptions): TPromise<boolean> {

		// touch resource if options tell so and file is not dirty
		if (options && options.force && resource.scheme === 'file' && !this.isDirty(resource)) {
			return this.fileService.touchFile(resource).then(() => true);
		}

279
		return this.saveAll([resource]).then(result => result.results.length === 1 && result.results[0].success);
E
Erich Gamma 已提交
280 281
	}

B
Benjamin Pasero 已提交
282 283 284
	public saveAll(includeUntitled?: boolean, reason?: SaveReason): TPromise<ITextFileOperationResult>;
	public saveAll(resources: URI[], reason?: SaveReason): TPromise<ITextFileOperationResult>;
	public saveAll(arg1?: any, reason?: SaveReason): TPromise<ITextFileOperationResult> {
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304

		// 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(s => {
			if (s.scheme === 'file') {
				filesToSave.push(s);
			} else if ((Array.isArray(arg1) || arg1 === true /* includeUntitled */) && s.scheme === 'untitled') {
				untitledToSave.push(s);
			}
		});

B
Benjamin Pasero 已提交
305
		return this.doSaveAll(filesToSave, untitledToSave, reason);
306 307
	}

B
Benjamin Pasero 已提交
308
	private doSaveAll(fileResources: URI[], untitledResources: URI[], reason?: SaveReason): TPromise<ITextFileOperationResult> {
309 310

		// Handle files first that can just be saved
B
Benjamin Pasero 已提交
311
		return this.doSaveAllFiles(fileResources, reason).then(result => {
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 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362

			// Preflight for untitled to handle cancellation from the dialog
			const targetsForUntitled: URI[] = [];
			for (let i = 0; i < untitledResources.length; i++) {
				const untitled = this.untitledEditorService.get(untitledResources[i]);
				if (untitled) {
					let targetPath: string;

					// Untitled with associated file path don't need to prompt
					if (this.untitledEditorService.hasAssociatedFilePath(untitled.getResource())) {
						targetPath = untitled.getResource().fsPath;
					}

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

					targetsForUntitled.push(URI.file(targetPath));
				}
			}

			// Handle untitled
			const untitledSaveAsPromises: TPromise<void>[] = [];
			targetsForUntitled.forEach((target, index) => {
				const untitledSaveAsPromise = this.saveAs(untitledResources[index], target).then(uri => {
					result.results.push({
						source: untitledResources[index],
						target: uri,
						success: !!uri
					});
				});

				untitledSaveAsPromises.push(untitledSaveAsPromise);
			});

			return TPromise.join(untitledSaveAsPromises).then(() => {
				return result;
			});
		});
	}

B
Benjamin Pasero 已提交
363
	private doSaveAllFiles(arg1?: any /* URI[] */, reason?: SaveReason): TPromise<ITextFileOperationResult> {
364
		const dirtyFileModels = this.getDirtyFileModels(Array.isArray(arg1) ? arg1 : void 0 /* Save All */);
E
Erich Gamma 已提交
365

366 367
		const mapResourceToResult: { [resource: string]: IResult } = Object.create(null);
		dirtyFileModels.forEach(m => {
E
Erich Gamma 已提交
368 369 370 371 372
			mapResourceToResult[m.getResource().toString()] = {
				source: m.getResource()
			};
		});

373
		return TPromise.join(dirtyFileModels.map(model => {
B
Benjamin Pasero 已提交
374
			return model.save({ reason }).then(() => {
E
Erich Gamma 已提交
375 376 377 378
				if (!model.isDirty()) {
					mapResourceToResult[model.getResource().toString()].success = true;
				}
			});
379
		})).then(r => {
E
Erich Gamma 已提交
380
			return {
381
				results: Object.keys(mapResourceToResult).map(k => mapResourceToResult[k])
E
Erich Gamma 已提交
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
	/**
	 * Performs an immedate backup of all dirty file and untitled models.
	 */
	private backupAll(): TPromise<void> {
		const toBackup = this.getDirty();

		// split up between files and untitled
		const filesToBackup: URI[] = [];
		const untitledToBackup: URI[] = [];
		toBackup.forEach(s => {
			if (s.scheme === 'file') {
				filesToBackup.push(s);
			} else if (s.scheme === 'untitled') {
				untitledToBackup.push(s);
			}
		});

		return this.doBackupAll(filesToBackup, untitledToBackup);
	}

	private doBackupAll(fileResources: URI[], untitledResources: URI[]): TPromise<void> {
		// Handle file resources first
		const dirtyFileModels = this.getDirtyFileModels(fileResources);

		const mapResourceToResult: { [resource: string]: IResult } = Object.create(null);
		dirtyFileModels.forEach(m => {
			mapResourceToResult[m.getResource().toString()] = {
				source: m.getResource()
			};
		});

		return TPromise.join(dirtyFileModels.map(model => {
			return model.backup().then(() => {
				mapResourceToResult[model.getResource().toString()].success = true;
			});
		})).then(result => {
			// Handle untitled resources
			const untitledModelPromises = untitledResources.map(untitledResource => this.untitledEditorService.get(untitledResource))
				.filter(untitled => !!untitled)
				.map(untitled => untitled.resolve());

			return TPromise.join(untitledModelPromises).then(untitledModels => {
				const untitledBackupPromises = untitledModels.map(model => model.backup());
				return TPromise.join(untitledBackupPromises).then(() => void 0);
			});
		});
	}

434 435 436
	private getFileModels(resources?: URI[]): ITextFileEditorModel[];
	private getFileModels(resource?: URI): ITextFileEditorModel[];
	private getFileModels(arg1?: any): ITextFileEditorModel[] {
E
Erich Gamma 已提交
437
		if (Array.isArray(arg1)) {
438
			const models: ITextFileEditorModel[] = [];
439
			(<URI[]>arg1).forEach(resource => {
E
Erich Gamma 已提交
440 441 442 443 444 445
				models.push(...this.getFileModels(resource));
			});

			return models;
		}

446
		return this._models.getAll(<URI>arg1);
E
Erich Gamma 已提交
447 448
	}

449 450 451
	private getDirtyFileModels(resources?: URI[]): ITextFileEditorModel[];
	private getDirtyFileModels(resource?: URI): ITextFileEditorModel[];
	private getDirtyFileModels(arg1?: any): ITextFileEditorModel[] {
452
		return this.getFileModels(arg1).filter(model => model.isDirty());
E
Erich Gamma 已提交
453 454
	}

455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
	public saveAs(resource: URI, target?: URI): TPromise<URI> {

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

			const pathRaw = this.promptForPath(dialogPath);
			if (pathRaw) {
				target = URI.file(pathRaw);
			}
		}

		if (!target) {
			return TPromise.as(null); // user canceled
		}

		// Just save if target is same as models own resource
		if (resource.toString() === target.toString()) {
			return this.save(resource).then(() => resource);
		}

		// Do it
		return this.doSaveAs(resource, target);
	}

	private doSaveAs(resource: URI, target?: URI): TPromise<URI> {

		// Retrieve text model from provided resource if any
486
		let modelPromise: TPromise<ITextFileEditorModel | UntitledEditorModel> = TPromise.as(null);
487
		if (resource.scheme === 'file') {
488
			modelPromise = TPromise.as(this._models.get(resource));
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
		} else if (resource.scheme === 'untitled') {
			const untitled = this.untitledEditorService.get(resource);
			if (untitled) {
				modelPromise = untitled.resolve();
			}
		}

		return modelPromise.then(model => {

			// 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)
			if (model) {
				return this.doSaveTextFileAs(model, resource, target);
			}

			// Otherwise we can only copy
			return this.fileService.copyFile(resource, target);
		}).then(() => {

			// Revert the source
			return this.revert(resource).then(() => {

				// Done: return target
				return target;
			});
		});
	}

516
	private doSaveTextFileAs(sourceModel: ITextFileEditorModel | UntitledEditorModel, resource: URI, target: URI): TPromise<void> {
517 518 519
		// create the target file empty if it does not exist already
		return this.fileService.resolveFile(target).then(stat => stat, () => null).then(stat => stat || this.fileService.createFile(target)).then(stat => {
			// resolve a model for the file (which can be binary if the file is not a text file)
520
			return this.editorService.resolveEditorModel({ resource: target }).then((targetModel: ITextFileEditorModel) => {
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
				// binary model: delete the file and run the operation again
				if (targetModel instanceof BinaryEditorModel) {
					return this.fileService.del(target).then(() => this.doSaveTextFileAs(sourceModel, resource, target));
				}

				// text model: take over encoding and model value from source model
				targetModel.updatePreferredEncoding(sourceModel.getEncoding());
				targetModel.textEditorModel.setValue(sourceModel.getValue());

				// save model
				return targetModel.save();
			});
		});
	}

	private suggestFileName(untitledResource: URI): string {
		const workspace = this.contextService.getWorkspace();
		if (workspace) {
			return URI.file(paths.join(workspace.resource.fsPath, this.untitledEditorService.get(untitledResource).suggestFileName())).fsPath;
		}

		return this.untitledEditorService.get(untitledResource).suggestFileName();
	}
E
Erich Gamma 已提交
544 545

	public revert(resource: URI, force?: boolean): TPromise<boolean> {
546
		return this.revertAll([resource], force).then(result => result.results.length === 1 && result.results[0].success);
E
Erich Gamma 已提交
547 548 549
	}

	public revertAll(resources?: URI[], force?: boolean): TPromise<ITextFileOperationResult> {
550 551 552 553 554 555 556 557 558 559 560 561 562

		// Revert files first
		return this.doRevertAllFiles(resources, force).then(operation => {

			// Revert untitled
			const reverted = this.untitledEditorService.revertAll(resources);
			reverted.forEach(res => operation.results.push({ source: res, success: true }));

			return operation;
		});
	}

	private doRevertAllFiles(resources?: URI[], force?: boolean): TPromise<ITextFileOperationResult> {
563
		const fileModels = force ? this.getFileModels(resources) : this.getDirtyFileModels(resources);
E
Erich Gamma 已提交
564

565 566
		const mapResourceToResult: { [resource: string]: IResult } = Object.create(null);
		fileModels.forEach(m => {
E
Erich Gamma 已提交
567 568 569 570 571
			mapResourceToResult[m.getResource().toString()] = {
				source: m.getResource()
			};
		});

572
		return TPromise.join(fileModels.map(model => {
E
Erich Gamma 已提交
573 574 575 576
			return model.revert().then(() => {
				if (!model.isDirty()) {
					mapResourceToResult[model.getResource().toString()].success = true;
				}
577
			}, error => {
E
Erich Gamma 已提交
578

579
				// FileNotFound means the file got deleted meanwhile, so still record as successful revert
E
Erich Gamma 已提交
580 581 582 583 584 585
				if ((<IFileOperationResult>error).fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
					mapResourceToResult[model.getResource().toString()].success = true;
				}

				// Otherwise bubble up the error
				else {
586
					return TPromise.wrapError(error);
E
Erich Gamma 已提交
587 588
				}
			});
589
		})).then(r => {
590 591 592
			return {
				results: Object.keys(mapResourceToResult).map(k => mapResourceToResult[k])
			};
E
Erich Gamma 已提交
593 594 595
		});
	}

D
Daniel Imms 已提交
596 597 598 599 600 601 602 603
	public backup(resource: URI): void {
		let model = this.getDirtyFileModels(resource);
		if (!model || model.length === 0) {
			return;
		}
		this.fileService.backupFile(resource, model[0].getValue());
	}

604 605 606 607 608
	public getAutoSaveMode(): AutoSaveMode {
		if (this.configuredAutoSaveOnFocusChange) {
			return AutoSaveMode.ON_FOCUS_CHANGE;
		}

609 610 611 612
		if (this.configuredAutoSaveOnWindowChange) {
			return AutoSaveMode.ON_WINDOW_CHANGE;
		}

613
		if (this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0) {
614
			return this.configuredAutoSaveDelay <= 1000 ? AutoSaveMode.AFTER_SHORT_DELAY : AutoSaveMode.AFTER_LONG_DELAY;
615 616 617
		}

		return AutoSaveMode.OFF;
618 619 620 621
	}

	public getAutoSaveConfiguration(): IAutoSaveConfiguration {
		return {
622
			autoSaveDelay: this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0 ? this.configuredAutoSaveDelay : void 0,
623 624
			autoSaveFocusChange: this.configuredAutoSaveOnFocusChange,
			autoSaveApplicationChange: this.configuredAutoSaveOnWindowChange
B
Benjamin Pasero 已提交
625
		};
626 627
	}

E
Erich Gamma 已提交
628
	public dispose(): void {
B
Benjamin Pasero 已提交
629
		this.toUnbind = dispose(this.toUnbind);
E
Erich Gamma 已提交
630 631

		// Clear all caches
632
		this._models.clear();
E
Erich Gamma 已提交
633 634
	}
}