textFileService.ts 29.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 11 12
import * as paths from 'vs/base/common/paths';
import * as errors from 'vs/base/common/errors';
import * as objects from 'vs/base/common/objects';
M
Matt Bierner 已提交
13
import { Event, Emitter } from 'vs/base/common/event';
14
import * as platform from 'vs/base/common/platform';
15 16
import { IWindowsService } from 'vs/platform/windows/common/windows';
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
I
isidor 已提交
17
import { IResult, ITextFileOperationResult, ITextFileService, IRawTextContent, IAutoSaveConfiguration, AutoSaveMode, SaveReason, ITextFileEditorModelManager, ITextFileEditorModel, ModelState, ISaveOptions, AutoSaveContext } from 'vs/workbench/services/textfile/common/textfiles';
18
import { ConfirmResult, IRevertOptions } 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
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
24
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
25
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
J
Johannes Rieken 已提交
26 27 28
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 已提交
29
import { ResourceMap } from 'vs/base/common/map';
B
Benjamin Pasero 已提交
30 31
import { Schemas } from 'vs/base/common/network';
import { IHistoryService } from 'vs/workbench/services/history/common/history';
I
isidor 已提交
32
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
B
Benjamin Pasero 已提交
33 34
import { createTextBufferFactoryFromSnapshot } from 'vs/editor/common/model/textModel';
import { IModelService } from 'vs/editor/common/services/modelService';
35
import { INotificationService } from 'vs/platform/notification/common/notification';
B
Benjamin Pasero 已提交
36
import { isEqualOrParent, isEqual } from 'vs/base/common/resources';
E
Erich Gamma 已提交
37

38 39 40 41
export interface IBackupResult {
	didBackup: boolean;
}

E
Erich Gamma 已提交
42 43 44 45 46 47
/**
 * 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 {
48

49
	public _serviceBrand: any;
E
Erich Gamma 已提交
50

B
Benjamin Pasero 已提交
51
	private toUnbind: IDisposable[];
52 53
	private _models: TextFileEditorModelManager;

M
Matt Bierner 已提交
54
	private readonly _onFilesAssociationChange: Emitter<void>;
55 56
	private currentFilesAssociationConfig: { [key: string]: string; };

M
Matt Bierner 已提交
57
	private readonly _onAutoSaveConfigurationChange: Emitter<IAutoSaveConfiguration>;
58
	private configuredAutoSaveDelay: number;
59 60
	private configuredAutoSaveOnFocusChange: boolean;
	private configuredAutoSaveOnWindowChange: boolean;
E
Erich Gamma 已提交
61

I
isidor 已提交
62
	private autoSaveContext: IContextKey<string>;
I
isidor 已提交
63

64
	private configuredHotExit: string;
65

E
Erich Gamma 已提交
66
	constructor(
67 68 69 70 71 72
		private lifecycleService: ILifecycleService,
		private contextService: IWorkspaceContextService,
		private configurationService: IConfigurationService,
		protected fileService: IFileService,
		private untitledEditorService: IUntitledEditorService,
		private instantiationService: IInstantiationService,
73
		private notificationService: INotificationService,
74 75 76
		protected environmentService: IEnvironmentService,
		private backupFileService: IBackupFileService,
		private windowsService: IWindowsService,
I
isidor 已提交
77
		private historyService: IHistoryService,
B
Benjamin Pasero 已提交
78 79
		contextKeyService: IContextKeyService,
		private modelService: IModelService
E
Erich Gamma 已提交
80
	) {
B
Benjamin Pasero 已提交
81
		this.toUnbind = [];
82

83
		this._onAutoSaveConfigurationChange = new Emitter<IAutoSaveConfiguration>();
84 85 86 87 88
		this.toUnbind.push(this._onAutoSaveConfigurationChange);

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

89
		this._models = this.instantiationService.createInstance(TextFileEditorModelManager);
I
isidor 已提交
90
		this.autoSaveContext = AutoSaveContext.bindTo(contextKeyService);
91

92
		const configuration = this.configurationService.getValue<IFilesConfiguration>();
93 94
		this.currentFilesAssociationConfig = configuration && configuration.files && configuration.files.associations;

95
		this.onFilesConfigurationChange(configuration);
96

97
		this.registerListeners();
E
Erich Gamma 已提交
98 99
	}

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

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

106
	abstract promptForPath(defaultPath: string): TPromise<string>;
107

108
	abstract confirmSave(resources?: URI[]): TPromise<ConfirmResult>;
109

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

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

118
	private registerListeners(): void {
119

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

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

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

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

138
			// If auto save is enabled, save all files and then check again for dirty files
139
			// We DO NOT run any save participant if we are in the shutdown phase for performance reasons
140
			let handleAutoSave: TPromise<URI[] /* remaining dirty resources */>;
141
			if (this.getAutoSaveMode() !== AutoSaveMode.OFF) {
142
				handleAutoSave = this.saveAll(false /* files only */, { skipSaveParticipants: true }).then(() => this.getDirty());
143 144
			} else {
				handleAutoSave = TPromise.as(dirty);
B
Benjamin Pasero 已提交
145 146
			}

147
			return handleAutoSave.then(dirty => {
148

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

153
					// If hot exit is enabled, backup dirty files and allow to exit without confirmation
154
					if (this.isHotExitEnabled) {
155
						return this.backupBeforeShutdown(dirty, this.models, reason).then(result => {
156 157 158 159 160 161 162 163
							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];
164
							this.notificationService.error(nls.localize('files.backup.failSave', "Files that are dirty could not be written to the backup location (Error: {0}). Try saving your files first and then exit.", firstError.message));
165

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

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

				return void 0;
175
			});
176 177
		}

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

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

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

			// 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 => {
234
			if (this.fileService.canHandleResource(s)) {
235
				filesToBackup.push(textFileEditorModelManager.get(s));
236
			} else if (s.scheme === Schemas.untitled) {
237 238 239 240 241 242 243 244 245 246
				untitledToBackup.push(s);
			}
		});

		return this.doBackupAll(filesToBackup, untitledToBackup);
	}

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

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

			// Handle untitled resources
250 251 252
			const untitledModelPromises = untitledResources
				.filter(untitled => this.untitledEditorService.exists(untitled))
				.map(untitled => this.untitledEditorService.loadOrCreate({ resource: untitled }));
253 254 255

			return TPromise.join(untitledModelPromises).then(untitledModels => {
				const untitledBackupPromises = untitledModels.map(model => {
256
					return this.backupFileService.backupResource(model.getResource(), model.createSnapshot(), model.getVersionId());
257 258 259 260 261 262 263
				});

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

264
	private confirmBeforeShutdown(): boolean | TPromise<boolean> {
265
		return this.confirmSave().then(confirm => {
266

267 268 269 270 271 272
			// Save
			if (confirm === ConfirmResult.SAVE) {
				return this.saveAll(true /* includeUntitled */, { skipSaveParticipants: true }).then(result => {
					if (result.results.some(r => !r.success)) {
						return true; // veto if some saves failed
					}
273

274 275 276
					return this.noVeto({ cleanUpBackups: true });
				});
			}
277

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

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

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

288 289 290 291
			// Cancel
			else if (confirm === ConfirmResult.CANCEL) {
				return true; // veto
			}
292

293 294
			return void 0;
		});
295 296
	}

B
Benjamin Pasero 已提交
297 298
	private noVeto(options: { cleanUpBackups: boolean }): boolean | TPromise<boolean> {
		if (!options.cleanUpBackups) {
B
Benjamin Pasero 已提交
299 300 301
			return false;
		}

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

305
	protected cleanupBackupsBeforeShutdown(): TPromise<void> {
306 307 308 309 310
		if (this.environmentService.isExtensionDevelopment) {
			return TPromise.as(void 0);
		}

		return this.backupFileService.discardAllWorkspaceBackups();
B
Benjamin Pasero 已提交
311 312
	}

313
	protected onFilesConfigurationChange(configuration: IFilesConfiguration): void {
314
		const wasAutoSaveEnabled = (this.getAutoSaveMode() !== AutoSaveMode.OFF);
315

316
		const autoSaveMode = (configuration && configuration.files && configuration.files.autoSave) || AutoSaveConfiguration.OFF;
I
isidor 已提交
317
		this.autoSaveContext.set(autoSaveMode);
318
		switch (autoSaveMode) {
319
			case AutoSaveConfiguration.AFTER_DELAY:
320 321
				this.configuredAutoSaveDelay = configuration && configuration.files && configuration.files.autoSaveDelay;
				this.configuredAutoSaveOnFocusChange = false;
322
				this.configuredAutoSaveOnWindowChange = false;
323 324
				break;

325
			case AutoSaveConfiguration.ON_FOCUS_CHANGE:
326 327
				this.configuredAutoSaveDelay = void 0;
				this.configuredAutoSaveOnFocusChange = true;
328 329 330 331 332 333 334
				this.configuredAutoSaveOnWindowChange = false;
				break;

			case AutoSaveConfiguration.ON_WINDOW_CHANGE:
				this.configuredAutoSaveDelay = void 0;
				this.configuredAutoSaveOnFocusChange = false;
				this.configuredAutoSaveOnWindowChange = true;
335 336 337 338 339
				break;

			default:
				this.configuredAutoSaveDelay = void 0;
				this.configuredAutoSaveOnFocusChange = false;
340
				this.configuredAutoSaveOnWindowChange = false;
341 342
				break;
		}
343

344 345
		// Emit as event
		this._onAutoSaveConfigurationChange.fire(this.getAutoSaveConfiguration());
346

347
		// save all dirty when enabling auto save
348
		if (!wasAutoSaveEnabled && this.getAutoSaveMode() !== AutoSaveMode.OFF) {
349
			this.saveAll().done(null, errors.onUnexpectedError);
350
		}
351 352 353 354 355 356 357

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

		// Hot exit
B
Benjamin Pasero 已提交
360
		const hotExitMode = configuration && configuration.files && configuration.files.hotExit;
B
Benjamin Pasero 已提交
361
		if (hotExitMode === HotExitConfiguration.OFF || hotExitMode === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
362
			this.configuredHotExit = hotExitMode;
B
Benjamin Pasero 已提交
363 364
		} else {
			this.configuredHotExit = HotExitConfiguration.ON_EXIT;
365
		}
E
Erich Gamma 已提交
366 367
	}

368
	public getDirty(resources?: URI[]): URI[] {
369 370 371 372 373

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

		// Add untitled ones
374
		dirty.push(...this.untitledEditorService.getDirty(resources));
375 376

		return dirty;
E
Erich Gamma 已提交
377 378 379
	}

	public isDirty(resource?: URI): boolean {
380 381

		// Check for dirty file
382
		if (this._models.getAll(resource).some(model => model.isDirty())) {
383 384 385 386 387
			return true;
		}

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

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

392
		// Run a forced save if we detect the file is not dirty so that save participants can still run
393
		if (options && options.force && this.fileService.canHandleResource(resource) && !this.isDirty(resource)) {
394 395 396 397
			const model = this._models.get(resource);
			if (model) {
				model.save({ force: true, reason: SaveReason.EXPLICIT }).then(() => !model.isDirty());
			}
398 399
		}

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

403 404 405
	public saveAll(includeUntitled?: boolean, options?: ISaveOptions): TPromise<ITextFileOperationResult>;
	public saveAll(resources: URI[], options?: ISaveOptions): TPromise<ITextFileOperationResult>;
	public saveAll(arg1?: any, options?: ISaveOptions): TPromise<ITextFileOperationResult> {
406 407 408 409 410 411 412 413 414 415 416 417 418

		// 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 => {
419
			if ((Array.isArray(arg1) || arg1 === true /* includeUntitled */) && s.scheme === Schemas.untitled) {
420
				untitledToSave.push(s);
J
Johannes Rieken 已提交
421 422
			} else {
				filesToSave.push(s);
423 424 425
			}
		});

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

429
	private doSaveAll(fileResources: URI[], untitledResources: URI[], options?: ISaveOptions): TPromise<ITextFileOperationResult> {
430 431

		// Handle files first that can just be saved
432
		return this.doSaveAllFiles(fileResources, options).then(async result => {
433 434 435 436

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

					// Untitled with associated file path don't need to prompt
442 443
					if (this.untitledEditorService.hasAssociatedFilePath(untitled)) {
						targetPath = untitled.fsPath;
444 445 446 447
					}

					// Otherwise ask user
					else {
448
						targetPath = await this.promptForPath(this.suggestFileName(untitled));
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 479 480 481 482 483
						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;
			});
		});
	}

484
	private doSaveAllFiles(resources?: URI[], options: ISaveOptions = Object.create(null)): TPromise<ITextFileOperationResult> {
B
Benjamin Pasero 已提交
485
		const dirtyFileModels = this.getDirtyFileModels(Array.isArray(resources) ? resources : void 0 /* Save All */)
486
			.filter(model => {
487 488
				if ((model.hasState(ModelState.CONFLICT) || model.hasState(ModelState.ERROR)) && (options.reason === SaveReason.AUTO || options.reason === SaveReason.FOCUS_CHANGE || options.reason === SaveReason.WINDOW_CHANGE)) {
					return false; // if model is in save conflict or error, do not save unless save reason is explicit or not provided at all
489 490 491 492
				}

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

B
Benjamin Pasero 已提交
494
		const mapResourceToResult = new ResourceMap<IResult>();
495
		dirtyFileModels.forEach(m => {
B
Benjamin Pasero 已提交
496
			mapResourceToResult.set(m.getResource(), {
E
Erich Gamma 已提交
497
				source: m.getResource()
B
Benjamin Pasero 已提交
498
			});
E
Erich Gamma 已提交
499 500
		});

501
		return TPromise.join(dirtyFileModels.map(model => {
502
			return model.save(options).then(() => {
E
Erich Gamma 已提交
503
				if (!model.isDirty()) {
B
Benjamin Pasero 已提交
504
					mapResourceToResult.get(model.getResource()).success = true;
E
Erich Gamma 已提交
505 506
				}
			});
507
		})).then(r => {
E
Erich Gamma 已提交
508
			return {
B
Benjamin Pasero 已提交
509
				results: mapResourceToResult.values()
E
Erich Gamma 已提交
510 511 512 513
			};
		});
	}

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

			return models;
		}

526
		return this._models.getAll(<URI>arg1);
E
Erich Gamma 已提交
527 528
	}

529 530 531
	private getDirtyFileModels(resources?: URI[]): ITextFileEditorModel[];
	private getDirtyFileModels(resource?: URI): ITextFileEditorModel[];
	private getDirtyFileModels(arg1?: any): ITextFileEditorModel[] {
532
		return this.getFileModels(arg1).filter(model => model.isDirty());
E
Erich Gamma 已提交
533 534
	}

535
	public saveAs(resource: URI, target?: URI, options?: ISaveOptions): TPromise<URI> {
536 537

		// Get to target resource
538 539 540 541
		let targetPromise: TPromise<URI>;
		if (target) {
			targetPromise = TPromise.wrap(target);
		} else {
542
			let dialogPath = resource.fsPath;
543
			if (resource.scheme === Schemas.untitled) {
544 545 546
				dialogPath = this.suggestFileName(resource);
			}

547 548 549 550
			targetPromise = this.promptForPath(dialogPath).then(pathRaw => {
				if (pathRaw) {
					return URI.file(pathRaw);
				}
551

552 553
				return void 0;
			});
554 555
		}

556 557 558 559
		return targetPromise.then(target => {
			if (!target) {
				return TPromise.as(null); // user canceled
			}
560

561 562 563 564 565 566 567 568
			// Just save if target is same as models own resource
			if (resource.toString() === target.toString()) {
				return this.save(resource, options).then(() => resource);
			}

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

571
	private doSaveAs(resource: URI, target?: URI, options?: ISaveOptions): TPromise<URI> {
572 573

		// Retrieve text model from provided resource if any
574
		let modelPromise: TPromise<ITextFileEditorModel | UntitledEditorModel> = TPromise.as(null);
575
		if (this.fileService.canHandleResource(resource)) {
576
			modelPromise = TPromise.as(this._models.get(resource));
577
		} else if (resource.scheme === Schemas.untitled && this.untitledEditorService.exists(resource)) {
578
			modelPromise = this.untitledEditorService.loadOrCreate({ resource });
579 580
		}

R
Ron Buckton 已提交
581
		return modelPromise.then<any>(model => {
582 583 584

			// 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) {
585
				return this.doSaveTextFileAs(model, resource, target, options);
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
			}

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

601
	private doSaveTextFileAs(sourceModel: ITextFileEditorModel | UntitledEditorModel, resource: URI, target: URI, options?: ISaveOptions): TPromise<void> {
602
		let targetModelResolver: TPromise<ITextFileEditorModel>;
603

604 605 606 607 608
		// 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);
		}
609

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

617
		return targetModelResolver.then(targetModel => {
618

619 620
			// take over encoding and model value from source model
			targetModel.updatePreferredEncoding(sourceModel.getEncoding());
B
Benjamin Pasero 已提交
621
			this.modelService.updateModel(targetModel.textEditorModel, createTextBufferFactoryFromSnapshot(sourceModel.createSnapshot()));
622

623
			// save model
624
			return targetModel.save(options);
625
		}, error => {
626

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

			return TPromise.wrapError(error);
633 634 635 636
		});
	}

	private suggestFileName(untitledResource: URI): string {
637 638 639 640 641
		const untitledFileName = this.untitledEditorService.suggestFileName(untitledResource);

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

644 645 646 647 648
		const lastActiveFolder = this.historyService.getLastActiveWorkspaceRoot('file');
		if (lastActiveFolder) {
			return URI.file(paths.join(lastActiveFolder.fsPath, untitledFileName)).fsPath;
		}

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

B
Benjamin Pasero 已提交
705
	public delete(resource: URI, useTrash?: boolean): TPromise<void> {
B
Benjamin Pasero 已提交
706 707 708
		const dirtyFiles = this.getDirty().filter(dirty => isEqualOrParent(dirty, resource, !platform.isLinux /* ignorecase */));

		return this.revertAll(dirtyFiles, { soft: true }).then(() => this.fileService.del(resource, useTrash));
B
Benjamin Pasero 已提交
709 710 711 712
	}

	public move(source: URI, target: URI, overwrite?: boolean): TPromise<void> {

B
Benjamin Pasero 已提交
713
		// Handle target models if existing (if target URI is a folder, this can be multiple)
B
Benjamin Pasero 已提交
714
		let handleTargetModelPromise: TPromise<any> = TPromise.as(void 0);
B
Benjamin Pasero 已提交
715 716 717
		const dirtyTargetModels = this.getDirtyFileModels().filter(model => isEqualOrParent(model.getResource(), target, !platform.isLinux /* ignorecase */));
		if (dirtyTargetModels.length) {
			handleTargetModelPromise = this.revertAll(dirtyTargetModels.map(targetModel => targetModel.getResource()), { soft: true });
B
Benjamin Pasero 已提交
718 719 720 721
		}

		return handleTargetModelPromise.then(() => {

B
Benjamin Pasero 已提交
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
			// Handle dirty source models if existing (if source URI is a folder, this can be multiple)
			let handleDirtySourceModels: TPromise<any>;
			const dirtySourceModels = this.getDirtyFileModels().filter(model => isEqualOrParent(model.getResource(), source, !platform.isLinux /* ignorecase */));
			const dirtyTargetModels: URI[] = [];
			if (dirtySourceModels.length) {
				handleDirtySourceModels = TPromise.join(dirtySourceModels.map(sourceModel => {
					const sourceModelResource = sourceModel.getResource();
					let targetModelResource: URI;

					// If the source is the actual model, just use target as new resource
					if (isEqual(sourceModelResource, source, !platform.isLinux /* ignorecase */)) {
						targetModelResource = target;
					}

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

					// Remember as dirty target model to load after the operation
					dirtyTargetModels.push(targetModelResource);

					// Backup dirty source model to the target resource it will become later
					return this.backupFileService.backupResource(targetModelResource, sourceModel.createSnapshot(), sourceModel.getVersionId());
				}));
B
Benjamin Pasero 已提交
748
			} else {
B
Benjamin Pasero 已提交
749
				handleDirtySourceModels = TPromise.as(void 0);
B
Benjamin Pasero 已提交
750 751
			}

B
Benjamin Pasero 已提交
752
			return handleDirtySourceModels.then(() => {
B
Benjamin Pasero 已提交
753

B
Benjamin Pasero 已提交
754 755
				// Soft revert the dirty source files if any
				return this.revertAll(dirtySourceModels.map(dirtySourceModel => dirtySourceModel.getResource()), { soft: true }).then(() => {
B
Benjamin Pasero 已提交
756 757 758 759

					// Rename to target
					return this.fileService.moveFile(source, target, overwrite).then(() => {

B
Benjamin Pasero 已提交
760 761
						// Load models that were dirty before
						return TPromise.join(dirtyTargetModels.map(dirtyTargetModel => this.models.loadOrCreate(dirtyTargetModel))).then(() => void 0);
B
Benjamin Pasero 已提交
762
					}, error => {
B
Benjamin Pasero 已提交
763 764 765 766

						// In case of an error, discard any dirty target backups that were made
						return TPromise.join(dirtyTargetModels.map(dirtyTargetModel => this.backupFileService.discardResourceBackup(dirtyTargetModel)))
							.then(() => TPromise.wrapError(error));
B
Benjamin Pasero 已提交
767 768 769 770 771 772
					});
				});
			});
		});
	}

773 774 775 776 777
	public getAutoSaveMode(): AutoSaveMode {
		if (this.configuredAutoSaveOnFocusChange) {
			return AutoSaveMode.ON_FOCUS_CHANGE;
		}

778 779 780 781
		if (this.configuredAutoSaveOnWindowChange) {
			return AutoSaveMode.ON_WINDOW_CHANGE;
		}

782
		if (this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0) {
783
			return this.configuredAutoSaveDelay <= 1000 ? AutoSaveMode.AFTER_SHORT_DELAY : AutoSaveMode.AFTER_LONG_DELAY;
784 785 786
		}

		return AutoSaveMode.OFF;
787 788 789 790
	}

	public getAutoSaveConfiguration(): IAutoSaveConfiguration {
		return {
791
			autoSaveDelay: this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0 ? this.configuredAutoSaveDelay : void 0,
792 793
			autoSaveFocusChange: this.configuredAutoSaveOnFocusChange,
			autoSaveApplicationChange: this.configuredAutoSaveOnWindowChange
B
Benjamin Pasero 已提交
794
		};
795 796
	}

797
	public get isHotExitEnabled(): boolean {
798
		return !this.environmentService.isExtensionDevelopment && this.configuredHotExit !== HotExitConfiguration.OFF;
799 800
	}

E
Erich Gamma 已提交
801
	public dispose(): void {
B
Benjamin Pasero 已提交
802
		this.toUnbind = dispose(this.toUnbind);
E
Erich Gamma 已提交
803 804

		// Clear all caches
805
		this._models.clear();
E
Erich Gamma 已提交
806
	}
J
Johannes Rieken 已提交
807
}