textFileService.ts 25.7 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';
17
import { IRevertOptions, IResult, ITextFileOperationResult, ITextFileService, IRawTextContent, IAutoSaveConfiguration, AutoSaveMode, SaveReason, ITextFileEditorModelManager, ITextFileEditorModel, ISaveOptions, ModelState } from 'vs/workbench/services/textfile/common/textfiles';
J
Johannes Rieken 已提交
18
import { ConfirmResult } from 'vs/workbench/common/editor';
B
Benjamin Pasero 已提交
19
import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService';
20
import { ILifecycleService, ShutdownReason } from 'vs/platform/lifecycle/common/lifecycle';
J
Johannes Rieken 已提交
21
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
22
import { IFileService, IResolveContentOptions, IFilesConfiguration, IFileOperationResult, FileOperationResult, AutoSaveConfiguration, HotExitConfiguration } from 'vs/platform/files/common/files';
J
Johannes Rieken 已提交
23 24 25
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
26
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
J
Johannes Rieken 已提交
27 28 29 30
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
	private configuredHotExit: string;
58

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,
B
Benjamin Pasero 已提交
64
		@IFileService protected fileService: IFileService,
65
		@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
66
		@IInstantiationService private instantiationService: IInstantiationService,
67 68 69
		@IMessageService private messageService: IMessageService,
		@IEnvironmentService protected environmentService: IEnvironmentService,
		@IBackupFileService private backupFileService: IBackupFileService,
B
Benjamin Pasero 已提交
70
		@IEditorGroupService private editorGroupService: IEditorGroupService,
71
		@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
							return true; // veto, the backups failed
						});
					}

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

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

173 174 175 176 177 178 179 180 181 182 183
	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:
D
Daniel Imms 已提交
184 185
					if (this.contextService.hasWorkspace() && this.configuredHotExit === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
						doBackup = true; // backup if a folder is open and onExitAndWindowClose is configured
186
					} else if (windowCount > 1 || platform.isMacintosh) {
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
						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:
202 203 204 205 206
					if (this.contextService.hasWorkspace() && this.configuredHotExit === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
						doBackup = true; // backup if a folder is open and onExitAndWindowClose is configured
					} else {
						doBackup = false; // do not backup because we are switching contexts
					}
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 251 252 253 254 255 256 257
					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);
			});
		});
	}

258 259 260 261 262 263 264 265 266 267
	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 已提交
268
				return this.noVeto({ cleanUpBackups: true });
269 270 271 272 273
			});
		}

		// Don't Save
		else if (confirm === ConfirmResult.DONT_SAVE) {
B
Benjamin Pasero 已提交
274
			return this.noVeto({ cleanUpBackups: true });
275 276 277 278 279 280
		}

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

		return undefined;
283 284
	}

B
Benjamin Pasero 已提交
285 286
	private noVeto(options: { cleanUpBackups: boolean }): boolean | TPromise<boolean> {
		if (!options.cleanUpBackups) {
B
Benjamin Pasero 已提交
287 288 289
			return false;
		}

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

293
	protected cleanupBackupsBeforeShutdown(): TPromise<void> {
294 295 296 297 298
		if (this.environmentService.isExtensionDevelopment) {
			return TPromise.as(void 0);
		}

		return this.backupFileService.discardAllWorkspaceBackups();
B
Benjamin Pasero 已提交
299 300
	}

301
	protected onConfigurationChange(configuration: IFilesConfiguration): void {
302
		const wasAutoSaveEnabled = (this.getAutoSaveMode() !== AutoSaveMode.OFF);
303

304
		const autoSaveMode = (configuration && configuration.files && configuration.files.autoSave) || AutoSaveConfiguration.OFF;
305
		switch (autoSaveMode) {
306
			case AutoSaveConfiguration.AFTER_DELAY:
307 308
				this.configuredAutoSaveDelay = configuration && configuration.files && configuration.files.autoSaveDelay;
				this.configuredAutoSaveOnFocusChange = false;
309
				this.configuredAutoSaveOnWindowChange = false;
310 311
				break;

312
			case AutoSaveConfiguration.ON_FOCUS_CHANGE:
313 314
				this.configuredAutoSaveDelay = void 0;
				this.configuredAutoSaveOnFocusChange = true;
315 316 317 318 319 320 321
				this.configuredAutoSaveOnWindowChange = false;
				break;

			case AutoSaveConfiguration.ON_WINDOW_CHANGE:
				this.configuredAutoSaveDelay = void 0;
				this.configuredAutoSaveOnFocusChange = false;
				this.configuredAutoSaveOnWindowChange = true;
322 323 324 325 326
				break;

			default:
				this.configuredAutoSaveDelay = void 0;
				this.configuredAutoSaveOnFocusChange = false;
327
				this.configuredAutoSaveOnWindowChange = false;
328 329
				break;
		}
330

331 332
		// Emit as event
		this._onAutoSaveConfigurationChange.fire(this.getAutoSaveConfiguration());
333

334
		// save all dirty when enabling auto save
335
		if (!wasAutoSaveEnabled && this.getAutoSaveMode() !== AutoSaveMode.OFF) {
336
			this.saveAll().done(null, errors.onUnexpectedError);
337
		}
338 339 340 341 342 343 344

		// 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();
		}
345 346

		// Hot exit
347
		const hotExitMode = configuration && configuration.files ? configuration.files.hotExit : HotExitConfiguration.OFF;
348 349 350 351
		// Handle the legacy case where hot exit was a boolean
		if (<any>hotExitMode === false) {
			this.configuredHotExit = HotExitConfiguration.OFF;
		} else if (<any>hotExitMode === true) {
D
Daniel Imms 已提交
352
			this.configuredHotExit = HotExitConfiguration.ON_EXIT;
353 354 355
		} else {
			this.configuredHotExit = hotExitMode;
		}
E
Erich Gamma 已提交
356 357
	}

358
	public getDirty(resources?: URI[]): URI[] {
359 360 361 362 363 364 365 366 367 368 369 370 371

		// 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 已提交
372 373 374
	}

	public isDirty(resource?: URI): boolean {
375 376

		// Check for dirty file
377
		if (this._models.getAll(resource).some(model => model.isDirty())) {
378 379 380 381 382
			return true;
		}

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

385 386
	public save(resource: URI, options?: ISaveOptions): TPromise<boolean> {

387
		// Run a forced save if we detect the file is not dirty so that save participants can still run
388
		if (options && options.force && resource.scheme === 'file' && !this.isDirty(resource)) {
389 390 391 392
			const model = this._models.get(resource);
			if (model) {
				model.save({ force: true, reason: SaveReason.EXPLICIT }).then(() => !model.isDirty());
			}
393 394
		}

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

B
Benjamin Pasero 已提交
398 399 400
	public saveAll(includeUntitled?: boolean, reason?: SaveReason): TPromise<ITextFileOperationResult>;
	public saveAll(resources: URI[], reason?: SaveReason): TPromise<ITextFileOperationResult>;
	public saveAll(arg1?: any, reason?: SaveReason): TPromise<ITextFileOperationResult> {
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420

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

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

		// Handle files first that can just be saved
B
Benjamin Pasero 已提交
427
		return this.doSaveAllFiles(fileResources, reason).then(result => {
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 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478

			// 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 已提交
479
	private doSaveAllFiles(arg1?: any /* URI[] */, reason?: SaveReason): TPromise<ITextFileOperationResult> {
480 481
		const dirtyFileModels = this.getDirtyFileModels(Array.isArray(arg1) ? arg1 : void 0 /* Save All */)
			.filter(model => {
482 483
				if (model.hasState(ModelState.CONFLICT) && (reason === SaveReason.AUTO || reason === SaveReason.FOCUS_CHANGE || reason === SaveReason.WINDOW_CHANGE)) {
					return false; // if model is in save conflict, do not save unless save reason is explicit or not provided at all
484 485 486 487
				}

				return true;
			});
E
Erich Gamma 已提交
488

489 490
		const mapResourceToResult: { [resource: string]: IResult } = Object.create(null);
		dirtyFileModels.forEach(m => {
E
Erich Gamma 已提交
491 492 493 494 495
			mapResourceToResult[m.getResource().toString()] = {
				source: m.getResource()
			};
		});

496
		return TPromise.join(dirtyFileModels.map(model => {
B
Benjamin Pasero 已提交
497
			return model.save({ reason }).then(() => {
E
Erich Gamma 已提交
498 499 500 501
				if (!model.isDirty()) {
					mapResourceToResult[model.getResource().toString()].success = true;
				}
			});
502
		})).then(r => {
E
Erich Gamma 已提交
503
			return {
504
				results: Object.keys(mapResourceToResult).map(k => mapResourceToResult[k])
E
Erich Gamma 已提交
505 506 507 508
			};
		});
	}

509 510 511
	private getFileModels(resources?: URI[]): ITextFileEditorModel[];
	private getFileModels(resource?: URI): ITextFileEditorModel[];
	private getFileModels(arg1?: any): ITextFileEditorModel[] {
E
Erich Gamma 已提交
512
		if (Array.isArray(arg1)) {
513
			const models: ITextFileEditorModel[] = [];
514
			(<URI[]>arg1).forEach(resource => {
E
Erich Gamma 已提交
515 516 517 518 519 520
				models.push(...this.getFileModels(resource));
			});

			return models;
		}

521
		return this._models.getAll(<URI>arg1);
E
Erich Gamma 已提交
522 523
	}

524 525 526
	private getDirtyFileModels(resources?: URI[]): ITextFileEditorModel[];
	private getDirtyFileModels(resource?: URI): ITextFileEditorModel[];
	private getDirtyFileModels(arg1?: any): ITextFileEditorModel[] {
527
		return this.getFileModels(arg1).filter(model => model.isDirty());
E
Erich Gamma 已提交
528 529
	}

530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
	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
561
		let modelPromise: TPromise<ITextFileEditorModel | UntitledEditorModel> = TPromise.as(null);
562
		if (resource.scheme === 'file') {
563
			modelPromise = TPromise.as(this._models.get(resource));
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
		} 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;
			});
		});
	}

591
	private doSaveTextFileAs(sourceModel: ITextFileEditorModel | UntitledEditorModel, resource: URI, target: URI): TPromise<void> {
592
		let targetModelResolver: TPromise<ITextFileEditorModel>;
593

594 595 596 597 598
		// Prefer an existing model if it is already loaded for the given target resource
		const targetModel = this.models.get(target);
		if (targetModel && targetModel.isResolved()) {
			targetModelResolver = TPromise.as(targetModel);
		}
599

600 601 602 603 604 605
		// Otherwise create the target file empty if it does not exist already and resolve it from there
		else {
			targetModelResolver = this.fileService.resolveFile(target).then(stat => stat, () => null).then(stat => stat || this.fileService.updateContent(target, '')).then(stat => {
				return this.models.loadOrCreate(target);
			});
		}
606

607
		return targetModelResolver.then(targetModel => {
608

609 610 611
			// take over encoding and model value from source model
			targetModel.updatePreferredEncoding(sourceModel.getEncoding());
			targetModel.textEditorModel.setValue(sourceModel.getValue());
612

613 614 615
			// save model
			return targetModel.save();
		}, error => {
616

617 618 619 620 621 622
			// 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);
623 624 625 626 627 628 629 630 631 632 633
		});
	}

	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 已提交
634

635 636
	public revert(resource: URI, options?: IRevertOptions): TPromise<boolean> {
		return this.revertAll([resource], options).then(result => result.results.length === 1 && result.results[0].success);
E
Erich Gamma 已提交
637 638
	}

639
	public revertAll(resources?: URI[], options?: IRevertOptions): TPromise<ITextFileOperationResult> {
640 641

		// Revert files first
642
		return this.doRevertAllFiles(resources, options).then(operation => {
643 644 645 646 647 648 649 650 651

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

			return operation;
		});
	}

652 653
	private doRevertAllFiles(resources?: URI[], options?: IRevertOptions): TPromise<ITextFileOperationResult> {
		const fileModels = options && options.force ? this.getFileModels(resources) : this.getDirtyFileModels(resources);
E
Erich Gamma 已提交
654

655 656
		const mapResourceToResult: { [resource: string]: IResult } = Object.create(null);
		fileModels.forEach(m => {
E
Erich Gamma 已提交
657 658 659 660 661
			mapResourceToResult[m.getResource().toString()] = {
				source: m.getResource()
			};
		});

662
		return TPromise.join(fileModels.map(model => {
663
			return model.revert(options && options.soft).then(() => {
E
Erich Gamma 已提交
664 665 666
				if (!model.isDirty()) {
					mapResourceToResult[model.getResource().toString()].success = true;
				}
667
			}, error => {
E
Erich Gamma 已提交
668

669
				// FileNotFound means the file got deleted meanwhile, so still record as successful revert
E
Erich Gamma 已提交
670 671 672 673 674 675
				if ((<IFileOperationResult>error).fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
					mapResourceToResult[model.getResource().toString()].success = true;
				}

				// Otherwise bubble up the error
				else {
676
					return TPromise.wrapError(error);
E
Erich Gamma 已提交
677
				}
678
				return undefined;
E
Erich Gamma 已提交
679
			});
680
		})).then(r => {
681 682 683
			return {
				results: Object.keys(mapResourceToResult).map(k => mapResourceToResult[k])
			};
E
Erich Gamma 已提交
684 685 686
		});
	}

687 688 689 690 691
	public getAutoSaveMode(): AutoSaveMode {
		if (this.configuredAutoSaveOnFocusChange) {
			return AutoSaveMode.ON_FOCUS_CHANGE;
		}

692 693 694 695
		if (this.configuredAutoSaveOnWindowChange) {
			return AutoSaveMode.ON_WINDOW_CHANGE;
		}

696
		if (this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0) {
697
			return this.configuredAutoSaveDelay <= 1000 ? AutoSaveMode.AFTER_SHORT_DELAY : AutoSaveMode.AFTER_LONG_DELAY;
698 699 700
		}

		return AutoSaveMode.OFF;
701 702 703 704
	}

	public getAutoSaveConfiguration(): IAutoSaveConfiguration {
		return {
705
			autoSaveDelay: this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0 ? this.configuredAutoSaveDelay : void 0,
706 707
			autoSaveFocusChange: this.configuredAutoSaveOnFocusChange,
			autoSaveApplicationChange: this.configuredAutoSaveOnWindowChange
B
Benjamin Pasero 已提交
708
		};
709 710
	}

711
	public get isHotExitEnabled(): boolean {
712
		return !this.environmentService.isExtensionDevelopment && this.configuredHotExit !== HotExitConfiguration.OFF;
713 714
	}

E
Erich Gamma 已提交
715
	public dispose(): void {
B
Benjamin Pasero 已提交
716
		this.toUnbind = dispose(this.toUnbind);
E
Erich Gamma 已提交
717 718

		// Clear all caches
719
		this._models.clear();
E
Erich Gamma 已提交
720 721
	}
}