textFileEditorModel.ts 40.6 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.
 *--------------------------------------------------------------------------------------------*/

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

E
Erich Gamma 已提交
35 36 37
/**
 * 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.
 */
38
export class TextFileEditorModel extends BaseTextEditorModel implements ITextFileEditorModel {
E
Erich Gamma 已提交
39

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

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

48 49
	private static saveParticipant: ISaveParticipant | null;
	static setSaveParticipant(handler: ISaveParticipant | null): void { TextFileEditorModel.saveParticipant = handler; }
E
Erich Gamma 已提交
50

B
Benjamin Pasero 已提交
51 52 53 54 55 56
	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 已提交
57 58 59 60 61 62
	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;
63
	private lastResolvedDiskStat: IFileStatWithMetadata;
E
Erich Gamma 已提交
64
	private blockModelContentChange: boolean;
65
	private autoSaveAfterMillies?: number;
66
	private autoSaveAfterMilliesEnabled: boolean;
67
	private autoSaveDisposable?: IDisposable;
68
	private contentChangeEventScheduler: RunOnceScheduler;
69
	private orphanedChangeEventScheduler: RunOnceScheduler;
70
	private saveSequentializer: SaveSequentializer;
E
Erich Gamma 已提交
71
	private disposed: boolean;
B
Benjamin Pasero 已提交
72
	private lastSaveAttemptTime: number;
M
Matt Bierner 已提交
73
	private createTextEditorModelPromise: Promise<TextFileEditorModel> | null;
74 75 76 77
	private inConflictMode: boolean;
	private inOrphanMode: boolean;
	private inErrorMode: boolean;

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

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

B
Benjamin Pasero 已提交
103 104
		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));
105

106
		this.updateAutoSaveConfiguration(textFileService.getAutoSaveConfiguration());
B
Benjamin Pasero 已提交
107

108
		this.registerListeners();
E
Erich Gamma 已提交
109 110
	}

111
	private registerListeners(): void {
B
Benjamin Pasero 已提交
112 113 114 115
		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 已提交
116
	}
117

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

B
Benjamin Pasero 已提交
121 122 123 124 125 126
			// 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);
		}
127 128
	}

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

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

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

151
		if (fileEventImpactsModel && this.inOrphanMode !== newInOrphanModeGuess) {
J
Johannes Rieken 已提交
152
			let checkOrphanedPromise: Promise<boolean>;
153 154 155 156 157
			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.
158
				checkOrphanedPromise = timeout(100).then(() => {
159 160
					if (this.disposed) {
						return true;
161
					}
162

B
Benjamin Pasero 已提交
163
					return this.fileService.exists(this.resource).then(exists => !exists);
164
				});
165
			} else {
166
				checkOrphanedPromise = Promise.resolve(false);
167
			}
168

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

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

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

B
Benjamin Pasero 已提交
187
		this.autoSaveAfterMilliesEnabled = autoSaveAfterMilliesEnabled;
R
Rob Lourens 已提交
188
		this.autoSaveAfterMillies = autoSaveAfterMilliesEnabled ? config.autoSaveDelay : undefined;
189 190
	}

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

A
Alex Dima 已提交
196
		const firstLineText = this.getFirstLineText(this.textEditorModel);
R
Rob Lourens 已提交
197
		const languageSelection = this.getOrCreateMode(this.modeService, undefined, firstLineText);
B
Benjamin Pasero 已提交
198

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

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

206
	async revert(soft?: boolean): Promise<void> {
E
Erich Gamma 已提交
207
		if (!this.isResolved()) {
R
Rob Lourens 已提交
208
			return Promise.resolve(undefined);
E
Erich Gamma 已提交
209 210
		}

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

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

217
		let loadPromise: Promise<unknown>;
218
		if (soft) {
B
Benjamin Pasero 已提交
219
			loadPromise = Promise.resolve();
220
		} else {
221
			loadPromise = this.load({ forceReadFromDisk: true });
222 223
		}

224 225
		try {
			await loadPromise;
E
Erich Gamma 已提交
226 227

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

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

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

238
	load(options?: ILoadOptions): Promise<ITextFileEditorModel> {
I
isidor 已提交
239
		this.logService.trace('load() - enter', this.resource);
E
Erich Gamma 已提交
240

B
Benjamin Pasero 已提交
241 242 243
		// 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.
244
		if (this.dirty || this.saveSequentializer.hasPendingSave()) {
I
isidor 已提交
245
			this.logService.trace('load() - exit - without loading because model is dirty or being saved', this.resource);
E
Erich Gamma 已提交
246

B
Benjamin Pasero 已提交
247
			return Promise.resolve(this);
E
Erich Gamma 已提交
248 249
		}

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

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

259 260 261 262 263 264 265 266 267 268
	private async loadFromBackup(options?: ILoadOptions): Promise<TextFileEditorModel> {
		const backup = await this.backupFileService.loadBackupResource(this.resource);

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

		// If we have a backup, continue loading with it
		if (!!backup) {
B
Benjamin Pasero 已提交
269
			const content: ITextFileContent = {
270 271 272 273 274 275
				resource: this.resource,
				name: basename(this.resource),
				mtime: Date.now(),
				size: 0,
				etag: etag(Date.now(), 0),
				value: createTextBufferFactory(''), /* will be filled later from backup */
276
				encoding: this.textFileService.encoding.getPreferredWriteEncoding(this.resource, this.preferredEncoding).encoding,
277 278
				isReadonly: false
			};
279

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

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

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

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

B
Benjamin Pasero 已提交
299 300 301 302 303 304 305 306
		// 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 已提交
307
		// Resolve Content
308
		try {
309
			const content = await this.textFileService.legacyRead(this.resource, { acceptTextOnly: !allowBinary, etag, encoding: this.preferredEncoding });
310

311 312
			// Clear orphaned state when loading was successful
			this.setOrphaned(false);
313

314 315 316 317
			// Guard against the model having changed in the meantime
			if (currentVersionId === this.versionId) {
				return this.loadWithContent(content, options);
			}
E
Erich Gamma 已提交
318

319 320 321
			return this;
		} catch (error) {
			const result = error.fileOperationResult;
E
Erich Gamma 已提交
322

323 324
			// Apply orphaned state based on error code
			this.setOrphaned(result === FileOperationResult.FILE_NOT_FOUND);
325

326 327
			// NotModified status is expected and can be handled gracefully
			if (result === FileOperationResult.FILE_NOT_MODIFIED_SINCE) {
E
Erich Gamma 已提交
328

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

334 335
				return this;
			}
336

337 338 339 340 341 342 343 344 345 346
			// 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 this;
			}

			// Otherwise bubble up the error
			throw error;
		}
347
	}
E
Erich Gamma 已提交
348

B
Benjamin Pasero 已提交
349
	private async loadWithContent(content: ITextFileContent, options?: ILoadOptions, backup?: URI): Promise<TextFileEditorModel> {
350
		const model = await this.doLoadWithContent(content, backup);
351

352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
		// Telemetry: We log the fileGet telemetry event after the model has been loaded to ensure a good mimetype
		const settingsType = this.getTypeIfSettings();
		if (settingsType) {
			/* __GDPR__
				"settingsRead" : {
					"settingsType": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
				}
			*/
			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
		} else {
			/* __GDPR__
				"fileGet" : {
					"${include}": [
						"${FileTelemetryData}"
					]
				}
			*/
			this.telemetryService.publicLog('fileGet', this.getTelemetryData(options && options.reason ? options.reason : LoadReason.OTHER));
		}
371

372
		return model;
373 374
	}

B
Benjamin Pasero 已提交
375
	private doLoadWithContent(content: ITextFileContent, backup?: URI): Promise<TextFileEditorModel> {
I
isidor 已提交
376
		this.logService.trace('load() - resolved content', this.resource);
377 378

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

		// 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 已提交
400

401 402
		// Update Existing Model
		if (this.textEditorModel) {
B
Benjamin Pasero 已提交
403 404 405
			this.doUpdateTextModel(content.value);

			return Promise.resolve(this);
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

B
Benjamin Pasero 已提交
419
	private doUpdateTextModel(value: ITextBufferFactory): void {
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
		// Ensure we track the latest saved version ID given that the contents changed
		this.updateSavedVersionId();
435 436
	}

M
Matt Bierner 已提交
437
	private doCreateTextModel(resource: URI, value: ITextBufferFactory, backup: URI | undefined): Promise<TextFileEditorModel> {
I
isidor 已提交
438
		this.logService.trace('load() - created text editor model', this.resource);
439

440
		this.createTextEditorModelPromise = this.doLoadBackup(backup).then(backupContent => {
B
Benjamin Pasero 已提交
441
			this.createTextEditorModelPromise = null;
442

B
Benjamin Pasero 已提交
443 444
			// Create model
			const hasBackupContent = !!backupContent;
M
Matt Bierner 已提交
445
			this.createTextEditorModel(backupContent ? backupContent : value, resource);
B
Benjamin Pasero 已提交
446 447 448 449 450 451 452 453

			// 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);
454
				}
B
Benjamin Pasero 已提交
455
			}
456

B
Benjamin Pasero 已提交
457 458 459 460
			// Ensure we are not tracking a stale state
			else {
				this.setDirty(false);
			}
461

B
Benjamin Pasero 已提交
462 463
			// Model Listeners
			this.installModelListeners();
464

B
Benjamin Pasero 已提交
465 466 467
			return this;
		}, error => {
			this.createTextEditorModelPromise = null;
468

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

472 473 474
		return this.createTextEditorModelPromise;
	}

B
Benjamin Pasero 已提交
475 476
	private installModelListeners(): void {

477 478 479
		// 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 已提交
480 481

		// Content Change
M
Matt Bierner 已提交
482 483 484
		if (this.textEditorModel) {
			this._register(this.textEditorModel.onDidChangeContent(() => this.onModelContentChanged()));
		}
485 486
	}

487
	private async doLoadBackup(backup: URI | undefined): Promise<ITextBufferFactory | null> {
488
		if (!backup) {
489
			return null;
490
		}
491

492 493 494 495 496
		try {
			return withUndefinedAsNull(await this.backupFileService.resolveBackupContent(backup));
		} catch (error) {
			return null; // ignore errors
		}
E
Erich Gamma 已提交
497 498
	}

499
	protected getOrCreateMode(modeService: IModeService, preferredModeIds: string | undefined, firstLineText?: string): ILanguageSelection {
A
Alex Dima 已提交
500
		return modeService.createByFilepathOrFirstLine(this.resource.fsPath, firstLineText);
E
Erich Gamma 已提交
501 502
	}

503
	private onModelContentChanged(): void {
I
isidor 已提交
504
		this.logService.trace(`onModelContentChanged() - enter`, this.resource);
E
Erich Gamma 已提交
505 506 507

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

		// 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.
M
Matt Bierner 已提交
519
		if (!this.autoSaveAfterMilliesEnabled && this.textEditorModel && this.textEditorModel.getAlternativeVersionId() === this.bufferSavedVersionId) {
I
isidor 已提交
520
			this.logService.trace('onModelContentChanged() - model content changed back to last saved version', this.resource);
E
Erich Gamma 已提交
521 522

			// Clear flags
523
			const wasDirty = this.dirty;
E
Erich Gamma 已提交
524 525 526
			this.setDirty(false);

			// Emit event
527
			if (wasDirty) {
528
				this._onDidStateChange.fire(StateChange.REVERTED);
529
			}
E
Erich Gamma 已提交
530 531 532 533

			return;
		}

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

		// Mark as dirty
B
Benjamin Pasero 已提交
537
		this.makeDirty();
E
Erich Gamma 已提交
538 539

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

548 549
		// Handle content change events
		this.contentChangeEventScheduler.schedule();
E
Erich Gamma 已提交
550 551
	}

B
Benjamin Pasero 已提交
552
	private makeDirty(): void {
E
Erich Gamma 已提交
553 554

		// Track dirty state and version id
B
Benjamin Pasero 已提交
555
		const wasDirty = this.dirty;
E
Erich Gamma 已提交
556 557 558 559
		this.setDirty(true);

		// Emit as Event if we turned dirty
		if (!wasDirty) {
560
			this._onDidStateChange.fire(StateChange.DIRTY);
E
Erich Gamma 已提交
561 562 563
		}
	}

564
	private doAutoSave(versionId: number): void {
I
isidor 已提交
565
		this.logService.trace(`doAutoSave() - enter for versionId ${versionId}`, this.resource);
E
Erich Gamma 已提交
566 567

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

570 571
		// Create new save timer and store it for disposal as needed
		const handle = setTimeout(() => {
E
Erich Gamma 已提交
572 573 574

			// Only trigger save if the version id has not changed meanwhile
			if (versionId === this.versionId) {
575
				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 已提交
576
			}
577
		}, this.autoSaveAfterMillies);
E
Erich Gamma 已提交
578

579
		this.autoSaveDisposable = toDisposable(() => clearTimeout(handle));
E
Erich Gamma 已提交
580 581
	}

582 583 584
	private cancelPendingAutoSave(): void {
		if (this.autoSaveDisposable) {
			this.autoSaveDisposable.dispose();
R
Rob Lourens 已提交
585
			this.autoSaveDisposable = undefined;
E
Erich Gamma 已提交
586 587 588
		}
	}

J
Johannes Rieken 已提交
589
	save(options: ISaveOptions = Object.create(null)): Promise<void> {
E
Erich Gamma 已提交
590
		if (!this.isResolved()) {
R
Rob Lourens 已提交
591
			return Promise.resolve(undefined);
E
Erich Gamma 已提交
592 593
		}

I
isidor 已提交
594
		this.logService.trace('save() - enter', this.resource);
E
Erich Gamma 已提交
595 596

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

599
		return this.doSave(this.versionId, options);
E
Erich Gamma 已提交
600 601
	}

J
Johannes Rieken 已提交
602
	private doSave(versionId: number, options: ISaveOptions): Promise<void> {
603
		if (isUndefinedOrNull(options.reason)) {
604 605 606
			options.reason = SaveReason.EXPLICIT;
		}

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

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

M
Matt Bierner 已提交
617
			return this.saveSequentializer.pendingSave || Promise.resolve(undefined);
E
Erich Gamma 已提交
618 619
		}

620
		// Return early if not dirty (unless forced) or version changed meanwhile
B
Benjamin Pasero 已提交
621 622 623 624 625 626
		//
		// 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.
		//
627
		if ((!options.force && !this.dirty) || versionId !== this.versionId) {
I
isidor 已提交
628
			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 已提交
629

R
Rob Lourens 已提交
630
			return Promise.resolve(undefined);
E
Erich Gamma 已提交
631 632
		}

633
		// Return if currently saving by storing this save request as the next save that should happen.
634
		// Never ever must 2 saves execute at the same time because this can lead to dirty writes and race conditions.
B
Benjamin Pasero 已提交
635
		//
636
		// Scenario A: auto save was triggered and is currently busy saving to disk. this takes long enough that another auto save
637
		//             kicks in.
638 639
		// 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 已提交
640
		//
641
		if (this.saveSequentializer.hasPendingSave()) {
I
isidor 已提交
642
			this.logService.trace(`doSave(${versionId}) - exit - because busy saving`, this.resource);
E
Erich Gamma 已提交
643

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

		// 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
M
Matt Bierner 已提交
650 651
		if (!this.autoSaveAfterMilliesEnabled && this.textEditorModel) {
			this.textEditorModel.pushStackElement();
E
Erich Gamma 已提交
652 653
		}

B
Benjamin Pasero 已提交
654
		// A save participant can still change the model now and since we are so close to saving
E
Erich Gamma 已提交
655 656
		// 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
657
		// Save participants can also be skipped through API.
J
Johannes Rieken 已提交
658
		let saveParticipantPromise: Promise<number> = Promise.resolve(versionId);
659
		if (TextFileEditorModel.saveParticipant && !options.skipSaveParticipants) {
B
💄  
Benjamin Pasero 已提交
660
			const onCompleteOrError = () => {
J
Johannes Rieken 已提交
661
				this.blockModelContentChange = false;
B
💄  
Benjamin Pasero 已提交
662

663
				return this.versionId;
B
💄  
Benjamin Pasero 已提交
664 665
			};

B
Benjamin Pasero 已提交
666
			this.blockModelContentChange = true;
667
			saveParticipantPromise = TextFileEditorModel.saveParticipant.participate(this as IResolvedTextFileEditorModel, { reason: options.reason }).then(onCompleteOrError, onCompleteOrError);
E
Erich Gamma 已提交
668 669
		}

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

673 674 675 676 677
			// 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).
678
			// To fix this issue, we will not store the contents to disk when we got disposed.
679
			if (this.disposed) {
R
Rob Lourens 已提交
680
				return undefined;
681 682
			}

B
Benjamin Pasero 已提交
683 684
			// 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.
685 686 687 688 689 690
			// 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 已提交
691
				return this.doTouch(newVersionId);
692 693
			}

694
			// update versionId with its new value (if pre-save changes happened)
J
Johannes Rieken 已提交
695 696 697 698 699 700 701 702 703
			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
704
			// mark the save operation as currently pending with the versionId (it might have changed from a save participant triggering)
B
Benjamin Pasero 已提交
705
			this.logService.trace(`doSave(${versionId}) - before write()`, this.resource);
M
Matt Bierner 已提交
706 707 708 709
			const snapshot = this.createSnapshot();
			if (!snapshot) {
				throw new Error('Invalid snapshot');
			}
B
Benjamin Pasero 已提交
710
			return this.saveSequentializer.setPending(newVersionId, this.textFileService.write(this.lastResolvedDiskStat.resource, snapshot, {
711 712
				overwriteReadonly: options.overwriteReadonly,
				overwriteEncoding: options.overwriteEncoding,
713
				mtime: this.lastResolvedDiskStat.mtime,
J
Johannes Rieken 已提交
714
				encoding: this.getEncoding(),
715 716
				etag: this.lastResolvedDiskStat.etag,
				writeElevated: options.writeElevated
717
			}).then(stat => {
B
Benjamin Pasero 已提交
718
				this.logService.trace(`doSave(${versionId}) - after write()`, this.resource);
J
Johannes Rieken 已提交
719 720 721

				// Update dirty state unless model has changed meanwhile
				if (versionId === this.versionId) {
I
isidor 已提交
722
					this.logService.trace(`doSave(${versionId}) - setting dirty to false because versionId did not change`, this.resource);
J
Johannes Rieken 已提交
723 724
					this.setDirty(false);
				} else {
I
isidor 已提交
725
					this.logService.trace(`doSave(${versionId}) - not setting dirty to false because versionId did change meanwhile`, this.resource);
J
Johannes Rieken 已提交
726
				}
E
Erich Gamma 已提交
727

728
				// Updated resolved stat with updated stat
729
				this.updateLastResolvedDiskStat(stat);
E
Erich Gamma 已提交
730

731 732 733
				// Cancel any content change event promises as they are no longer valid
				this.contentChangeEventScheduler.cancel();

J
Johannes Rieken 已提交
734 735
				// Emit File Saved Event
				this._onDidStateChange.fire(StateChange.SAVED);
736 737 738 739 740 741 742 743 744 745 746

				// Telemetry
				const settingsType = this.getTypeIfSettings();
				if (settingsType) {
					/* __GDPR__
						"settingsWritten" : {
							"settingsType": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
						}
					*/
					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
				} else {
747
					/* __GDPR__
748 749 750 751 752 753
							"filePUT" : {
								"${include}": [
									"${FileTelemetryData}"
								]
							}
						*/
754
					this.telemetryService.publicLog('filePUT', this.getTelemetryData(options.reason));
755
				}
756
			}, error => {
757 758
				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 已提交
759 760
				}

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

763
				// Flag as error state in the model
J
Johannes Rieken 已提交
764
				this.inErrorMode = true;
E
Erich Gamma 已提交
765

766
				// Look out for a save conflict
767
				if ((<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_MODIFIED_SINCE) {
768 769 770
					this.inConflictMode = true;
				}

J
Johannes Rieken 已提交
771 772
				// Show to user
				this.onSaveError(error);
E
Erich Gamma 已提交
773

J
Johannes Rieken 已提交
774 775
				// Emit as event
				this._onDidStateChange.fire(StateChange.SAVE_ERROR);
776 777
			}));
		}));
E
Erich Gamma 已提交
778 779
	}

780
	private getTypeIfSettings(): string {
B
Benjamin Pasero 已提交
781
		if (extname(this.resource) !== '.json') {
782
			return '';
783
		}
784 785

		// Check for global settings file
S
Sandeep Somavarapu 已提交
786
		if (isEqual(this.resource, URI.file(this.environmentService.appSettingsPath), !isLinux)) {
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
796
		if (isEqual(this.resource, URI.file(join(this.environmentService.appSettingsHome, 'locale.json')), !isLinux)) {
797 798 799 800
			return 'locale';
		}

		// Check for snippets
801
		if (isEqualOrParent(this.resource, URI.file(join(this.environmentService.appSettingsHome, 'snippets')))) {
802
			return 'snippets';
803 804 805
		}

		// Check for workspace settings file
806
		const folders = this.contextService.getWorkspace().folders;
807 808
		for (const folder of folders) {
			if (isEqualOrParent(this.resource, folder.toResource('.vscode'))) {
B
Benjamin Pasero 已提交
809
				const filename = basename(this.resource);
810 811 812 813 814 815 816
				if (TextFileEditorModel.WHITELIST_WORKSPACE_JSON.indexOf(filename) > -1) {
					return `.vscode/${filename}`;
				}
			}
		}

		return '';
817 818
	}

819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
	private getTelemetryData(reason: number | undefined): object {
		const ext = extname(this.resource);
		const fileName = basename(this.resource);
		const telemetryData = {
			mimeType: guessMimeTypes(this.resource.fsPath).join(', '),
			ext,
			path: hash(this.resource.fsPath),
			reason
		};

		if (ext === '.json' && TextFileEditorModel.WHITELIST_JSON.indexOf(fileName) > -1) {
			telemetryData['whitelistedjson'] = fileName;
		}

		/* __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" }
840
			}
841 842
		*/
		return telemetryData;
843 844
	}

J
Johannes Rieken 已提交
845
	private doTouch(versionId: number): Promise<void> {
M
Matt Bierner 已提交
846 847 848 849
		const snapshot = this.createSnapshot();
		if (!snapshot) {
			throw new Error('invalid snapshot');
		}
850

B
Benjamin Pasero 已提交
851
		return this.saveSequentializer.setPending(versionId, this.textFileService.write(this.lastResolvedDiskStat.resource, snapshot, {
B
Benjamin Pasero 已提交
852 853 854 855
			mtime: this.lastResolvedDiskStat.mtime,
			encoding: this.getEncoding(),
			etag: this.lastResolvedDiskStat.etag
		}).then(stat => {
856 857 858

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

E
Erich Gamma 已提交
862
	private setDirty(dirty: boolean): () => void {
B
Benjamin Pasero 已提交
863
		const wasDirty = this.dirty;
864
		const wasInConflictMode = this.inConflictMode;
B
Benjamin Pasero 已提交
865 866
		const wasInErrorMode = this.inErrorMode;
		const oldBufferSavedVersionId = this.bufferSavedVersionId;
E
Erich Gamma 已提交
867 868 869

		if (!dirty) {
			this.dirty = false;
870
			this.inConflictMode = false;
E
Erich Gamma 已提交
871
			this.inErrorMode = false;
872
			this.updateSavedVersionId();
E
Erich Gamma 已提交
873 874 875 876 877 878 879
		} else {
			this.dirty = true;
		}

		// Return function to revert this call
		return () => {
			this.dirty = wasDirty;
880
			this.inConflictMode = wasInConflictMode;
E
Erich Gamma 已提交
881 882 883 884 885
			this.inErrorMode = wasInErrorMode;
			this.bufferSavedVersionId = oldBufferSavedVersionId;
		};
	}

886 887 888 889 890 891 892 893 894 895 896
	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();
		}
	}

897
	private updateLastResolvedDiskStat(newVersionOnDiskStat: IFileStatWithMetadata): void {
E
Erich Gamma 已提交
898 899

		// First resolve - just take
900 901
		if (!this.lastResolvedDiskStat) {
			this.lastResolvedDiskStat = newVersionOnDiskStat;
E
Erich Gamma 已提交
902 903 904
		}

		// Subsequent resolve - make sure that we only assign it if the mtime is equal or has advanced.
B
Benjamin Pasero 已提交
905 906
		// 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.
907 908
		else if (this.lastResolvedDiskStat.mtime <= newVersionOnDiskStat.mtime) {
			this.lastResolvedDiskStat = newVersionOnDiskStat;
E
Erich Gamma 已提交
909 910 911
		}
	}

912
	private onSaveError(error: Error): void {
E
Erich Gamma 已提交
913 914 915 916 917 918 919 920 921 922

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

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

B
Benjamin Pasero 已提交
923
	isDirty(): boolean {
E
Erich Gamma 已提交
924 925 926
		return this.dirty;
	}

B
Benjamin Pasero 已提交
927
	getLastSaveAttemptTime(): number {
B
Benjamin Pasero 已提交
928
		return this.lastSaveAttemptTime;
E
Erich Gamma 已提交
929 930
	}

931
	getETag(): string | null {
M
Matt Bierner 已提交
932
		return this.lastResolvedDiskStat ? this.lastResolvedDiskStat.etag || null : null;
E
Erich Gamma 已提交
933 934
	}

B
Benjamin Pasero 已提交
935
	hasState(state: ModelState): boolean {
936 937 938 939 940 941 942 943 944 945 946 947 948
		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 已提交
949 950 951
		}
	}

B
Benjamin Pasero 已提交
952
	getEncoding(): string {
E
Erich Gamma 已提交
953 954 955
		return this.preferredEncoding || this.contentEncoding;
	}

B
Benjamin Pasero 已提交
956
	setEncoding(encoding: string, mode: EncodingMode): void {
E
Erich Gamma 已提交
957 958 959 960 961 962 963 964 965 966 967 968 969 970
		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();
			}

971
			if (!this.inConflictMode) {
972
				this.save({ overwriteEncoding: true });
E
Erich Gamma 已提交
973 974 975 976 977 978
			}
		}

		// Decode: Load with encoding
		else {
			if (this.isDirty()) {
979
				this.notificationService.info(nls.localize('saveFileFirst', "The file is dirty. Please save it first before reopening it with another encoding."));
E
Erich Gamma 已提交
980 981 982 983 984 985 986

				return;
			}

			this.updatePreferredEncoding(encoding);

			// Load
987 988
			this.load({
				forceReadFromDisk: true	// because encoding has changed
989
			});
E
Erich Gamma 已提交
990 991 992
		}
	}

B
Benjamin Pasero 已提交
993
	updatePreferredEncoding(encoding: string): void {
E
Erich Gamma 已提交
994 995 996 997 998 999 1000
		if (!this.isNewEncoding(encoding)) {
			return;
		}

		this.preferredEncoding = encoding;

		// Emit
1001
		this._onDidStateChange.fire(StateChange.ENCODING);
E
Erich Gamma 已提交
1002 1003 1004 1005 1006 1007 1008 1009
	}

	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) {
1010
			return false; // also return if we don't have a preferred encoding but the content encoding is already the same
E
Erich Gamma 已提交
1011 1012 1013 1014 1015
		}

		return true;
	}

B
Benjamin Pasero 已提交
1016
	isResolved(): boolean {
1017
		return !isUndefinedOrNull(this.lastResolvedDiskStat);
E
Erich Gamma 已提交
1018 1019
	}

B
Benjamin Pasero 已提交
1020
	isReadonly(): boolean {
1021
		return !!(this.lastResolvedDiskStat && this.lastResolvedDiskStat.isReadonly);
1022 1023
	}

B
Benjamin Pasero 已提交
1024
	isDisposed(): boolean {
E
Erich Gamma 已提交
1025 1026 1027
		return this.disposed;
	}

B
Benjamin Pasero 已提交
1028
	getResource(): URI {
E
Erich Gamma 已提交
1029 1030 1031
		return this.resource;
	}

1032
	getStat(): IFileStatWithMetadata {
B
Benjamin Pasero 已提交
1033 1034 1035
		return this.lastResolvedDiskStat;
	}

B
Benjamin Pasero 已提交
1036
	dispose(): void {
E
Erich Gamma 已提交
1037
		this.disposed = true;
1038 1039
		this.inConflictMode = false;
		this.inOrphanMode = false;
E
Erich Gamma 已提交
1040 1041 1042 1043
		this.inErrorMode = false;

		this.createTextEditorModelPromise = null;

1044
		this.cancelPendingAutoSave();
D
Daniel Imms 已提交
1045

E
Erich Gamma 已提交
1046 1047
		super.dispose();
	}
1048 1049
}

1050 1051
interface IPendingSave {
	versionId: number;
J
Johannes Rieken 已提交
1052
	promise: Promise<void>;
1053 1054
}

1055
interface ISaveOperation {
J
Johannes Rieken 已提交
1056
	promise: Promise<void>;
B
Benjamin Pasero 已提交
1057 1058
	promiseResolve: () => void;
	promiseReject: (error: Error) => void;
J
Johannes Rieken 已提交
1059
	run: () => Promise<void>;
1060 1061 1062
}

export class SaveSequentializer {
1063 1064
	private _pendingSave?: IPendingSave;
	private _nextSave?: ISaveOperation;
1065

B
Benjamin Pasero 已提交
1066
	hasPendingSave(versionId?: number): boolean {
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
		if (!this._pendingSave) {
			return false;
		}

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

		return !!this._pendingSave;
	}

1078
	get pendingSave(): Promise<void> | undefined {
R
Rob Lourens 已提交
1079
		return this._pendingSave ? this._pendingSave.promise : undefined;
1080 1081
	}

J
Johannes Rieken 已提交
1082
	setPending(versionId: number, promise: Promise<void>): Promise<void> {
1083 1084
		this._pendingSave = { versionId, promise };

1085
		promise.then(() => this.donePending(versionId), () => this.donePending(versionId));
1086 1087 1088 1089 1090 1091

		return promise;
	}

	private donePending(versionId: number): void {
		if (this._pendingSave && versionId === this._pendingSave.versionId) {
1092 1093

			// only set pending to done if the promise finished that is associated with that versionId
R
Rob Lourens 已提交
1094
			this._pendingSave = undefined;
1095 1096 1097

			// schedule the next save now that we are free if we have any
			this.triggerNextSave();
1098 1099 1100
		}
	}

1101 1102 1103
	private triggerNextSave(): void {
		if (this._nextSave) {
			const saveOperation = this._nextSave;
R
Rob Lourens 已提交
1104
			this._nextSave = undefined;
1105 1106

			// Run next save and complete on the associated promise
B
Benjamin Pasero 已提交
1107
			saveOperation.run().then(saveOperation.promiseResolve, saveOperation.promiseReject);
1108 1109 1110
		}
	}

J
Johannes Rieken 已提交
1111
	setNext(run: () => Promise<void>): Promise<void> {
1112 1113 1114 1115 1116

		// 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) {
M
Matt Bierner 已提交
1117 1118
			let promiseResolve: () => void;
			let promiseReject: (error: Error) => void;
B
Benjamin Pasero 已提交
1119 1120 1121
			const promise = new Promise<void>((resolve, reject) => {
				promiseResolve = resolve;
				promiseReject = reject;
1122 1123 1124 1125 1126
			});

			this._nextSave = {
				run,
				promise,
M
Matt Bierner 已提交
1127 1128
				promiseResolve: promiseResolve!,
				promiseReject: promiseReject!
1129 1130 1131 1132 1133 1134 1135 1136
			};
		}

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

M
Matt Bierner 已提交
1137
		return this._nextSave.promise;
1138 1139 1140
	}
}

1141 1142
class DefaultSaveErrorHandler implements ISaveErrorHandler {

1143
	constructor(@INotificationService private readonly notificationService: INotificationService) { }
1144

1145
	onSaveError(error: Error, model: TextFileEditorModel): void {
B
Benjamin Pasero 已提交
1146
		this.notificationService.error(nls.localize('genericSaveError', "Failed to save '{0}': {1}", basename(model.getResource()), toErrorMessage(error, false)));
1147 1148
	}
}