textFileService.ts 24.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';

B
Benjamin Pasero 已提交
7
import * as nls from 'vs/nls';
J
Johannes Rieken 已提交
8
import { TPromise } from 'vs/base/common/winjs.base';
E
Erich Gamma 已提交
9
import URI from 'vs/base/common/uri';
10
import paths = require('vs/base/common/paths');
11
import errors = require('vs/base/common/errors');
12
import objects = require('vs/base/common/objects');
J
Johannes Rieken 已提交
13
import Event, { Emitter } from 'vs/base/common/event';
14 15 16
import platform = require('vs/base/common/platform');
import { IWindowsService } from 'vs/platform/windows/common/windows';
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
J
Johannes Rieken 已提交
17 18
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';
19
import { ILifecycleService, ShutdownReason } from 'vs/platform/lifecycle/common/lifecycle';
J
Johannes Rieken 已提交
20 21 22 23 24
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';
25
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
J
Johannes Rieken 已提交
26 27 28 29 30
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 { TextFileEditorModelManager } from 'vs/workbench/services/textfile/common/textFileEditorModelManager';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
B
Benjamin Pasero 已提交
31
import { IMessageService, Severity } from 'vs/platform/message/common/message';
E
Erich Gamma 已提交
32

33 34 35 36
export interface IBackupResult {
	didBackup: boolean;
}

E
Erich Gamma 已提交
37 38 39 40 41 42
/**
 * 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 {
43

44
	public _serviceBrand: any;
E
Erich Gamma 已提交
45

B
Benjamin Pasero 已提交
46
	private toUnbind: IDisposable[];
47 48
	private _models: TextFileEditorModelManager;

49 50 51
	private _onFilesAssociationChange: Emitter<void>;
	private currentFilesAssociationConfig: { [key: string]: string; };

52
	private _onAutoSaveConfigurationChange: Emitter<IAutoSaveConfiguration>;
53
	private configuredAutoSaveDelay: number;
54 55
	private configuredAutoSaveOnFocusChange: boolean;
	private configuredAutoSaveOnWindowChange: boolean;
E
Erich Gamma 已提交
56

57 58
	private configuredHotExit: boolean;

E
Erich Gamma 已提交
59
	constructor(
60 61
		@ILifecycleService private lifecycleService: ILifecycleService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
62
		@IConfigurationService private configurationService: IConfigurationService,
63
		@ITelemetryService private telemetryService: ITelemetryService,
64
		@IEditorGroupService private editorGroupService: IEditorGroupService,
B
Benjamin Pasero 已提交
65
		@IFileService protected fileService: IFileService,
66
		@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
67
		@IInstantiationService private instantiationService: IInstantiationService,
68 69 70 71
		@IMessageService private messageService: IMessageService,
		@IEnvironmentService protected environmentService: IEnvironmentService,
		@IBackupFileService private backupFileService: IBackupFileService,
		@IWindowsService private windowsService: IWindowsService
E
Erich Gamma 已提交
72
	) {
B
Benjamin Pasero 已提交
73
		this.toUnbind = [];
74

75
		this._onAutoSaveConfigurationChange = new Emitter<IAutoSaveConfiguration>();
76 77 78 79 80
		this.toUnbind.push(this._onAutoSaveConfigurationChange);

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

81
		this._models = this.instantiationService.createInstance(TextFileEditorModelManager);
82 83

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

86 87 88
		this.onConfigurationChange(configuration);

		this.telemetryService.publicLog('autoSave', this.getAutoSaveConfiguration());
89 90

		this.registerListeners();
E
Erich Gamma 已提交
91 92
	}

93 94 95 96
	public get models(): ITextFileEditorModelManager {
		return this._models;
	}

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

99
	abstract promptForPath(defaultPath?: string): string;
100

101
	abstract confirmSave(resources?: URI[]): ConfirmResult;
102

D
Daniel Imms 已提交
103 104
	abstract showHotExitMessage(): void;

105 106 107 108
	public get onAutoSaveConfigurationChange(): Event<IAutoSaveConfiguration> {
		return this._onAutoSaveConfigurationChange.event;
	}

109 110 111 112
	public get onFilesAssociationChange(): Event<void> {
		return this._onFilesAssociationChange.event;
	}

113
	private registerListeners(): void {
114

115
		// Lifecycle
116
		this.lifecycleService.onWillShutdown(event => event.veto(this.beforeShutdown(event.reason)));
117 118
		this.lifecycleService.onShutdown(this.dispose, this);

119
		// Configuration changes
B
Benjamin Pasero 已提交
120
		this.toUnbind.push(this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationChange(e.config)));
121 122
	}

123
	private beforeShutdown(reason: ShutdownReason): boolean | TPromise<boolean> {
B
Benjamin Pasero 已提交
124

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

129
			// If auto save is enabled, save all files and then check again for dirty files
130
			let handleAutoSave: TPromise<URI[] /* remaining dirty resources */>;
131
			if (this.getAutoSaveMode() !== AutoSaveMode.OFF) {
132 133 134
				handleAutoSave = this.saveAll(false /* files only */).then(() => this.getDirty());
			} else {
				handleAutoSave = TPromise.as(dirty);
B
Benjamin Pasero 已提交
135 136
			}

137
			return handleAutoSave.then(dirty => {
138

139 140 141
				// If we still have dirty files, we either have untitled ones or files that cannot be saved
				// or auto save was not enabled and as such we did not save any dirty files to disk automatically
				if (dirty.length) {
B
Benjamin Pasero 已提交
142

143
					// If hot exit is enabled, backup dirty files and allow to exit without confirmation
144
					if (this.isHotExitEnabled) {
D
Daniel Imms 已提交
145 146
						this.showHotExitMessage();

147
						return this.backupBeforeShutdown(dirty, this.models, reason).then(result => {
148 149 150 151 152 153 154 155 156
							if (result.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();
						}, errors => {
							const firstError = errors[0];
							this.messageService.show(Severity.Error, nls.localize('files.backup.failSave', "Files could not be backed up (Error: {0}), try saving your files to exit.", firstError.message));
157

158 159 160 161 162 163 164 165
							return true; // veto, the backups failed
						});
					}

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

B
Benjamin Pasero 已提交
168 169
		// No dirty files: no veto
		return this.noVeto({ cleanUpBackups: true });
170 171
	}

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 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 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
	private backupBeforeShutdown(dirtyToBackup: URI[], textFileEditorModelManager: ITextFileEditorModelManager, reason: ShutdownReason): TPromise<IBackupResult> {
		return this.windowsService.getWindowCount().then(windowCount => {

			// 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;
			switch (reason) {
				case ShutdownReason.CLOSE:
					if (windowCount > 1 || platform.isMacintosh) {
						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:
					doBackup = false; // do not backup because we are switching contexts
					break;
			}

			if (!doBackup) {
				return TPromise.as({ didBackup: false });
			}

			// Telemetry
			this.telemetryService.publicLog('hotExit:triggered', { reason, windowCount, fileCount: dirtyToBackup.length });

			// Backup
			return this.backupAll(dirtyToBackup, textFileEditorModelManager).then(() => { return { didBackup: true }; });
		});
	}

	private backupAll(dirtyToBackup: URI[], textFileEditorModelManager: ITextFileEditorModelManager): TPromise<void> {

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

		return this.doBackupAll(filesToBackup, untitledToBackup);
	}

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

		// Handle file resources first
		return TPromise.join(dirtyFileModels.map(model => this.backupFileService.backupResource(model.getResource(), model.getValue(), model.getVersionId()))).then(results => {

			// 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 => {
					return this.backupFileService.backupResource(model.getResource(), model.getValue(), model.getVersionId());
				});

				return TPromise.join(untitledBackupPromises).then(() => void 0);
			});
		});
	}

251 252 253 254 255 256 257 258 259 260
	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
				}

B
Benjamin Pasero 已提交
261
				return this.noVeto({ cleanUpBackups: true });
262 263 264 265 266
			});
		}

		// Don't Save
		else if (confirm === ConfirmResult.DONT_SAVE) {
B
Benjamin Pasero 已提交
267
			return this.noVeto({ cleanUpBackups: true });
268 269 270 271 272 273 274 275
		}

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

B
Benjamin Pasero 已提交
276 277
	private noVeto(options: { cleanUpBackups: boolean }): boolean | TPromise<boolean> {
		if (!options.cleanUpBackups) {
B
Benjamin Pasero 已提交
278 279 280
			return false;
		}

281 282 283 284 285 286 287 288 289
		return this.cleanupBackupsBeforeShutdown().then(() => false, () => false);
	}

	private cleanupBackupsBeforeShutdown(): TPromise<void> {
		if (this.environmentService.isExtensionDevelopment) {
			return TPromise.as(void 0);
		}

		return this.backupFileService.discardAllWorkspaceBackups();
B
Benjamin Pasero 已提交
290 291
	}

292
	private onConfigurationChange(configuration: IFilesConfiguration): void {
293
		const wasAutoSaveEnabled = (this.getAutoSaveMode() !== AutoSaveMode.OFF);
294

295
		const autoSaveMode = (configuration && configuration.files && configuration.files.autoSave) || AutoSaveConfiguration.OFF;
296
		switch (autoSaveMode) {
297
			case AutoSaveConfiguration.AFTER_DELAY:
298 299
				this.configuredAutoSaveDelay = configuration && configuration.files && configuration.files.autoSaveDelay;
				this.configuredAutoSaveOnFocusChange = false;
300
				this.configuredAutoSaveOnWindowChange = false;
301 302
				break;

303
			case AutoSaveConfiguration.ON_FOCUS_CHANGE:
304 305
				this.configuredAutoSaveDelay = void 0;
				this.configuredAutoSaveOnFocusChange = true;
306 307 308 309 310 311 312
				this.configuredAutoSaveOnWindowChange = false;
				break;

			case AutoSaveConfiguration.ON_WINDOW_CHANGE:
				this.configuredAutoSaveDelay = void 0;
				this.configuredAutoSaveOnFocusChange = false;
				this.configuredAutoSaveOnWindowChange = true;
313 314 315 316 317
				break;

			default:
				this.configuredAutoSaveDelay = void 0;
				this.configuredAutoSaveOnFocusChange = false;
318
				this.configuredAutoSaveOnWindowChange = false;
319 320
				break;
		}
321

322 323
		// Emit as event
		this._onAutoSaveConfigurationChange.fire(this.getAutoSaveConfiguration());
324

325
		// save all dirty when enabling auto save
326
		if (!wasAutoSaveEnabled && this.getAutoSaveMode() !== AutoSaveMode.OFF) {
327
			this.saveAll().done(null, errors.onUnexpectedError);
328
		}
329 330 331 332 333 334 335

		// 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();
		}
336 337 338

		// Hot exit
		this.configuredHotExit = configuration && configuration.files && configuration.files.hotExit;
E
Erich Gamma 已提交
339 340
	}

341
	public getDirty(resources?: URI[]): URI[] {
342 343 344 345 346 347 348 349 350 351 352 353 354

		// 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 已提交
355 356 357
	}

	public isDirty(resource?: URI): boolean {
358 359

		// Check for dirty file
360
		if (this._models.getAll(resource).some(model => model.isDirty())) {
361 362 363 364 365
			return true;
		}

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

368 369 370 371
	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)) {
372
			return this.fileService.touchFile(resource).then(() => true, () => true /* gracefully ignore errors if just touching */);
373 374
		}

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

B
Benjamin Pasero 已提交
378 379 380
	public saveAll(includeUntitled?: boolean, reason?: SaveReason): TPromise<ITextFileOperationResult>;
	public saveAll(resources: URI[], reason?: SaveReason): TPromise<ITextFileOperationResult>;
	public saveAll(arg1?: any, reason?: SaveReason): TPromise<ITextFileOperationResult> {
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400

		// 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 已提交
401
		return this.doSaveAll(filesToSave, untitledToSave, reason);
402 403
	}

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

		// Handle files first that can just be saved
B
Benjamin Pasero 已提交
407
		return this.doSaveAllFiles(fileResources, reason).then(result => {
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 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458

			// 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 已提交
459
	private doSaveAllFiles(arg1?: any /* URI[] */, reason?: SaveReason): TPromise<ITextFileOperationResult> {
460
		const dirtyFileModels = this.getDirtyFileModels(Array.isArray(arg1) ? arg1 : void 0 /* Save All */);
E
Erich Gamma 已提交
461

462 463
		const mapResourceToResult: { [resource: string]: IResult } = Object.create(null);
		dirtyFileModels.forEach(m => {
E
Erich Gamma 已提交
464 465 466 467 468
			mapResourceToResult[m.getResource().toString()] = {
				source: m.getResource()
			};
		});

469
		return TPromise.join(dirtyFileModels.map(model => {
B
Benjamin Pasero 已提交
470
			return model.save({ reason }).then(() => {
E
Erich Gamma 已提交
471 472 473 474
				if (!model.isDirty()) {
					mapResourceToResult[model.getResource().toString()].success = true;
				}
			});
475
		})).then(r => {
E
Erich Gamma 已提交
476
			return {
477
				results: Object.keys(mapResourceToResult).map(k => mapResourceToResult[k])
E
Erich Gamma 已提交
478 479 480 481
			};
		});
	}

482 483 484
	private getFileModels(resources?: URI[]): ITextFileEditorModel[];
	private getFileModels(resource?: URI): ITextFileEditorModel[];
	private getFileModels(arg1?: any): ITextFileEditorModel[] {
E
Erich Gamma 已提交
485
		if (Array.isArray(arg1)) {
486
			const models: ITextFileEditorModel[] = [];
487
			(<URI[]>arg1).forEach(resource => {
E
Erich Gamma 已提交
488 489 490 491 492 493
				models.push(...this.getFileModels(resource));
			});

			return models;
		}

494
		return this._models.getAll(<URI>arg1);
E
Erich Gamma 已提交
495 496
	}

497 498 499
	private getDirtyFileModels(resources?: URI[]): ITextFileEditorModel[];
	private getDirtyFileModels(resource?: URI): ITextFileEditorModel[];
	private getDirtyFileModels(arg1?: any): ITextFileEditorModel[] {
500
		return this.getFileModels(arg1).filter(model => model.isDirty());
E
Erich Gamma 已提交
501 502
	}

503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
	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
534
		let modelPromise: TPromise<ITextFileEditorModel | UntitledEditorModel> = TPromise.as(null);
535
		if (resource.scheme === 'file') {
536
			modelPromise = TPromise.as(this._models.get(resource));
537 538 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
		} 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;
			});
		});
	}

564
	private doSaveTextFileAs(sourceModel: ITextFileEditorModel | UntitledEditorModel, resource: URI, target: URI): TPromise<void> {
565

566 567
		// 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 => {
568

569
			// resolve a model for the file (which can be binary if the file is not a text file)
570
			return this.models.loadOrCreate(target).then((targetModel: ITextFileEditorModel) => {
571

572
				// take over encoding and model value from source model
573 574 575 576 577
				targetModel.updatePreferredEncoding(sourceModel.getEncoding());
				targetModel.textEditorModel.setValue(sourceModel.getValue());

				// save model
				return targetModel.save();
578 579 580 581 582 583 584 585
			}, error => {

				// binary model: delete the file and run the operation again
				if ((<IFileOperationResult>error).fileOperationResult === FileOperationResult.FILE_IS_BINARY || (<IFileOperationResult>error).fileOperationResult === FileOperationResult.FILE_TOO_LARGE) {
					return this.fileService.del(target).then(() => this.doSaveTextFileAs(sourceModel, resource, target));
				}

				return TPromise.wrapError(error);
586 587 588 589 590 591 592 593 594 595 596 597
			});
		});
	}

	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 已提交
598 599

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

	public revertAll(resources?: URI[], force?: boolean): TPromise<ITextFileOperationResult> {
604 605 606 607 608 609 610 611 612 613 614 615 616

		// 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> {
617
		const fileModels = force ? this.getFileModels(resources) : this.getDirtyFileModels(resources);
E
Erich Gamma 已提交
618

619 620
		const mapResourceToResult: { [resource: string]: IResult } = Object.create(null);
		fileModels.forEach(m => {
E
Erich Gamma 已提交
621 622 623 624 625
			mapResourceToResult[m.getResource().toString()] = {
				source: m.getResource()
			};
		});

626
		return TPromise.join(fileModels.map(model => {
E
Erich Gamma 已提交
627 628 629 630
			return model.revert().then(() => {
				if (!model.isDirty()) {
					mapResourceToResult[model.getResource().toString()].success = true;
				}
631
			}, error => {
E
Erich Gamma 已提交
632

633
				// FileNotFound means the file got deleted meanwhile, so still record as successful revert
E
Erich Gamma 已提交
634 635 636 637 638 639
				if ((<IFileOperationResult>error).fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
					mapResourceToResult[model.getResource().toString()].success = true;
				}

				// Otherwise bubble up the error
				else {
640
					return TPromise.wrapError(error);
E
Erich Gamma 已提交
641 642
				}
			});
643
		})).then(r => {
644 645 646
			return {
				results: Object.keys(mapResourceToResult).map(k => mapResourceToResult[k])
			};
E
Erich Gamma 已提交
647 648 649
		});
	}

650 651 652 653 654
	public getAutoSaveMode(): AutoSaveMode {
		if (this.configuredAutoSaveOnFocusChange) {
			return AutoSaveMode.ON_FOCUS_CHANGE;
		}

655 656 657 658
		if (this.configuredAutoSaveOnWindowChange) {
			return AutoSaveMode.ON_WINDOW_CHANGE;
		}

659
		if (this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0) {
660
			return this.configuredAutoSaveDelay <= 1000 ? AutoSaveMode.AFTER_SHORT_DELAY : AutoSaveMode.AFTER_LONG_DELAY;
661 662 663
		}

		return AutoSaveMode.OFF;
664 665 666 667
	}

	public getAutoSaveConfiguration(): IAutoSaveConfiguration {
		return {
668
			autoSaveDelay: this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0 ? this.configuredAutoSaveDelay : void 0,
669 670
			autoSaveFocusChange: this.configuredAutoSaveOnFocusChange,
			autoSaveApplicationChange: this.configuredAutoSaveOnWindowChange
B
Benjamin Pasero 已提交
671
		};
672 673
	}

674 675 676 677
	public get isHotExitEnabled(): boolean {
		return !this.environmentService.isExtensionDevelopment && this.configuredHotExit;
	}

E
Erich Gamma 已提交
678
	public dispose(): void {
B
Benjamin Pasero 已提交
679
		this.toUnbind = dispose(this.toUnbind);
E
Erich Gamma 已提交
680 681

		// Clear all caches
682
		this._models.clear();
E
Erich Gamma 已提交
683 684
	}
}