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

T
t-amqi 已提交
6
import * as path from 'vs/base/common/paths';
7
import * as nls from 'vs/nls';
M
Matt Bierner 已提交
8
import { Event, Emitter } from 'vs/base/common/event';
B
Benjamin Pasero 已提交
9
import { TPromise } from 'vs/base/common/winjs.base';
J
Johannes Rieken 已提交
10 11
import { guessMimeTypes } from 'vs/base/common/mime';
import { toErrorMessage } from 'vs/base/common/errorMessage';
12
import { URI } from 'vs/base/common/uri';
13
import { isUndefinedOrNull } from 'vs/base/common/types';
14
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
15
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
16
import { ITextFileService, IAutoSaveConfiguration, ModelState, ITextFileEditorModel, ISaveOptions, ISaveErrorHandler, ISaveParticipant, StateChange, SaveReason, IRawTextContent, ILoadOptions, LoadReason } from 'vs/workbench/services/textfile/common/textfiles';
B
Benjamin Pasero 已提交
17
import { EncodingMode } from 'vs/workbench/common/editor';
J
Johannes Rieken 已提交
18
import { BaseTextEditorModel } from 'vs/workbench/common/editor/textEditorModel';
19
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
20
import { IFileService, IFileStat, FileOperationError, FileOperationResult, CONTENT_CHANGE_EVENT_BUFFER_DELAY, FileChangesEvent, FileChangeType } from 'vs/platform/files/common/files';
J
Johannes Rieken 已提交
21
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
A
Alex Dima 已提交
22
import { IModeService, ILanguageSelection } from 'vs/editor/common/services/modeService';
23
import { IModelService } from 'vs/editor/common/services/modelService';
24
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
25
import { RunOnceScheduler, timeout } from 'vs/base/common/async';
26
import { ITextBufferFactory } from 'vs/editor/common/model';
R
Ramya Achutha Rao 已提交
27
import { IHashService } from 'vs/workbench/services/hash/common/hashService';
28
import { createTextBufferFactory } from 'vs/editor/common/model/textModel';
29
import { INotificationService } from 'vs/platform/notification/common/notification';
B
Benjamin Pasero 已提交
30
import { isLinux } from 'vs/base/common/platform';
31
import { IDisposable, toDisposable } from 'vs/base/common/lifecycle';
I
isidor 已提交
32
import { ILogService } from 'vs/platform/log/common/log';
33
import { isEqual, isEqualOrParent } from 'vs/base/common/resources';
B
Benjamin Pasero 已提交
34
import { onUnexpectedError } from 'vs/base/common/errors';
B
Benjamin Pasero 已提交
35

E
Erich Gamma 已提交
36 37 38
/**
 * The text file editor model listens to changes to its underlying code editor model and saves these changes through the file service back to the disk.
 */
39
export class TextFileEditorModel extends BaseTextEditorModel implements ITextFileEditorModel {
E
Erich Gamma 已提交
40

B
Benjamin Pasero 已提交
41 42
	static DEFAULT_CONTENT_CHANGE_BUFFER_DELAY = CONTENT_CHANGE_EVENT_BUFFER_DELAY;
	static DEFAULT_ORPHANED_CHANGE_BUFFER_DELAY = 100;
K
kieferrm 已提交
43
	static WHITELIST_JSON = ['package.json', 'package-lock.json', 'tsconfig.json', 'jsconfig.json', 'bower.json', '.eslintrc.json', 'tslint.json', 'composer.json'];
44
	static WHITELIST_WORKSPACE_JSON = ['settings.json', 'extensions.json', 'tasks.json', 'launch.json'];
45

E
Erich Gamma 已提交
46
	private static saveErrorHandler: ISaveErrorHandler;
B
Benjamin Pasero 已提交
47 48
	static setSaveErrorHandler(handler: ISaveErrorHandler): void { TextFileEditorModel.saveErrorHandler = handler; }

B
Benjamin Pasero 已提交
49
	private static saveParticipant: ISaveParticipant;
B
Benjamin Pasero 已提交
50
	static setSaveParticipant(handler: ISaveParticipant): void { TextFileEditorModel.saveParticipant = handler; }
E
Erich Gamma 已提交
51

B
Benjamin Pasero 已提交
52 53 54 55 56 57
	private readonly _onDidContentChange: Emitter<StateChange> = this._register(new Emitter<StateChange>());
	get onDidContentChange(): Event<StateChange> { return this._onDidContentChange.event; }

	private readonly _onDidStateChange: Emitter<StateChange> = this._register(new Emitter<StateChange>());
	get onDidStateChange(): Event<StateChange> { return this._onDidStateChange.event; }

E
Erich Gamma 已提交
58 59 60 61 62 63
	private resource: URI;
	private contentEncoding: string; 			// encoding as reported from disk
	private preferredEncoding: string;			// encoding as chosen by the user
	private dirty: boolean;
	private versionId: number;
	private bufferSavedVersionId: number;
64
	private lastResolvedDiskStat: IFileStat;
E
Erich Gamma 已提交
65
	private blockModelContentChange: boolean;
66
	private autoSaveAfterMillies: number;
67
	private autoSaveAfterMilliesEnabled: boolean;
68
	private autoSaveDisposable: IDisposable;
69
	private contentChangeEventScheduler: RunOnceScheduler;
70
	private orphanedChangeEventScheduler: RunOnceScheduler;
71
	private saveSequentializer: SaveSequentializer;
E
Erich Gamma 已提交
72
	private disposed: boolean;
B
Benjamin Pasero 已提交
73
	private lastSaveAttemptTime: number;
E
Erich Gamma 已提交
74
	private createTextEditorModelPromise: TPromise<TextFileEditorModel>;
75 76 77 78
	private inConflictMode: boolean;
	private inOrphanMode: boolean;
	private inErrorMode: boolean;

E
Erich Gamma 已提交
79 80 81
	constructor(
		resource: URI,
		preferredEncoding: string,
82
		@INotificationService private notificationService: INotificationService,
E
Erich Gamma 已提交
83 84 85 86
		@IModeService modeService: IModeService,
		@IModelService modelService: IModelService,
		@IFileService private fileService: IFileService,
		@IInstantiationService private instantiationService: IInstantiationService,
87
		@ITelemetryService private telemetryService: ITelemetryService,
88
		@ITextFileService private textFileService: ITextFileService,
89
		@IBackupFileService private backupFileService: IBackupFileService,
90
		@IEnvironmentService private environmentService: IEnvironmentService,
T
t-amqi 已提交
91
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
I
isidor 已提交
92 93
		@IHashService private hashService: IHashService,
		@ILogService private logService: ILogService
E
Erich Gamma 已提交
94 95
	) {
		super(modelService, modeService);
B
Benjamin Pasero 已提交
96

E
Erich Gamma 已提交
97 98
		this.resource = resource;
		this.preferredEncoding = preferredEncoding;
99
		this.inOrphanMode = false;
E
Erich Gamma 已提交
100 101
		this.dirty = false;
		this.versionId = 0;
B
Benjamin Pasero 已提交
102
		this.lastSaveAttemptTime = 0;
103
		this.saveSequentializer = new SaveSequentializer();
104

B
Benjamin Pasero 已提交
105 106
		this.contentChangeEventScheduler = this._register(new RunOnceScheduler(() => this._onDidContentChange.fire(StateChange.CONTENT_CHANGE), TextFileEditorModel.DEFAULT_CONTENT_CHANGE_BUFFER_DELAY));
		this.orphanedChangeEventScheduler = this._register(new RunOnceScheduler(() => this._onDidStateChange.fire(StateChange.ORPHANED_CHANGE), TextFileEditorModel.DEFAULT_ORPHANED_CHANGE_BUFFER_DELAY));
107

108
		this.updateAutoSaveConfiguration(textFileService.getAutoSaveConfiguration());
B
Benjamin Pasero 已提交
109

110
		this.registerListeners();
E
Erich Gamma 已提交
111 112
	}

113
	private registerListeners(): void {
B
Benjamin Pasero 已提交
114 115 116 117
		this._register(this.fileService.onFileChanges(e => this.onFileChanges(e)));
		this._register(this.textFileService.onAutoSaveConfigurationChange(config => this.updateAutoSaveConfiguration(config)));
		this._register(this.textFileService.onFilesAssociationChange(e => this.onFilesAssociationChange()));
		this._register(this.onDidStateChange(e => this.onStateChange(e)));
B
Benjamin Pasero 已提交
118
	}
119

B
Benjamin Pasero 已提交
120 121
	private onStateChange(e: StateChange): void {
		if (e === StateChange.REVERTED) {
122

B
Benjamin Pasero 已提交
123 124 125 126 127 128
			// Cancel any content change event promises as they are no longer valid.
			this.contentChangeEventScheduler.cancel();

			// Refire state change reverted events as content change events
			this._onDidContentChange.fire(StateChange.REVERTED);
		}
129 130
	}

131
	private onFileChanges(e: FileChangesEvent): void {
132 133 134 135 136 137 138 139 140 141 142
		let fileEventImpactsModel = false;
		let newInOrphanModeGuess: boolean;

		// If we are currently orphaned, we check if the model file was added back
		if (this.inOrphanMode) {
			const modelFileAdded = e.contains(this.resource, FileChangeType.ADDED);
			if (modelFileAdded) {
				newInOrphanModeGuess = false;
				fileEventImpactsModel = true;
			}
		}
143

144 145 146 147 148 149 150 151
		// Otherwise we check if the model file was deleted
		else {
			const modelFileDeleted = e.contains(this.resource, FileChangeType.DELETED);
			if (modelFileDeleted) {
				newInOrphanModeGuess = true;
				fileEventImpactsModel = true;
			}
		}
152

153
		if (fileEventImpactsModel && this.inOrphanMode !== newInOrphanModeGuess) {
154
			let checkOrphanedPromise: Thenable<boolean>;
155 156 157 158 159
			if (newInOrphanModeGuess) {
				// We have received reports of users seeing delete events even though the file still
				// exists (network shares issue: https://github.com/Microsoft/vscode/issues/13665).
				// Since we do not want to mark the model as orphaned, we have to check if the
				// file is really gone and not just a faulty file event.
160
				checkOrphanedPromise = timeout(100).then(() => {
161 162
					if (this.disposed) {
						return true;
163
					}
164 165

					return this.fileService.existsFile(this.resource).then(exists => !exists);
166
				});
167
			} else {
168
				checkOrphanedPromise = Promise.resolve(false);
169
			}
170

171
			checkOrphanedPromise.then(newInOrphanModeValidated => {
172 173 174 175
				if (this.inOrphanMode !== newInOrphanModeValidated && !this.disposed) {
					this.setOrphaned(newInOrphanModeValidated);
				}
			});
176 177 178 179 180 181 182 183 184 185
		}
	}

	private setOrphaned(orphaned: boolean): void {
		if (this.inOrphanMode !== orphaned) {
			this.inOrphanMode = orphaned;
			this.orphanedChangeEventScheduler.schedule();
		}
	}

186
	private updateAutoSaveConfiguration(config: IAutoSaveConfiguration): void {
B
Benjamin Pasero 已提交
187
		const autoSaveAfterMilliesEnabled = (typeof config.autoSaveDelay === 'number') && config.autoSaveDelay > 0;
E
Erich Gamma 已提交
188

B
Benjamin Pasero 已提交
189 190
		this.autoSaveAfterMilliesEnabled = autoSaveAfterMilliesEnabled;
		this.autoSaveAfterMillies = autoSaveAfterMilliesEnabled ? config.autoSaveDelay : void 0;
191 192
	}

B
Benjamin Pasero 已提交
193
	private onFilesAssociationChange(): void {
B
Benjamin Pasero 已提交
194 195 196 197
		if (!this.textEditorModel) {
			return;
		}

A
Alex Dima 已提交
198
		const firstLineText = this.getFirstLineText(this.textEditorModel);
A
Alex Dima 已提交
199
		const languageSelection = this.getOrCreateMode(this.modeService, void 0, firstLineText);
B
Benjamin Pasero 已提交
200

A
Alex Dima 已提交
201
		this.modelService.setMode(this.textEditorModel, languageSelection);
B
Benjamin Pasero 已提交
202 203
	}

B
Benjamin Pasero 已提交
204
	getVersionId(): number {
205 206 207
		return this.versionId;
	}

B
Benjamin Pasero 已提交
208
	revert(soft?: boolean): TPromise<void> {
E
Erich Gamma 已提交
209
		if (!this.isResolved()) {
B
Benjamin Pasero 已提交
210
			return Promise.resolve(null);
E
Erich Gamma 已提交
211 212
		}

213
		// Cancel any running auto-save
214
		this.cancelPendingAutoSave();
E
Erich Gamma 已提交
215 216

		// Unset flags
B
Benjamin Pasero 已提交
217
		const undo = this.setDirty(false);
E
Erich Gamma 已提交
218

B
Benjamin Pasero 已提交
219
		let loadPromise: TPromise<TextFileEditorModel>;
220 221 222
		if (soft) {
			loadPromise = TPromise.as(this);
		} else {
223
			loadPromise = this.load({ forceReadFromDisk: true });
224 225 226
		}

		return loadPromise.then(() => {
E
Erich Gamma 已提交
227 228

			// Emit file change event
229
			this._onDidStateChange.fire(StateChange.REVERTED);
230
		}, error => {
E
Erich Gamma 已提交
231

232
			// Set flags back to previous values, we are still dirty if revert failed
233
			undo();
E
Erich Gamma 已提交
234

B
Benjamin Pasero 已提交
235
			return Promise.reject(error);
E
Erich Gamma 已提交
236 237 238
		});
	}

B
Benjamin Pasero 已提交
239
	load(options?: ILoadOptions): TPromise<TextFileEditorModel> {
I
isidor 已提交
240
		this.logService.trace('load() - enter', this.resource);
E
Erich Gamma 已提交
241

B
Benjamin Pasero 已提交
242 243 244
		// It is very important to not reload the model when the model is dirty.
		// We also only want to reload the model from the disk if no save is pending
		// to avoid data loss.
245
		if (this.dirty || this.saveSequentializer.hasPendingSave()) {
I
isidor 已提交
246
			this.logService.trace('load() - exit - without loading because model is dirty or being saved', this.resource);
E
Erich Gamma 已提交
247 248 249 250

			return TPromise.as(this);
		}

251 252
		// Only for new models we support to load from backup
		if (!this.textEditorModel && !this.createTextEditorModelPromise) {
B
Benjamin Pasero 已提交
253
			return this.loadFromBackup(options);
254 255 256
		}

		// Otherwise load from file resource
257
		return this.loadFromFile(options);
258 259
	}

B
Benjamin Pasero 已提交
260
	private loadFromBackup(options?: ILoadOptions): TPromise<TextFileEditorModel> {
261 262 263 264 265 266 267 268 269
		return this.backupFileService.loadBackupResource(this.resource).then(backup => {

			// Make sure meanwhile someone else did not suceed or start loading
			if (this.createTextEditorModelPromise || this.textEditorModel) {
				return this.createTextEditorModelPromise || TPromise.as(this);
			}

			// If we have a backup, continue loading with it
			if (!!backup) {
270
				const content: IRawTextContent = {
271
					resource: this.resource,
272
					name: path.basename(this.resource.fsPath),
273 274
					mtime: Date.now(),
					etag: void 0,
275
					value: createTextBufferFactory(''), /* will be filled later from backup */
I
isidor 已提交
276 277
					encoding: this.fileService.encoding.getWriteEncoding(this.resource, this.preferredEncoding),
					isReadonly: false
278 279
				};

280
				return this.loadWithContent(content, options, backup);
281 282 283
			}

			// Otherwise load from file
284
			return this.loadFromFile(options);
285 286 287
		});
	}

288 289 290
	private loadFromFile(options?: ILoadOptions): TPromise<TextFileEditorModel> {
		const forceReadFromDisk = options && options.forceReadFromDisk;
		const allowBinary = this.isResolved() /* always allow if we resolved previously */ || (options && options.allowBinary);
291

E
Erich Gamma 已提交
292 293
		// Decide on etag
		let etag: string;
294 295
		if (forceReadFromDisk) {
			etag = void 0; // reset ETag if we enforce to read from disk
296 297
		} else if (this.lastResolvedDiskStat) {
			etag = this.lastResolvedDiskStat.etag; // otherwise respect etag to support caching
E
Erich Gamma 已提交
298 299
		}

B
Benjamin Pasero 已提交
300 301 302 303 304 305 306 307
		// Ensure to track the versionId before doing a long running operation
		// to make sure the model was not changed in the meantime which would
		// indicate that the user or program has made edits. If we would ignore
		// this, we could potentially loose the changes that were made because
		// after resolving the content we update the model and reset the dirty
		// flag.
		const currentVersionId = this.versionId;

T
t-amqi 已提交
308 309
		// Resolve Content
		return this.textFileService
310
			.resolveTextContent(this.resource, { acceptTextOnly: !allowBinary, etag, encoding: this.preferredEncoding })
B
Benjamin Pasero 已提交
311
			.then(content => {
312

B
Benjamin Pasero 已提交
313 314
				// Clear orphaned state when loading was successful
				this.setOrphaned(false);
315

B
Benjamin Pasero 已提交
316 317
				// Guard against the model having changed in the meantime
				if (currentVersionId === this.versionId) {
318
					return this.loadWithContent(content, options);
B
Benjamin Pasero 已提交
319
				}
320

B
Benjamin Pasero 已提交
321 322 323
				return this;
			}, error => {
				const result = error.fileOperationResult;
E
Erich Gamma 已提交
324

B
Benjamin Pasero 已提交
325 326
				// Apply orphaned state based on error code
				this.setOrphaned(result === FileOperationResult.FILE_NOT_FOUND);
E
Erich Gamma 已提交
327

B
Benjamin Pasero 已提交
328 329
				// NotModified status is expected and can be handled gracefully
				if (result === FileOperationResult.FILE_NOT_MODIFIED_SINCE) {
330

B
Benjamin Pasero 已提交
331 332 333 334
					// Guard against the model having changed in the meantime
					if (currentVersionId === this.versionId) {
						this.setDirty(false); // Ensure we are not tracking a stale state
					}
E
Erich Gamma 已提交
335

B
Benjamin Pasero 已提交
336 337
					return TPromise.as<TextFileEditorModel>(this);
				}
338

B
Benjamin Pasero 已提交
339 340 341 342 343 344
				// Ignore when a model has been resolved once and the file was deleted meanwhile. Since
				// we already have the model loaded, we can return to this state and update the orphaned
				// flag to indicate that this model has no version on disk anymore.
				if (this.isResolved() && result === FileOperationResult.FILE_NOT_FOUND) {
					return TPromise.as<TextFileEditorModel>(this);
				}
345

B
Benjamin Pasero 已提交
346
				// Otherwise bubble up the error
B
Benjamin Pasero 已提交
347
				return Promise.reject<TextFileEditorModel>(error);
B
Benjamin Pasero 已提交
348
			});
349
	}
E
Erich Gamma 已提交
350

351
	private loadWithContent(content: IRawTextContent, options?: ILoadOptions, backup?: URI): TPromise<TextFileEditorModel> {
352
		return this.doLoadWithContent(content, backup).then(model => {
353
			// Telemetry: We log the fileGet telemetry event after the model has been loaded to ensure a good mimetype
354 355
			const settingsType = this.getTypeIfSettings();
			if (settingsType) {
356
				/* __GDPR__
357
					"settingsRead" : {
358
						"settingsType": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
359
					}
360
				*/
361
				this.telemetryService.publicLog('settingsRead', { settingsType }); // Do not log read to user settings.json and .vscode folder as a fileGet event as it ruins our JSON usage data
362 363 364
			} else {
				/* __GDPR__
					"fileGet" : {
365 366 367
						"${include}": [
							"${FileTelemetryData}"
						]
368 369
					}
				*/
370
				this.telemetryService.publicLog('fileGet', this.getTelemetryData(options && options.reason ? options.reason : LoadReason.OTHER));
371
			}
372 373 374 375 376

			return model;
		});
	}

377
	private doLoadWithContent(content: IRawTextContent, backup?: URI): TPromise<TextFileEditorModel> {
I
isidor 已提交
378
		this.logService.trace('load() - resolved content', this.resource);
379 380

		// Update our resolved disk stat model
B
Benjamin Pasero 已提交
381
		this.updateLastResolvedDiskStat({
382 383 384 385 386
			resource: this.resource,
			name: content.name,
			mtime: content.mtime,
			etag: content.etag,
			isDirectory: false,
387
			isSymbolicLink: false,
I
isidor 已提交
388 389
			children: void 0,
			isReadonly: content.isReadonly
B
Benjamin Pasero 已提交
390
		} as IFileStat);
391 392 393 394 395 396 397 398 399 400 401

		// Keep the original encoding to not loose it when saving
		const oldEncoding = this.contentEncoding;
		this.contentEncoding = content.encoding;

		// Handle events if encoding changed
		if (this.preferredEncoding) {
			this.updatePreferredEncoding(this.contentEncoding); // make sure to reflect the real encoding of the file (never out of sync)
		} else if (oldEncoding !== this.contentEncoding) {
			this._onDidStateChange.fire(StateChange.ENCODING);
		}
E
Erich Gamma 已提交
402

403 404
		// Update Existing Model
		if (this.textEditorModel) {
405
			return this.doUpdateTextModel(content.value);
406
		}
E
Erich Gamma 已提交
407

408 409
		// Join an existing request to create the editor model to avoid race conditions
		else if (this.createTextEditorModelPromise) {
I
isidor 已提交
410
			this.logService.trace('load() - join existing text editor model promise', this.resource);
E
Erich Gamma 已提交
411

412 413
			return this.createTextEditorModelPromise;
		}
E
Erich Gamma 已提交
414

415
		// Create New Model
416
		return this.doCreateTextModel(content.resource, content.value, backup);
417
	}
E
Erich Gamma 已提交
418

419
	private doUpdateTextModel(value: ITextBufferFactory): TPromise<TextFileEditorModel> {
I
isidor 已提交
420
		this.logService.trace('load() - updated text editor model', this.resource);
421

422 423
		// Ensure we are not tracking a stale state
		this.setDirty(false);
424

425
		// Update model value in a block that ignores model content change events
426 427 428 429 430 431 432
		this.blockModelContentChange = true;
		try {
			this.updateTextEditorModel(value);
		} finally {
			this.blockModelContentChange = false;
		}

433 434 435
		// Ensure we track the latest saved version ID given that the contents changed
		this.updateSavedVersionId();

B
Benjamin Pasero 已提交
436
		return TPromise.as<TextFileEditorModel>(this);
437 438
	}

439
	private doCreateTextModel(resource: URI, value: ITextBufferFactory, backup: URI): TPromise<TextFileEditorModel> {
I
isidor 已提交
440
		this.logService.trace('load() - created text editor model', this.resource);
441

442
		this.createTextEditorModelPromise = this.doLoadBackup(backup).then(backupContent => {
443
			const hasBackupContent = !!backupContent;
444 445 446 447 448 449 450 451 452 453 454 455

			return this.createTextEditorModel(hasBackupContent ? backupContent : value, resource).then(() => {
				this.createTextEditorModelPromise = null;

				// We restored a backup so we have to set the model as being dirty
				// We also want to trigger auto save if it is enabled to simulate the exact same behaviour
				// you would get if manually making the model dirty (fixes https://github.com/Microsoft/vscode/issues/16977)
				if (hasBackupContent) {
					this.makeDirty();
					if (this.autoSaveAfterMilliesEnabled) {
						this.doAutoSave(this.versionId);
					}
456 457
				}

458 459 460 461 462
				// Ensure we are not tracking a stale state
				else {
					this.setDirty(false);
				}

B
Benjamin Pasero 已提交
463 464
				// Model Listeners
				this.installModelListeners();
465 466 467 468 469

				return this;
			}, error => {
				this.createTextEditorModelPromise = null;

B
Benjamin Pasero 已提交
470
				return Promise.reject<TextFileEditorModel>(error);
471
			});
472
		});
473

474 475 476
		return this.createTextEditorModelPromise;
	}

B
Benjamin Pasero 已提交
477 478
	private installModelListeners(): void {

479 480 481
		// See https://github.com/Microsoft/vscode/issues/30189
		// This code has been extracted to a different method because it caused a memory leak
		// where `value` was captured in the content change listener closure scope.
B
Benjamin Pasero 已提交
482 483

		// Content Change
B
Benjamin Pasero 已提交
484
		this._register(this.textEditorModel.onDidChangeContent(() => this.onModelContentChanged()));
485 486
	}

487
	private doLoadBackup(backup: URI): TPromise<ITextBufferFactory> {
488 489 490
		if (!backup) {
			return TPromise.as(null);
		}
491

492
		return this.backupFileService.resolveBackupContent(backup).then(backupContent => backupContent, error => null /* ignore errors */);
E
Erich Gamma 已提交
493 494
	}

A
Alex Dima 已提交
495 496
	protected getOrCreateMode(modeService: IModeService, preferredModeIds: string, firstLineText?: string): ILanguageSelection {
		return modeService.createByFilepathOrFirstLine(this.resource.fsPath, firstLineText);
E
Erich Gamma 已提交
497 498
	}

499
	private onModelContentChanged(): void {
I
isidor 已提交
500
		this.logService.trace(`onModelContentChanged() - enter`, this.resource);
E
Erich Gamma 已提交
501 502 503

		// In any case increment the version id because it tracks the textual content state of the model at all times
		this.versionId++;
I
isidor 已提交
504
		this.logService.trace(`onModelContentChanged() - new versionId ${this.versionId}`, this.resource);
E
Erich Gamma 已提交
505 506 507 508 509 510 511 512 513 514

		// Ignore if blocking model changes
		if (this.blockModelContentChange) {
			return;
		}

		// The contents changed as a matter of Undo and the version reached matches the saved one
		// In this case we clear the dirty flag and emit a SAVED event to indicate this state.
		// Note: we currently only do this check when auto-save is turned off because there you see
		// a dirty indicator that you want to get rid of when undoing to the saved version.
515
		if (!this.autoSaveAfterMilliesEnabled && this.textEditorModel.getAlternativeVersionId() === this.bufferSavedVersionId) {
I
isidor 已提交
516
			this.logService.trace('onModelContentChanged() - model content changed back to last saved version', this.resource);
E
Erich Gamma 已提交
517 518

			// Clear flags
519
			const wasDirty = this.dirty;
E
Erich Gamma 已提交
520 521 522
			this.setDirty(false);

			// Emit event
523
			if (wasDirty) {
524
				this._onDidStateChange.fire(StateChange.REVERTED);
525
			}
E
Erich Gamma 已提交
526 527 528 529

			return;
		}

I
isidor 已提交
530
		this.logService.trace('onModelContentChanged() - model content changed and marked as dirty', this.resource);
E
Erich Gamma 已提交
531 532

		// Mark as dirty
B
Benjamin Pasero 已提交
533
		this.makeDirty();
E
Erich Gamma 已提交
534 535

		// Start auto save process unless we are in conflict resolution mode and unless it is disabled
536
		if (this.autoSaveAfterMilliesEnabled) {
537
			if (!this.inConflictMode) {
E
Erich Gamma 已提交
538 539
				this.doAutoSave(this.versionId);
			} else {
I
isidor 已提交
540
				this.logService.trace('makeDirty() - prevented save because we are in conflict resolution mode', this.resource);
E
Erich Gamma 已提交
541 542
			}
		}
543

544 545
		// Handle content change events
		this.contentChangeEventScheduler.schedule();
E
Erich Gamma 已提交
546 547
	}

B
Benjamin Pasero 已提交
548
	private makeDirty(): void {
E
Erich Gamma 已提交
549 550

		// Track dirty state and version id
B
Benjamin Pasero 已提交
551
		const wasDirty = this.dirty;
E
Erich Gamma 已提交
552 553 554 555
		this.setDirty(true);

		// Emit as Event if we turned dirty
		if (!wasDirty) {
556
			this._onDidStateChange.fire(StateChange.DIRTY);
E
Erich Gamma 已提交
557 558 559
		}
	}

560
	private doAutoSave(versionId: number): void {
I
isidor 已提交
561
		this.logService.trace(`doAutoSave() - enter for versionId ${versionId}`, this.resource);
E
Erich Gamma 已提交
562 563

		// Cancel any currently running auto saves to make this the one that succeeds
564
		this.cancelPendingAutoSave();
E
Erich Gamma 已提交
565

566 567
		// Create new save timer and store it for disposal as needed
		const handle = setTimeout(() => {
E
Erich Gamma 已提交
568 569 570

			// Only trigger save if the version id has not changed meanwhile
			if (versionId === this.versionId) {
571
				this.doSave(versionId, { reason: SaveReason.AUTO }); // Very important here to not return the promise because if the timeout promise is canceled it will bubble up the error otherwise - do not change
E
Erich Gamma 已提交
572
			}
573
		}, this.autoSaveAfterMillies);
E
Erich Gamma 已提交
574

575
		this.autoSaveDisposable = toDisposable(() => clearTimeout(handle));
E
Erich Gamma 已提交
576 577
	}

578 579 580 581
	private cancelPendingAutoSave(): void {
		if (this.autoSaveDisposable) {
			this.autoSaveDisposable.dispose();
			this.autoSaveDisposable = void 0;
E
Erich Gamma 已提交
582 583 584
		}
	}

B
Benjamin Pasero 已提交
585
	save(options: ISaveOptions = Object.create(null)): TPromise<void> {
E
Erich Gamma 已提交
586
		if (!this.isResolved()) {
B
Benjamin Pasero 已提交
587
			return Promise.resolve(null);
E
Erich Gamma 已提交
588 589
		}

I
isidor 已提交
590
		this.logService.trace('save() - enter', this.resource);
E
Erich Gamma 已提交
591 592

		// Cancel any currently running auto saves to make this the one that succeeds
593
		this.cancelPendingAutoSave();
E
Erich Gamma 已提交
594

595
		return this.doSave(this.versionId, options);
E
Erich Gamma 已提交
596 597
	}

598
	private doSave(versionId: number, options: ISaveOptions): TPromise<void> {
599
		if (isUndefinedOrNull(options.reason)) {
600 601 602
			options.reason = SaveReason.EXPLICIT;
		}

I
isidor 已提交
603
		this.logService.trace(`doSave(${versionId}) - enter with versionId ' + versionId`, this.resource);
E
Erich Gamma 已提交
604 605

		// Lookup any running pending save for this versionId and return it if found
B
Benjamin Pasero 已提交
606 607 608 609
		//
		// Scenario: user invoked the save action multiple times quickly for the same contents
		//           while the save was not yet finished to disk
		//
610
		if (this.saveSequentializer.hasPendingSave(versionId)) {
I
isidor 已提交
611
			this.logService.trace(`doSave(${versionId}) - exit - found a pending save for versionId ${versionId}`, this.resource);
E
Erich Gamma 已提交
612

613
			return this.saveSequentializer.pendingSave;
E
Erich Gamma 已提交
614 615
		}

616
		// Return early if not dirty (unless forced) or version changed meanwhile
B
Benjamin Pasero 已提交
617 618 619 620 621 622
		//
		// Scenario A: user invoked save action even though the model is not dirty
		// Scenario B: auto save was triggered for a certain change by the user but meanwhile the user changed
		//             the contents and the version for which auto save was started is no longer the latest.
		//             Thus we avoid spawning multiple auto saves and only take the latest.
		//
623
		if ((!options.force && !this.dirty) || versionId !== this.versionId) {
I
isidor 已提交
624
			this.logService.trace(`doSave(${versionId}) - exit - because not dirty and/or versionId is different (this.isDirty: ${this.dirty}, this.versionId: ${this.versionId})`, this.resource);
E
Erich Gamma 已提交
625

B
Benjamin Pasero 已提交
626
			return Promise.resolve(null);
E
Erich Gamma 已提交
627 628
		}

629
		// Return if currently saving by storing this save request as the next save that should happen.
630
		// Never ever must 2 saves execute at the same time because this can lead to dirty writes and race conditions.
B
Benjamin Pasero 已提交
631
		//
632
		// Scenario A: auto save was triggered and is currently busy saving to disk. this takes long enough that another auto save
633
		//             kicks in.
634 635
		// Scenario B: save is very slow (e.g. network share) and the user manages to change the buffer and trigger another save
		//             while the first save has not returned yet.
B
Benjamin Pasero 已提交
636
		//
637
		if (this.saveSequentializer.hasPendingSave()) {
I
isidor 已提交
638
			this.logService.trace(`doSave(${versionId}) - exit - because busy saving`, this.resource);
E
Erich Gamma 已提交
639

640
			// Register this as the next upcoming save and return
641
			return this.saveSequentializer.setNext(() => this.doSave(this.versionId /* make sure to use latest version id here */, options));
E
Erich Gamma 已提交
642 643 644 645
		}

		// Push all edit operations to the undo stack so that the user has a chance to
		// Ctrl+Z back to the saved version. We only do this when auto-save is turned off
646
		if (!this.autoSaveAfterMilliesEnabled) {
E
Erich Gamma 已提交
647 648 649
			this.textEditorModel.pushStackElement();
		}

B
Benjamin Pasero 已提交
650
		// A save participant can still change the model now and since we are so close to saving
E
Erich Gamma 已提交
651 652
		// we do not want to trigger another auto save or similar, so we block this
		// In addition we update our version right after in case it changed because of a model change
653
		// Save participants can also be skipped through API.
J
Johannes Rieken 已提交
654
		let saveParticipantPromise = TPromise.as(versionId);
655
		if (TextFileEditorModel.saveParticipant && !options.skipSaveParticipants) {
B
💄  
Benjamin Pasero 已提交
656
			const onCompleteOrError = () => {
J
Johannes Rieken 已提交
657
				this.blockModelContentChange = false;
B
💄  
Benjamin Pasero 已提交
658

659
				return this.versionId;
B
💄  
Benjamin Pasero 已提交
660 661
			};

J
Johannes Rieken 已提交
662 663
			saveParticipantPromise = TPromise.as(undefined).then(() => {
				this.blockModelContentChange = true;
B
💄  
Benjamin Pasero 已提交
664

665
				return TextFileEditorModel.saveParticipant.participate(this, { reason: options.reason });
B
💄  
Benjamin Pasero 已提交
666
			}).then(onCompleteOrError, onCompleteOrError);
E
Erich Gamma 已提交
667 668
		}

669
		// mark the save participant as current pending save operation
670
		return this.saveSequentializer.setPending(versionId, saveParticipantPromise.then(newVersionId => {
E
Erich Gamma 已提交
671

672 673 674 675 676
			// We have to protect against being disposed at this point. It could be that the save() operation
			// was triggerd followed by a dispose() operation right after without waiting. Typically we cannot
			// be disposed if we are dirty, but if we are not dirty, save() and dispose() can still be triggered
			// one after the other without waiting for the save() to complete. If we are disposed(), we risk
			// saving contents to disk that are stale (see https://github.com/Microsoft/vscode/issues/50942).
677
			// To fix this issue, we will not store the contents to disk when we got disposed.
678 679 680 681
			if (this.disposed) {
				return void 0;
			}

B
Benjamin Pasero 已提交
682 683
			// Under certain conditions we do a short-cut of flushing contents to disk when we can assume that
			// the file has not changed and as such was not dirty before.
684 685 686 687 688 689
			// The conditions are all of:
			// - a forced, explicit save (Ctrl+S)
			// - the model is not dirty (otherwise we know there are changed which needs to go to the file)
			// - the model is not in orphan mode (because in that case we know the file does not exist on disk)
			// - the model version did not change due to save participants running
			if (options.force && !this.dirty && !this.inOrphanMode && options.reason === SaveReason.EXPLICIT && versionId === newVersionId) {
B
Benjamin Pasero 已提交
690
				return this.doTouch(newVersionId);
691 692
			}

693
			// update versionId with its new value (if pre-save changes happened)
J
Johannes Rieken 已提交
694 695 696 697 698 699 700 701 702
			versionId = newVersionId;

			// Clear error flag since we are trying to save again
			this.inErrorMode = false;

			// Remember when this model was saved last
			this.lastSaveAttemptTime = Date.now();

			// Save to Disk
703
			// mark the save operation as currently pending with the versionId (it might have changed from a save participant triggering)
I
isidor 已提交
704
			this.logService.trace(`doSave(${versionId}) - before updateContent()`, this.resource);
705
			return this.saveSequentializer.setPending(newVersionId, this.fileService.updateContent(this.lastResolvedDiskStat.resource, this.createSnapshot(), {
706 707
				overwriteReadonly: options.overwriteReadonly,
				overwriteEncoding: options.overwriteEncoding,
708
				mtime: this.lastResolvedDiskStat.mtime,
J
Johannes Rieken 已提交
709
				encoding: this.getEncoding(),
710 711
				etag: this.lastResolvedDiskStat.etag,
				writeElevated: options.writeElevated
712
			}).then(stat => {
I
isidor 已提交
713
				this.logService.trace(`doSave(${versionId}) - after updateContent()`, this.resource);
J
Johannes Rieken 已提交
714 715

				// Telemetry
716 717
				const settingsType = this.getTypeIfSettings();
				if (settingsType) {
K
kieferrm 已提交
718
					/* __GDPR__
719
						"settingsWritten" : {
720
							"settingsType": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
721
						}
K
kieferrm 已提交
722
					*/
723
					this.telemetryService.publicLog('settingsWritten', { settingsType }); // Do not log write to user settings.json and .vscode folder as a filePUT event as it ruins our JSON usage data
724
				} else {
K
kieferrm 已提交
725
					/* __GDPR__
K
kieferrm 已提交
726
						"filePUT" : {
727 728 729
							"${include}": [
								"${FileTelemetryData}"
							]
K
kieferrm 已提交
730 731
						}
					*/
732
					this.telemetryService.publicLog('filePUT', this.getTelemetryData(options.reason));
733
				}
J
Johannes Rieken 已提交
734 735 736

				// Update dirty state unless model has changed meanwhile
				if (versionId === this.versionId) {
I
isidor 已提交
737
					this.logService.trace(`doSave(${versionId}) - setting dirty to false because versionId did not change`, this.resource);
J
Johannes Rieken 已提交
738 739
					this.setDirty(false);
				} else {
I
isidor 已提交
740
					this.logService.trace(`doSave(${versionId}) - not setting dirty to false because versionId did change meanwhile`, this.resource);
J
Johannes Rieken 已提交
741
				}
E
Erich Gamma 已提交
742

743
				// Updated resolved stat with updated stat
744
				this.updateLastResolvedDiskStat(stat);
E
Erich Gamma 已提交
745

746 747 748
				// Cancel any content change event promises as they are no longer valid
				this.contentChangeEventScheduler.cancel();

J
Johannes Rieken 已提交
749 750
				// Emit File Saved Event
				this._onDidStateChange.fire(StateChange.SAVED);
751
			}, error => {
752 753
				if (!error) {
					error = new Error('Unknown Save Error'); // TODO@remote we should never get null as error (https://github.com/Microsoft/vscode/issues/55051)
M
Martin Aeschlimann 已提交
754 755
				}

I
isidor 已提交
756
				this.logService.error(`doSave(${versionId}) - exit - resulted in a save error: ${error.toString()}`, this.resource);
E
Erich Gamma 已提交
757

758
				// Flag as error state in the model
J
Johannes Rieken 已提交
759
				this.inErrorMode = true;
E
Erich Gamma 已提交
760

761
				// Look out for a save conflict
762
				if ((<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_MODIFIED_SINCE) {
763 764 765
					this.inConflictMode = true;
				}

J
Johannes Rieken 已提交
766 767
				// Show to user
				this.onSaveError(error);
E
Erich Gamma 已提交
768

J
Johannes Rieken 已提交
769 770
				// Emit as event
				this._onDidStateChange.fire(StateChange.SAVE_ERROR);
771 772
			}));
		}));
E
Erich Gamma 已提交
773 774
	}

775
	private getTypeIfSettings(): string {
776
		if (path.extname(this.resource.fsPath) !== '.json') {
777
			return '';
778
		}
779 780

		// Check for global settings file
S
Sandeep Somavarapu 已提交
781
		if (isEqual(this.resource, URI.file(this.environmentService.appSettingsPath), !isLinux)) {
782 783 784 785 786 787 788 789 790 791 792 793 794 795
			return 'global-settings';
		}

		// Check for keybindings file
		if (isEqual(this.resource, URI.file(this.environmentService.appKeybindingsPath), !isLinux)) {
			return 'keybindings';
		}

		// Check for locale file
		if (isEqual(this.resource, URI.file(path.join(this.environmentService.appSettingsHome, 'locale.json')), !isLinux)) {
			return 'locale';
		}

		// Check for snippets
796
		if (isEqualOrParent(this.resource, URI.file(path.join(this.environmentService.appSettingsHome, 'snippets')))) {
797
			return 'snippets';
798 799 800
		}

		// Check for workspace settings file
801 802
		const folders = this.contextService.getWorkspace().folders;
		for (let i = 0; i < folders.length; i++) {
803
			if (isEqualOrParent(this.resource, folders[i].toResource('.vscode'))) {
804 805 806 807 808 809 810 811
				const filename = path.basename(this.resource.fsPath);
				if (TextFileEditorModel.WHITELIST_WORKSPACE_JSON.indexOf(filename) > -1) {
					return `.vscode/${filename}`;
				}
			}
		}

		return '';
812 813
	}

814
	private getTelemetryData(reason: number): Object {
R
Ramya Achutha Rao 已提交
815 816
		const ext = path.extname(this.resource.fsPath);
		const fileName = path.basename(this.resource.fsPath);
817 818
		const telemetryData = {
			mimeType: guessMimeTypes(this.resource.fsPath).join(', '),
R
Ramya Achutha Rao 已提交
819
			ext,
820 821 822 823
			path: this.hashService.createSHA1(this.resource.fsPath),
			reason
		};

R
Ramya Achutha Rao 已提交
824 825
		if (ext === '.json' && TextFileEditorModel.WHITELIST_JSON.indexOf(fileName) > -1) {
			telemetryData['whitelistedjson'] = fileName;
826 827 828 829 830 831 832 833 834 835 836 837 838 839
		}

		/* __GDPR__FRAGMENT__
			"FileTelemetryData" : {
				"mimeType" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
				"ext": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
				"path": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
				"reason": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
				"whitelistedjson": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
			}
		*/
		return telemetryData;
	}

B
Benjamin Pasero 已提交
840 841 842 843 844 845
	private doTouch(versionId: number): TPromise<void> {
		return this.saveSequentializer.setPending(versionId, this.fileService.updateContent(this.lastResolvedDiskStat.resource, this.createSnapshot(), {
			mtime: this.lastResolvedDiskStat.mtime,
			encoding: this.getEncoding(),
			etag: this.lastResolvedDiskStat.etag
		}).then(stat => {
846 847 848

			// Updated resolved stat with updated stat since touching it might have changed mtime
			this.updateLastResolvedDiskStat(stat);
B
Benjamin Pasero 已提交
849
		}, error => onUnexpectedError(error) /* just log any error but do not notify the user since the file was not dirty */));
850 851
	}

E
Erich Gamma 已提交
852
	private setDirty(dirty: boolean): () => void {
B
Benjamin Pasero 已提交
853
		const wasDirty = this.dirty;
854
		const wasInConflictMode = this.inConflictMode;
B
Benjamin Pasero 已提交
855 856
		const wasInErrorMode = this.inErrorMode;
		const oldBufferSavedVersionId = this.bufferSavedVersionId;
E
Erich Gamma 已提交
857 858 859

		if (!dirty) {
			this.dirty = false;
860
			this.inConflictMode = false;
E
Erich Gamma 已提交
861
			this.inErrorMode = false;
862
			this.updateSavedVersionId();
E
Erich Gamma 已提交
863 864 865 866 867 868 869
		} else {
			this.dirty = true;
		}

		// Return function to revert this call
		return () => {
			this.dirty = wasDirty;
870
			this.inConflictMode = wasInConflictMode;
E
Erich Gamma 已提交
871 872 873 874 875
			this.inErrorMode = wasInErrorMode;
			this.bufferSavedVersionId = oldBufferSavedVersionId;
		};
	}

876 877 878 879 880 881 882 883 884 885 886
	private updateSavedVersionId(): void {
		// we remember the models alternate version id to remember when the version
		// of the model matches with the saved version on disk. we need to keep this
		// in order to find out if the model changed back to a saved version (e.g.
		// when undoing long enough to reach to a version that is saved and then to
		// clear the dirty flag)
		if (this.textEditorModel) {
			this.bufferSavedVersionId = this.textEditorModel.getAlternativeVersionId();
		}
	}

887
	private updateLastResolvedDiskStat(newVersionOnDiskStat: IFileStat): void {
E
Erich Gamma 已提交
888 889

		// First resolve - just take
890 891
		if (!this.lastResolvedDiskStat) {
			this.lastResolvedDiskStat = newVersionOnDiskStat;
E
Erich Gamma 已提交
892 893 894
		}

		// Subsequent resolve - make sure that we only assign it if the mtime is equal or has advanced.
B
Benjamin Pasero 已提交
895 896
		// This prevents race conditions from loading and saving. If a save comes in late after a revert
		// was called, the mtime could be out of sync.
897 898
		else if (this.lastResolvedDiskStat.mtime <= newVersionOnDiskStat.mtime) {
			this.lastResolvedDiskStat = newVersionOnDiskStat;
E
Erich Gamma 已提交
899 900 901 902 903 904 905 906 907 908 909 910 911 912
		}
	}

	private onSaveError(error: any): void {

		// Prepare handler
		if (!TextFileEditorModel.saveErrorHandler) {
			TextFileEditorModel.setSaveErrorHandler(this.instantiationService.createInstance(DefaultSaveErrorHandler));
		}

		// Handle
		TextFileEditorModel.saveErrorHandler.onSaveError(error, this);
	}

B
Benjamin Pasero 已提交
913
	isDirty(): boolean {
E
Erich Gamma 已提交
914 915 916
		return this.dirty;
	}

B
Benjamin Pasero 已提交
917
	getLastSaveAttemptTime(): number {
B
Benjamin Pasero 已提交
918
		return this.lastSaveAttemptTime;
E
Erich Gamma 已提交
919 920
	}

B
Benjamin Pasero 已提交
921
	getETag(): string {
922
		return this.lastResolvedDiskStat ? this.lastResolvedDiskStat.etag : null;
E
Erich Gamma 已提交
923 924
	}

B
Benjamin Pasero 已提交
925
	hasState(state: ModelState): boolean {
926 927 928 929 930 931 932 933 934 935 936 937 938
		switch (state) {
			case ModelState.CONFLICT:
				return this.inConflictMode;
			case ModelState.DIRTY:
				return this.dirty;
			case ModelState.ERROR:
				return this.inErrorMode;
			case ModelState.ORPHAN:
				return this.inOrphanMode;
			case ModelState.PENDING_SAVE:
				return this.saveSequentializer.hasPendingSave();
			case ModelState.SAVED:
				return !this.dirty;
E
Erich Gamma 已提交
939 940 941
		}
	}

B
Benjamin Pasero 已提交
942
	getEncoding(): string {
E
Erich Gamma 已提交
943 944 945
		return this.preferredEncoding || this.contentEncoding;
	}

B
Benjamin Pasero 已提交
946
	setEncoding(encoding: string, mode: EncodingMode): void {
E
Erich Gamma 已提交
947 948 949 950 951 952 953 954 955 956 957 958 959 960
		if (!this.isNewEncoding(encoding)) {
			return; // return early if the encoding is already the same
		}

		// Encode: Save with encoding
		if (mode === EncodingMode.Encode) {
			this.updatePreferredEncoding(encoding);

			// Save
			if (!this.isDirty()) {
				this.versionId++; // needs to increment because we change the model potentially
				this.makeDirty();
			}

961
			if (!this.inConflictMode) {
962
				this.save({ overwriteEncoding: true });
E
Erich Gamma 已提交
963 964 965 966 967 968
			}
		}

		// Decode: Load with encoding
		else {
			if (this.isDirty()) {
969
				this.notificationService.info(nls.localize('saveFileFirst', "The file is dirty. Please save it first before reopening it with another encoding."));
E
Erich Gamma 已提交
970 971 972 973 974 975 976

				return;
			}

			this.updatePreferredEncoding(encoding);

			// Load
977 978
			this.load({
				forceReadFromDisk: true	// because encoding has changed
979
			});
E
Erich Gamma 已提交
980 981 982
		}
	}

B
Benjamin Pasero 已提交
983
	updatePreferredEncoding(encoding: string): void {
E
Erich Gamma 已提交
984 985 986 987 988 989 990
		if (!this.isNewEncoding(encoding)) {
			return;
		}

		this.preferredEncoding = encoding;

		// Emit
991
		this._onDidStateChange.fire(StateChange.ENCODING);
E
Erich Gamma 已提交
992 993 994 995 996 997 998 999
	}

	private isNewEncoding(encoding: string): boolean {
		if (this.preferredEncoding === encoding) {
			return false; // return early if the encoding is already the same
		}

		if (!this.preferredEncoding && this.contentEncoding === encoding) {
1000
			return false; // also return if we don't have a preferred encoding but the content encoding is already the same
E
Erich Gamma 已提交
1001 1002 1003 1004 1005
		}

		return true;
	}

B
Benjamin Pasero 已提交
1006
	isResolved(): boolean {
1007
		return !isUndefinedOrNull(this.lastResolvedDiskStat);
E
Erich Gamma 已提交
1008 1009
	}

B
Benjamin Pasero 已提交
1010
	isReadonly(): boolean {
1011
		return this.lastResolvedDiskStat && this.lastResolvedDiskStat.isReadonly;
1012 1013
	}

B
Benjamin Pasero 已提交
1014
	isDisposed(): boolean {
E
Erich Gamma 已提交
1015 1016 1017
		return this.disposed;
	}

B
Benjamin Pasero 已提交
1018
	getResource(): URI {
E
Erich Gamma 已提交
1019 1020 1021
		return this.resource;
	}

B
Benjamin Pasero 已提交
1022
	getStat(): IFileStat {
B
Benjamin Pasero 已提交
1023 1024 1025
		return this.lastResolvedDiskStat;
	}

B
Benjamin Pasero 已提交
1026
	dispose(): void {
E
Erich Gamma 已提交
1027
		this.disposed = true;
1028 1029
		this.inConflictMode = false;
		this.inOrphanMode = false;
E
Erich Gamma 已提交
1030 1031 1032 1033
		this.inErrorMode = false;

		this.createTextEditorModelPromise = null;

1034
		this.cancelPendingAutoSave();
D
Daniel Imms 已提交
1035

E
Erich Gamma 已提交
1036 1037
		super.dispose();
	}
1038 1039
}

1040 1041
interface IPendingSave {
	versionId: number;
B
Benjamin Pasero 已提交
1042
	promise: Thenable<void>;
1043 1044
}

1045
interface ISaveOperation {
B
Benjamin Pasero 已提交
1046 1047 1048 1049
	promise: Thenable<void>;
	promiseResolve: () => void;
	promiseReject: (error: Error) => void;
	run: () => Thenable<void>;
1050 1051 1052
}

export class SaveSequentializer {
1053
	private _pendingSave: IPendingSave;
1054
	private _nextSave: ISaveOperation;
1055

B
Benjamin Pasero 已提交
1056
	hasPendingSave(versionId?: number): boolean {
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
		if (!this._pendingSave) {
			return false;
		}

		if (typeof versionId === 'number') {
			return this._pendingSave.versionId === versionId;
		}

		return !!this._pendingSave;
	}

B
Benjamin Pasero 已提交
1068
	get pendingSave(): Thenable<void> {
1069 1070 1071
		return this._pendingSave ? this._pendingSave.promise : void 0;
	}

B
Benjamin Pasero 已提交
1072
	setPending(versionId: number, promise: Thenable<void>): Thenable<void> {
1073 1074
		this._pendingSave = { versionId, promise };

1075
		promise.then(() => this.donePending(versionId), () => this.donePending(versionId));
1076 1077 1078 1079 1080 1081

		return promise;
	}

	private donePending(versionId: number): void {
		if (this._pendingSave && versionId === this._pendingSave.versionId) {
1082 1083 1084 1085 1086 1087

			// only set pending to done if the promise finished that is associated with that versionId
			this._pendingSave = void 0;

			// schedule the next save now that we are free if we have any
			this.triggerNextSave();
1088 1089 1090
		}
	}

1091 1092 1093 1094 1095 1096
	private triggerNextSave(): void {
		if (this._nextSave) {
			const saveOperation = this._nextSave;
			this._nextSave = void 0;

			// Run next save and complete on the associated promise
B
Benjamin Pasero 已提交
1097
			saveOperation.run().then(saveOperation.promiseResolve, saveOperation.promiseReject);
1098 1099 1100
		}
	}

B
Benjamin Pasero 已提交
1101
	setNext(run: () => Thenable<void>): Thenable<void> {
1102 1103 1104 1105 1106

		// this is our first next save, so we create associated promise with it
		// so that we can return a promise that completes when the save operation
		// has completed.
		if (!this._nextSave) {
B
Benjamin Pasero 已提交
1107 1108 1109 1110 1111
			let promiseResolve: () => void;
			let promiseReject: (error: Error) => void;
			const promise = new Promise<void>((resolve, reject) => {
				promiseResolve = resolve;
				promiseReject = reject;
1112 1113 1114 1115 1116
			});

			this._nextSave = {
				run,
				promise,
B
Benjamin Pasero 已提交
1117 1118
				promiseResolve: promiseResolve,
				promiseReject: promiseReject
1119 1120 1121 1122 1123 1124 1125 1126 1127
			};
		}

		// we have a previous next save, just overwrite it
		else {
			this._nextSave.run = run;
		}

		return this._nextSave.promise;
1128 1129 1130
	}
}

1131 1132
class DefaultSaveErrorHandler implements ISaveErrorHandler {

M
Matt Bierner 已提交
1133
	constructor(@INotificationService private notificationService: INotificationService) { }
1134

B
Benjamin Pasero 已提交
1135
	onSaveError(error: any, model: TextFileEditorModel): void {
1136
		this.notificationService.error(nls.localize('genericSaveError', "Failed to save '{0}': {1}", path.basename(model.getResource().fsPath), toErrorMessage(error, false)));
1137 1138
	}
}