textFileService.ts 26.0 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, ModelState, ISaveOptions } from 'vs/workbench/services/textfile/common/textfiles';
J
Johannes Rieken 已提交
18
import { ConfirmResult } from 'vs/workbench/common/editor';
19
import { ILifecycleService, ShutdownReason } from 'vs/platform/lifecycle/common/lifecycle';
20
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
21
import { IFileService, IResolveContentOptions, IFilesConfiguration, FileOperationError, FileOperationResult, AutoSaveConfiguration, HotExitConfiguration } from 'vs/platform/files/common/files';
J
Johannes Rieken 已提交
22 23 24
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';
26
import { IUntitledEditorService, UNTITLED_SCHEMA } from 'vs/workbench/services/untitled/common/untitledEditorService';
J
Johannes Rieken 已提交
27 28 29
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 已提交
30
import { IMessageService, Severity } from 'vs/platform/message/common/message';
B
Benjamin Pasero 已提交
31
import { ResourceMap } from 'vs/base/common/map';
B
Benjamin Pasero 已提交
32 33
import { Schemas } from 'vs/base/common/network';
import { IHistoryService } from 'vs/workbench/services/history/common/history';
E
Erich Gamma 已提交
34

35 36 37 38
export interface IBackupResult {
	didBackup: boolean;
}

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

46
	public _serviceBrand: any;
E
Erich Gamma 已提交
47

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

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

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

59
	private configuredHotExit: string;
60

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

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

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

83
		this._models = this.instantiationService.createInstance(TextFileEditorModelManager);
84

85
		const configuration = this.configurationService.getValue<IFilesConfiguration>();
86 87
		this.currentFilesAssociationConfig = configuration && configuration.files && configuration.files.associations;

88
		this.onFilesConfigurationChange(configuration);
89

K
kieferrm 已提交
90
		/* __GDPR__
K
kieferrm 已提交
91 92 93 94 95 96
			"autoSave" : {
				"${include}": [
					"${IAutoSaveConfiguration}"
				]
			}
		*/
97
		this.telemetryService.publicLog('autoSave', this.getAutoSaveConfiguration());
98 99

		this.registerListeners();
E
Erich Gamma 已提交
100 101
	}

102 103 104 105
	public get models(): ITextFileEditorModelManager {
		return this._models;
	}

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

108
	abstract promptForPath(defaultPath?: string): string;
109

110
	abstract confirmSave(resources?: URI[]): ConfirmResult;
111

112 113 114 115
	public get onAutoSaveConfigurationChange(): Event<IAutoSaveConfiguration> {
		return this._onAutoSaveConfigurationChange.event;
	}

116 117 118 119
	public get onFilesAssociationChange(): Event<void> {
		return this._onFilesAssociationChange.event;
	}

120
	private registerListeners(): void {
121

122
		// Lifecycle
123
		this.lifecycleService.onWillShutdown(event => event.veto(this.beforeShutdown(event.reason)));
124 125
		this.lifecycleService.onShutdown(this.dispose, this);

126 127 128
		// Files configuration changes
		this.toUnbind.push(this.configurationService.onDidChangeConfiguration(e => {
			if (e.affectsConfiguration('files')) {
129
				this.onFilesConfigurationChange(this.configurationService.getValue<IFilesConfiguration>());
130 131
			}
		}));
132 133
	}

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

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

140
			// If auto save is enabled, save all files and then check again for dirty files
141
			let handleAutoSave: TPromise<URI[] /* remaining dirty resources */>;
142
			if (this.getAutoSaveMode() !== AutoSaveMode.OFF) {
143 144 145
				handleAutoSave = this.saveAll(false /* files only */).then(() => this.getDirty());
			} else {
				handleAutoSave = TPromise.as(dirty);
B
Benjamin Pasero 已提交
146 147
			}

148
			return handleAutoSave.then(dirty => {
149

150 151 152
				// 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 已提交
153

154
					// If hot exit is enabled, backup dirty files and allow to exit without confirmation
155
					if (this.isHotExitEnabled) {
156
						return this.backupBeforeShutdown(dirty, this.models, reason).then(result => {
157 158 159 160 161 162 163 164
							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];
B
Benjamin Pasero 已提交
165
							this.messageService.show(Severity.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.", firstError.message));
166

167 168 169 170 171 172 173
							return true; // veto, the backups failed
						});
					}

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

				return void 0;
176
			});
177 178
		}

B
Benjamin Pasero 已提交
179 180
		// No dirty files: no veto
		return this.noVeto({ cleanUpBackups: true });
181 182
	}

183 184 185 186 187 188 189 190 191 192 193
	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:
194
					if (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY && this.configuredHotExit === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
D
Daniel Imms 已提交
195
						doBackup = true; // backup if a folder is open and onExitAndWindowClose is configured
196
					} else if (windowCount > 1 || platform.isMacintosh) {
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
						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:
212
					if (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY && this.configuredHotExit === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
213 214 215 216
						doBackup = true; // backup if a folder is open and onExitAndWindowClose is configured
					} else {
						doBackup = false; // do not backup because we are switching contexts
					}
217 218 219 220 221 222 223 224
					break;
			}

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

			// Telemetry
K
kieferrm 已提交
225
			/* __GDPR__
K
kieferrm 已提交
226 227 228 229 230 231
				"hotExit:triggered" : {
					"reason" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
					"windowCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
					"fileCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
				}
			*/
232 233 234 235 236 237 238 239 240 241 242 243 244
			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 => {
245
			if (s.scheme === Schemas.file) {
246
				filesToBackup.push(textFileEditorModelManager.get(s));
247
			} else if (s.scheme === UNTITLED_SCHEMA) {
248 249 250 251 252 253 254 255 256 257 258 259 260
				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
261 262 263
			const untitledModelPromises = untitledResources
				.filter(untitled => this.untitledEditorService.exists(untitled))
				.map(untitled => this.untitledEditorService.loadOrCreate({ resource: untitled }));
264 265 266 267 268 269 270 271 272 273 274

			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);
			});
		});
	}

275 276 277 278 279 280 281 282 283 284
	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 已提交
285
				return this.noVeto({ cleanUpBackups: true });
286 287 288 289 290
			});
		}

		// Don't Save
		else if (confirm === ConfirmResult.DONT_SAVE) {
291 292 293 294 295

			// Make sure to revert untitled so that they do not restore
			// see https://github.com/Microsoft/vscode/issues/29572
			this.untitledEditorService.revertAll();

B
Benjamin Pasero 已提交
296
			return this.noVeto({ cleanUpBackups: true });
297 298 299 300 301 302
		}

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

304
		return void 0;
305 306
	}

B
Benjamin Pasero 已提交
307 308
	private noVeto(options: { cleanUpBackups: boolean }): boolean | TPromise<boolean> {
		if (!options.cleanUpBackups) {
B
Benjamin Pasero 已提交
309 310 311
			return false;
		}

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

315
	protected cleanupBackupsBeforeShutdown(): TPromise<void> {
316 317 318 319 320
		if (this.environmentService.isExtensionDevelopment) {
			return TPromise.as(void 0);
		}

		return this.backupFileService.discardAllWorkspaceBackups();
B
Benjamin Pasero 已提交
321 322
	}

323
	protected onFilesConfigurationChange(configuration: IFilesConfiguration): void {
324
		const wasAutoSaveEnabled = (this.getAutoSaveMode() !== AutoSaveMode.OFF);
325

326
		const autoSaveMode = (configuration && configuration.files && configuration.files.autoSave) || AutoSaveConfiguration.OFF;
327
		switch (autoSaveMode) {
328
			case AutoSaveConfiguration.AFTER_DELAY:
329 330
				this.configuredAutoSaveDelay = configuration && configuration.files && configuration.files.autoSaveDelay;
				this.configuredAutoSaveOnFocusChange = false;
331
				this.configuredAutoSaveOnWindowChange = false;
332 333
				break;

334
			case AutoSaveConfiguration.ON_FOCUS_CHANGE:
335 336
				this.configuredAutoSaveDelay = void 0;
				this.configuredAutoSaveOnFocusChange = true;
337 338 339 340 341 342 343
				this.configuredAutoSaveOnWindowChange = false;
				break;

			case AutoSaveConfiguration.ON_WINDOW_CHANGE:
				this.configuredAutoSaveDelay = void 0;
				this.configuredAutoSaveOnFocusChange = false;
				this.configuredAutoSaveOnWindowChange = true;
344 345 346 347 348
				break;

			default:
				this.configuredAutoSaveDelay = void 0;
				this.configuredAutoSaveOnFocusChange = false;
349
				this.configuredAutoSaveOnWindowChange = false;
350 351
				break;
		}
352

353 354
		// Emit as event
		this._onAutoSaveConfigurationChange.fire(this.getAutoSaveConfiguration());
355

356
		// save all dirty when enabling auto save
357
		if (!wasAutoSaveEnabled && this.getAutoSaveMode() !== AutoSaveMode.OFF) {
358
			this.saveAll().done(null, errors.onUnexpectedError);
359
		}
360 361 362 363 364 365 366

		// 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();
		}
367 368

		// Hot exit
B
Benjamin Pasero 已提交
369
		const hotExitMode = configuration && configuration.files && configuration.files.hotExit;
B
Benjamin Pasero 已提交
370
		if (hotExitMode === HotExitConfiguration.OFF || hotExitMode === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
371
			this.configuredHotExit = hotExitMode;
B
Benjamin Pasero 已提交
372 373
		} else {
			this.configuredHotExit = HotExitConfiguration.ON_EXIT;
374
		}
E
Erich Gamma 已提交
375 376
	}

377
	public getDirty(resources?: URI[]): URI[] {
378 379 380 381 382

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

		// Add untitled ones
383
		dirty.push(...this.untitledEditorService.getDirty(resources));
384 385

		return dirty;
E
Erich Gamma 已提交
386 387 388
	}

	public isDirty(resource?: URI): boolean {
389 390

		// Check for dirty file
391
		if (this._models.getAll(resource).some(model => model.isDirty())) {
392 393 394 395 396
			return true;
		}

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

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

401
		// Run a forced save if we detect the file is not dirty so that save participants can still run
402
		if (options && options.force && resource.scheme === Schemas.file && !this.isDirty(resource)) {
403 404 405 406
			const model = this._models.get(resource);
			if (model) {
				model.save({ force: true, reason: SaveReason.EXPLICIT }).then(() => !model.isDirty());
			}
407 408
		}

409
		return this.saveAll([resource], options).then(result => result.results.length === 1 && result.results[0].success);
E
Erich Gamma 已提交
410 411
	}

412 413 414
	public saveAll(includeUntitled?: boolean, options?: ISaveOptions): TPromise<ITextFileOperationResult>;
	public saveAll(resources: URI[], options?: ISaveOptions): TPromise<ITextFileOperationResult>;
	public saveAll(arg1?: any, options?: ISaveOptions): TPromise<ITextFileOperationResult> {
415 416 417 418 419 420 421 422 423 424 425 426 427

		// 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 => {
J
Johannes Rieken 已提交
428
			// TODO@remote
J
Johannes Rieken 已提交
429 430 431 432
			// if (s.scheme === Schemas.file) {
			// 	filesToSave.push(s);
			// } else
			if ((Array.isArray(arg1) || arg1 === true /* includeUntitled */) && s.scheme === UNTITLED_SCHEMA) {
433
				untitledToSave.push(s);
J
Johannes Rieken 已提交
434 435
			} else {
				filesToSave.push(s);
436 437 438
			}
		});

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

442
	private doSaveAll(fileResources: URI[], untitledResources: URI[], options?: ISaveOptions): TPromise<ITextFileOperationResult> {
443 444

		// Handle files first that can just be saved
445
		return this.doSaveAllFiles(fileResources, options).then(result => {
446 447 448 449

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

					// Untitled with associated file path don't need to prompt
455 456
					if (this.untitledEditorService.hasAssociatedFilePath(untitled)) {
						targetPath = untitled.fsPath;
457 458 459 460
					}

					// Otherwise ask user
					else {
461
						targetPath = this.promptForPath(this.suggestFileName(untitled));
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
						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;
			});
		});
	}

497
	private doSaveAllFiles(resources?: URI[], options: ISaveOptions = Object.create(null)): TPromise<ITextFileOperationResult> {
B
Benjamin Pasero 已提交
498
		const dirtyFileModels = this.getDirtyFileModels(Array.isArray(resources) ? resources : void 0 /* Save All */)
499
			.filter(model => {
500
				if (model.hasState(ModelState.CONFLICT) && (options.reason === SaveReason.AUTO || options.reason === SaveReason.FOCUS_CHANGE || options.reason === SaveReason.WINDOW_CHANGE)) {
501
					return false; // if model is in save conflict, do not save unless save reason is explicit or not provided at all
502 503 504 505
				}

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

B
Benjamin Pasero 已提交
507
		const mapResourceToResult = new ResourceMap<IResult>();
508
		dirtyFileModels.forEach(m => {
B
Benjamin Pasero 已提交
509
			mapResourceToResult.set(m.getResource(), {
E
Erich Gamma 已提交
510
				source: m.getResource()
B
Benjamin Pasero 已提交
511
			});
E
Erich Gamma 已提交
512 513
		});

514
		return TPromise.join(dirtyFileModels.map(model => {
515
			return model.save(options).then(() => {
E
Erich Gamma 已提交
516
				if (!model.isDirty()) {
B
Benjamin Pasero 已提交
517
					mapResourceToResult.get(model.getResource()).success = true;
E
Erich Gamma 已提交
518 519
				}
			});
520
		})).then(r => {
E
Erich Gamma 已提交
521
			return {
B
Benjamin Pasero 已提交
522
				results: mapResourceToResult.values()
E
Erich Gamma 已提交
523 524 525 526
			};
		});
	}

527 528 529
	private getFileModels(resources?: URI[]): ITextFileEditorModel[];
	private getFileModels(resource?: URI): ITextFileEditorModel[];
	private getFileModels(arg1?: any): ITextFileEditorModel[] {
E
Erich Gamma 已提交
530
		if (Array.isArray(arg1)) {
531
			const models: ITextFileEditorModel[] = [];
532
			(<URI[]>arg1).forEach(resource => {
E
Erich Gamma 已提交
533 534 535 536 537 538
				models.push(...this.getFileModels(resource));
			});

			return models;
		}

539
		return this._models.getAll(<URI>arg1);
E
Erich Gamma 已提交
540 541
	}

542 543 544
	private getDirtyFileModels(resources?: URI[]): ITextFileEditorModel[];
	private getDirtyFileModels(resource?: URI): ITextFileEditorModel[];
	private getDirtyFileModels(arg1?: any): ITextFileEditorModel[] {
545
		return this.getFileModels(arg1).filter(model => model.isDirty());
E
Erich Gamma 已提交
546 547
	}

548 549 550 551 552
	public saveAs(resource: URI, target?: URI): TPromise<URI> {

		// Get to target resource
		if (!target) {
			let dialogPath = resource.fsPath;
553
			if (resource.scheme === UNTITLED_SCHEMA) {
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
				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
579
		let modelPromise: TPromise<ITextFileEditorModel | UntitledEditorModel> = TPromise.as(null);
580
		if (resource.scheme === Schemas.file) {
581
			modelPromise = TPromise.as(this._models.get(resource));
582 583
		} else if (resource.scheme === UNTITLED_SCHEMA && this.untitledEditorService.exists(resource)) {
			modelPromise = this.untitledEditorService.loadOrCreate({ resource });
584 585
		}

R
Ron Buckton 已提交
586
		return modelPromise.then<any>(model => {
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605

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

606
	private doSaveTextFileAs(sourceModel: ITextFileEditorModel | UntitledEditorModel, resource: URI, target: URI): TPromise<void> {
607
		let targetModelResolver: TPromise<ITextFileEditorModel>;
608

609 610 611 612 613
		// 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);
		}
614

615 616 617 618 619 620
		// 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);
			});
		}
621

622
		return targetModelResolver.then(targetModel => {
623

624 625 626
			// take over encoding and model value from source model
			targetModel.updatePreferredEncoding(sourceModel.getEncoding());
			targetModel.textEditorModel.setValue(sourceModel.getValue());
627

628 629 630
			// save model
			return targetModel.save();
		}, error => {
631

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

			return TPromise.wrapError(error);
638 639 640 641
		});
	}

	private suggestFileName(untitledResource: URI): string {
642 643 644 645 646
		const untitledFileName = this.untitledEditorService.suggestFileName(untitledResource);

		const lastActiveFile = this.historyService.getLastActiveFile();
		if (lastActiveFile) {
			return URI.file(paths.join(paths.dirname(lastActiveFile.fsPath), untitledFileName)).fsPath;
647 648
		}

649
		return untitledFileName;
650
	}
E
Erich Gamma 已提交
651

652 653
	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 已提交
654 655
	}

656
	public revertAll(resources?: URI[], options?: IRevertOptions): TPromise<ITextFileOperationResult> {
657 658

		// Revert files first
659
		return this.doRevertAllFiles(resources, options).then(operation => {
660 661 662 663 664 665 666 667 668

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

			return operation;
		});
	}

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

B
Benjamin Pasero 已提交
672
		const mapResourceToResult = new ResourceMap<IResult>();
673
		fileModels.forEach(m => {
B
Benjamin Pasero 已提交
674
			mapResourceToResult.set(m.getResource(), {
E
Erich Gamma 已提交
675
				source: m.getResource()
B
Benjamin Pasero 已提交
676
			});
E
Erich Gamma 已提交
677 678
		});

679
		return TPromise.join(fileModels.map(model => {
680
			return model.revert(options && options.soft).then(() => {
E
Erich Gamma 已提交
681
				if (!model.isDirty()) {
B
Benjamin Pasero 已提交
682
					mapResourceToResult.get(model.getResource()).success = true;
E
Erich Gamma 已提交
683
				}
684
			}, error => {
E
Erich Gamma 已提交
685

686
				// FileNotFound means the file got deleted meanwhile, so still record as successful revert
687
				if ((<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
B
Benjamin Pasero 已提交
688
					mapResourceToResult.get(model.getResource()).success = true;
E
Erich Gamma 已提交
689 690 691 692
				}

				// Otherwise bubble up the error
				else {
693
					return TPromise.wrapError(error);
E
Erich Gamma 已提交
694
				}
B
Benjamin Pasero 已提交
695

696
				return void 0;
E
Erich Gamma 已提交
697
			});
698
		})).then(r => {
699
			return {
B
Benjamin Pasero 已提交
700
				results: mapResourceToResult.values()
701
			};
E
Erich Gamma 已提交
702 703 704
		});
	}

705 706 707 708 709
	public getAutoSaveMode(): AutoSaveMode {
		if (this.configuredAutoSaveOnFocusChange) {
			return AutoSaveMode.ON_FOCUS_CHANGE;
		}

710 711 712 713
		if (this.configuredAutoSaveOnWindowChange) {
			return AutoSaveMode.ON_WINDOW_CHANGE;
		}

714
		if (this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0) {
715
			return this.configuredAutoSaveDelay <= 1000 ? AutoSaveMode.AFTER_SHORT_DELAY : AutoSaveMode.AFTER_LONG_DELAY;
716 717 718
		}

		return AutoSaveMode.OFF;
719 720 721 722
	}

	public getAutoSaveConfiguration(): IAutoSaveConfiguration {
		return {
723
			autoSaveDelay: this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0 ? this.configuredAutoSaveDelay : void 0,
724 725
			autoSaveFocusChange: this.configuredAutoSaveOnFocusChange,
			autoSaveApplicationChange: this.configuredAutoSaveOnWindowChange
B
Benjamin Pasero 已提交
726
		};
727 728
	}

729
	public get isHotExitEnabled(): boolean {
730
		return !this.environmentService.isExtensionDevelopment && this.configuredHotExit !== HotExitConfiguration.OFF;
731 732
	}

E
Erich Gamma 已提交
733
	public dispose(): void {
B
Benjamin Pasero 已提交
734
		this.toUnbind = dispose(this.toUnbind);
E
Erich Gamma 已提交
735 736

		// Clear all caches
737
		this._models.clear();
E
Erich Gamma 已提交
738
	}
J
Johannes Rieken 已提交
739
}