textFileEditorModel.ts 39.8 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 * as nls from 'vs/nls';
M
Matt Bierner 已提交
7
import { Event, Emitter } from 'vs/base/common/event';
J
Johannes Rieken 已提交
8 9
import { guessMimeTypes } from 'vs/base/common/mime';
import { toErrorMessage } from 'vs/base/common/errorMessage';
10
import { URI } from 'vs/base/common/uri';
11
import { isUndefinedOrNull } from 'vs/base/common/types';
12
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
13
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
14
import { ITextFileService, IAutoSaveConfiguration, ModelState, ITextFileEditorModel, ISaveOptions, ISaveErrorHandler, ISaveParticipant, StateChange, SaveReason, ITextFileStreamContent, ILoadOptions, LoadReason, IResolvedTextFileEditorModel } from 'vs/workbench/services/textfile/common/textfiles';
B
Benjamin Pasero 已提交
15
import { EncodingMode } from 'vs/workbench/common/editor';
J
Johannes Rieken 已提交
16
import { BaseTextEditorModel } from 'vs/workbench/common/editor/textEditorModel';
17
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
B
Benjamin Pasero 已提交
18
import { IFileService, FileOperationError, FileOperationResult, CONTENT_CHANGE_EVENT_BUFFER_DELAY, FileChangesEvent, FileChangeType, IFileStatWithMetadata, ETAG_DISABLED } from 'vs/platform/files/common/files';
J
Johannes Rieken 已提交
19
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
20
import { IModeService } from 'vs/editor/common/services/modeService';
21
import { IModelService } from 'vs/editor/common/services/modelService';
22
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
23
import { RunOnceScheduler, timeout } from 'vs/base/common/async';
24
import { ITextBufferFactory } from 'vs/editor/common/model';
25
import { hash } from 'vs/base/common/hash';
26
import { INotificationService } from 'vs/platform/notification/common/notification';
B
Benjamin Pasero 已提交
27
import { isLinux } from 'vs/base/common/platform';
28
import { toDisposable, MutableDisposable } from 'vs/base/common/lifecycle';
I
isidor 已提交
29
import { ILogService } from 'vs/platform/log/common/log';
S
Sandeep Somavarapu 已提交
30
import { isEqual, isEqualOrParent, extname, basename, joinPath } from 'vs/base/common/resources';
B
Benjamin Pasero 已提交
31
import { onUnexpectedError } from 'vs/base/common/errors';
32
import { Schemas } from 'vs/base/common/network';
B
Benjamin Pasero 已提交
33

34
export interface IBackupMetaData {
B
Benjamin Pasero 已提交
35 36 37 38
	mtime: number;
	size: number;
	etag: string;
	orphaned: boolean;
39 40
}

E
Erich Gamma 已提交
41 42 43
/**
 * 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.
 */
44
export class TextFileEditorModel extends BaseTextEditorModel implements ITextFileEditorModel {
E
Erich Gamma 已提交
45

B
Benjamin Pasero 已提交
46 47
	static DEFAULT_CONTENT_CHANGE_BUFFER_DELAY = CONTENT_CHANGE_EVENT_BUFFER_DELAY;
	static DEFAULT_ORPHANED_CHANGE_BUFFER_DELAY = 100;
K
kieferrm 已提交
48
	static WHITELIST_JSON = ['package.json', 'package-lock.json', 'tsconfig.json', 'jsconfig.json', 'bower.json', '.eslintrc.json', 'tslint.json', 'composer.json'];
49
	static WHITELIST_WORKSPACE_JSON = ['settings.json', 'extensions.json', 'tasks.json', 'launch.json'];
50

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

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

B
Benjamin Pasero 已提交
57 58 59 60 61 62
	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 已提交
63
	private resource: URI;
B
Benjamin Pasero 已提交
64

65 66 67 68
	private contentEncoding: string; 	// encoding as reported from disk
	private preferredEncoding: string;	// encoding as chosen by the user

	private preferredMode: string;		// mode as chosen by the user
B
Benjamin Pasero 已提交
69

E
Erich Gamma 已提交
70 71 72
	private versionId: number;
	private bufferSavedVersionId: number;
	private blockModelContentChange: boolean;
B
Benjamin Pasero 已提交
73

74
	private lastResolvedFileStat: IFileStatWithMetadata;
B
Benjamin Pasero 已提交
75

76
	private autoSaveAfterMillies?: number;
77
	private autoSaveAfterMilliesEnabled: boolean;
78
	private readonly autoSaveDisposable = this._register(new MutableDisposable());
B
Benjamin Pasero 已提交
79

80
	private saveSequentializer: SaveSequentializer;
B
Benjamin Pasero 已提交
81
	private lastSaveAttemptTime: number;
B
Benjamin Pasero 已提交
82 83 84 85 86

	private contentChangeEventScheduler: RunOnceScheduler;
	private orphanedChangeEventScheduler: RunOnceScheduler;

	private dirty: boolean;
87 88 89 90
	private inConflictMode: boolean;
	private inOrphanMode: boolean;
	private inErrorMode: boolean;

B
Benjamin Pasero 已提交
91 92
	private disposed: boolean;

E
Erich Gamma 已提交
93 94 95
	constructor(
		resource: URI,
		preferredEncoding: string,
96
		preferredMode: string,
97
		@INotificationService private readonly notificationService: INotificationService,
E
Erich Gamma 已提交
98 99
		@IModeService modeService: IModeService,
		@IModelService modelService: IModelService,
100 101 102 103 104 105 106
		@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,
S
Sandeep Somavarapu 已提交
107
		@ILogService private readonly logService: ILogService
E
Erich Gamma 已提交
108 109
	) {
		super(modelService, modeService);
B
Benjamin Pasero 已提交
110

E
Erich Gamma 已提交
111 112
		this.resource = resource;
		this.preferredEncoding = preferredEncoding;
113
		this.preferredMode = preferredMode;
114
		this.inOrphanMode = false;
E
Erich Gamma 已提交
115 116
		this.dirty = false;
		this.versionId = 0;
B
Benjamin Pasero 已提交
117
		this.lastSaveAttemptTime = 0;
118
		this.saveSequentializer = new SaveSequentializer();
119

B
Benjamin Pasero 已提交
120 121
		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));
122

123
		this.updateAutoSaveConfiguration(textFileService.getAutoSaveConfiguration());
B
Benjamin Pasero 已提交
124

125
		this.registerListeners();
E
Erich Gamma 已提交
126 127
	}

128
	private registerListeners(): void {
B
Benjamin Pasero 已提交
129 130 131 132
		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 已提交
133
	}
134

B
Benjamin Pasero 已提交
135 136
	private onStateChange(e: StateChange): void {
		if (e === StateChange.REVERTED) {
137

B
Benjamin Pasero 已提交
138 139 140 141 142 143
			// 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);
		}
144 145
	}

146
	private async onFileChanges(e: FileChangesEvent): Promise<void> {
147
		let fileEventImpactsModel = false;
148
		let newInOrphanModeGuess: boolean | undefined;
149 150 151 152 153 154 155 156 157

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

159 160 161 162 163 164 165 166
		// Otherwise we check if the model file was deleted
		else {
			const modelFileDeleted = e.contains(this.resource, FileChangeType.DELETED);
			if (modelFileDeleted) {
				newInOrphanModeGuess = true;
				fileEventImpactsModel = true;
			}
		}
167

168
		if (fileEventImpactsModel && this.inOrphanMode !== newInOrphanModeGuess) {
169
			let newInOrphanModeValidated: boolean = false;
170 171 172 173 174
			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.
175
				await timeout(100);
176

177 178 179 180 181 182
				if (this.disposed) {
					newInOrphanModeValidated = true;
				} else {
					const exists = await this.fileService.exists(this.resource);
					newInOrphanModeValidated = !exists;
				}
183
			}
184

185 186 187
			if (this.inOrphanMode !== newInOrphanModeValidated && !this.disposed) {
				this.setOrphaned(newInOrphanModeValidated);
			}
188 189 190 191 192 193 194 195 196 197
		}
	}

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

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

B
Benjamin Pasero 已提交
201
		this.autoSaveAfterMilliesEnabled = autoSaveAfterMilliesEnabled;
R
Rob Lourens 已提交
202
		this.autoSaveAfterMillies = autoSaveAfterMilliesEnabled ? config.autoSaveDelay : undefined;
203 204
	}

B
Benjamin Pasero 已提交
205
	private onFilesAssociationChange(): void {
206
		if (!this.isResolved()) {
B
Benjamin Pasero 已提交
207 208 209
			return;
		}

A
Alex Dima 已提交
210
		const firstLineText = this.getFirstLineText(this.textEditorModel);
211
		const languageSelection = this.getOrCreateMode(this.resource, this.modeService, this.preferredMode, firstLineText);
B
Benjamin Pasero 已提交
212

A
Alex Dima 已提交
213
		this.modelService.setMode(this.textEditorModel, languageSelection);
B
Benjamin Pasero 已提交
214 215
	}

216 217 218 219 220 221
	setMode(mode: string): void {
		super.setMode(mode);

		this.preferredMode = mode;
	}

222
	async backup(target = this.resource): Promise<void> {
223 224 225 226
		if (this.isResolved()) {

			// Only fill in model metadata if resource matches
			let meta: IBackupMetaData | undefined = undefined;
227
			if (isEqual(target, this.resource) && this.lastResolvedFileStat) {
228
				meta = {
229 230 231
					mtime: this.lastResolvedFileStat.mtime,
					size: this.lastResolvedFileStat.size,
					etag: this.lastResolvedFileStat.etag,
232 233 234
					orphaned: this.inOrphanMode
				};
			}
235

236
			return this.backupFileService.backupResource<IBackupMetaData>(target, this.createSnapshot(), this.versionId, meta);
237 238 239
		}
	}

240 241 242 243
	hasBackup(): boolean {
		return this.backupFileService.hasBackupSync(this.resource, this.versionId);
	}

244
	async revert(soft?: boolean): Promise<void> {
E
Erich Gamma 已提交
245
		if (!this.isResolved()) {
246
			return;
E
Erich Gamma 已提交
247 248
		}

249
		// Cancel any running auto-save
250
		this.autoSaveDisposable.clear();
E
Erich Gamma 已提交
251 252

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

255 256 257 258 259
		// Force read from disk unless reverting soft
		if (!soft) {
			try {
				await this.load({ forceReadFromDisk: true });
			} catch (error) {
E
Erich Gamma 已提交
260

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

264 265
				throw error;
			}
266
		}
267 268 269

		// Emit file change event
		this._onDidStateChange.fire(StateChange.REVERTED);
E
Erich Gamma 已提交
270 271
	}

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

B
Benjamin Pasero 已提交
275 276 277
		// 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.
278
		if (this.dirty || this.saveSequentializer.hasPendingSave()) {
I
isidor 已提交
279
			this.logService.trace('load() - exit - without loading because model is dirty or being saved', this.resource);
E
Erich Gamma 已提交
280

281
			return this;
E
Erich Gamma 已提交
282 283
		}

284
		// Only for new models we support to load from backup
285
		if (!this.isResolved()) {
286 287
			const backup = await this.backupFileService.loadBackupResource(this.resource);

288
			if (this.isResolved()) {
289 290 291 292 293
				return this; // Make sure meanwhile someone else did not suceed in loading
			}

			if (backup) {
				try {
B
Benjamin Pasero 已提交
294
					return await this.loadFromBackup(backup, options);
295 296 297 298
				} catch (error) {
					// ignore error and continue to load as file below
				}
			}
299 300 301
		}

		// Otherwise load from file resource
302
		return this.loadFromFile(options);
303 304
	}

305
	private async loadFromBackup(backup: URI, options?: ILoadOptions): Promise<TextFileEditorModel> {
306

307
		// Resolve actual backup contents
308
		const resolvedBackup = await this.backupFileService.resolveBackupContent<IBackupMetaData>(backup);
309

310
		if (this.isResolved()) {
311
			return this; // Make sure meanwhile someone else did not suceed in loading
312
		}
313

314 315
		// Load with backup
		this.loadFromContent({
316 317
			resource: this.resource,
			name: basename(this.resource),
B
Benjamin Pasero 已提交
318 319 320
			mtime: resolvedBackup.meta ? resolvedBackup.meta.mtime : Date.now(),
			size: resolvedBackup.meta ? resolvedBackup.meta.size : 0,
			etag: resolvedBackup.meta ? resolvedBackup.meta.etag : ETAG_DISABLED, // etag disabled if unknown!
321
			value: resolvedBackup.value,
322 323 324
			encoding: this.textFileService.encoding.getPreferredWriteEncoding(this.resource, this.preferredEncoding).encoding,
			isReadonly: false
		}, options, true /* from backup */);
325 326

		// Restore orphaned flag based on state
B
Benjamin Pasero 已提交
327
		if (resolvedBackup.meta && resolvedBackup.meta.orphaned) {
328 329 330 331
			this.setOrphaned(true);
		}

		return this;
332 333
	}

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

E
Erich Gamma 已提交
338
		// Decide on etag
339
		let etag: string | undefined;
340
		if (forceReadFromDisk) {
341
			etag = ETAG_DISABLED; // disable ETag if we enforce to read from disk
342 343
		} else if (this.lastResolvedFileStat) {
			etag = this.lastResolvedFileStat.etag; // otherwise respect etag to support caching
E
Erich Gamma 已提交
344 345
		}

B
Benjamin Pasero 已提交
346 347 348 349 350 351 352 353
		// 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 已提交
354
		// Resolve Content
355
		try {
356
			const content = await this.textFileService.readStream(this.resource, { acceptTextOnly: !allowBinary, etag, encoding: this.preferredEncoding });
357

358 359
			// Clear orphaned state when loading was successful
			this.setOrphaned(false);
360

361 362
			if (currentVersionId !== this.versionId) {
				return this; // Make sure meanwhile someone else did not suceed loading
363
			}
E
Erich Gamma 已提交
364

365
			return this.loadFromContent(content, options);
366 367
		} catch (error) {
			const result = error.fileOperationResult;
E
Erich Gamma 已提交
368

369 370
			// Apply orphaned state based on error code
			this.setOrphaned(result === FileOperationResult.FILE_NOT_FOUND);
371

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

375 376 377
				// 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 已提交
378
				}
379

380 381
				return this;
			}
382

383 384 385 386 387 388 389 390 391 392
			// 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;
		}
393
	}
E
Erich Gamma 已提交
394

395
	private loadFromContent(content: ITextFileStreamContent, options?: ILoadOptions, fromBackup?: boolean): TextFileEditorModel {
I
isidor 已提交
396
		this.logService.trace('load() - resolved content', this.resource);
397 398

		// Update our resolved disk stat model
399
		this.updateLastResolvedFileStat({
400 401 402
			resource: this.resource,
			name: content.name,
			mtime: content.mtime,
403
			size: content.size,
404 405
			etag: content.etag,
			isDirectory: false,
406
			isSymbolicLink: false,
I
isidor 已提交
407
			isReadonly: content.isReadonly
408
		});
409 410 411 412 413 414 415 416 417 418 419

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

421
		// Update Existing Model
422
		if (this.isResolved()) {
B
Benjamin Pasero 已提交
423
			this.doUpdateTextModel(content.value);
424
		}
B
Benjamin Pasero 已提交
425

426 427 428
		// Create New Model
		else {
			this.doCreateTextModel(content.resource, content.value, !!fromBackup);
429
		}
E
Erich Gamma 已提交
430

431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
		// 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));
		}

		return this;
	}
E
Erich Gamma 已提交
453

454 455 456 457
	private doCreateTextModel(resource: URI, value: ITextBufferFactory, fromBackup: boolean): void {
		this.logService.trace('load() - created text editor model', this.resource);

		// Create model
458
		this.createTextEditorModel(value, resource, this.preferredMode);
459 460 461 462 463 464 465 466 467

		// 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 (fromBackup) {
			this.makeDirty();
			if (this.autoSaveAfterMilliesEnabled) {
				this.doAutoSave(this.versionId);
			}
468
		}
E
Erich Gamma 已提交
469

470 471 472 473 474 475 476
		// Ensure we are not tracking a stale state
		else {
			this.setDirty(false);
		}

		// Model Listeners
		this.installModelListeners();
477
	}
E
Erich Gamma 已提交
478

B
Benjamin Pasero 已提交
479
	private doUpdateTextModel(value: ITextBufferFactory): void {
I
isidor 已提交
480
		this.logService.trace('load() - updated text editor model', this.resource);
481

482 483
		// Ensure we are not tracking a stale state
		this.setDirty(false);
484

485
		// Update model value in a block that ignores model content change events
486 487
		this.blockModelContentChange = true;
		try {
488
			this.updateTextEditorModel(value, this.preferredMode);
489 490 491 492
		} finally {
			this.blockModelContentChange = false;
		}

493 494
		// Ensure we track the latest saved version ID given that the contents changed
		this.updateSavedVersionId();
495 496
	}

B
Benjamin Pasero 已提交
497 498
	private installModelListeners(): void {

499 500 501
		// 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 已提交
502 503

		// Content Change
504
		if (this.isResolved()) {
M
Matt Bierner 已提交
505 506
			this._register(this.textEditorModel.onDidChangeContent(() => this.onModelContentChanged()));
		}
507 508
	}

509
	private onModelContentChanged(): void {
I
isidor 已提交
510
		this.logService.trace(`onModelContentChanged() - enter`, this.resource);
E
Erich Gamma 已提交
511 512 513

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

		// 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.
525
		if (!this.autoSaveAfterMilliesEnabled && this.isResolved() && this.textEditorModel.getAlternativeVersionId() === this.bufferSavedVersionId) {
I
isidor 已提交
526
			this.logService.trace('onModelContentChanged() - model content changed back to last saved version', this.resource);
E
Erich Gamma 已提交
527 528

			// Clear flags
529
			const wasDirty = this.dirty;
E
Erich Gamma 已提交
530 531 532
			this.setDirty(false);

			// Emit event
533
			if (wasDirty) {
534
				this._onDidStateChange.fire(StateChange.REVERTED);
535
			}
E
Erich Gamma 已提交
536 537 538 539

			return;
		}

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

		// Mark as dirty
B
Benjamin Pasero 已提交
543
		this.makeDirty();
E
Erich Gamma 已提交
544 545

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

554 555
		// Handle content change events
		this.contentChangeEventScheduler.schedule();
E
Erich Gamma 已提交
556 557
	}

B
Benjamin Pasero 已提交
558
	private makeDirty(): void {
E
Erich Gamma 已提交
559 560

		// Track dirty state and version id
B
Benjamin Pasero 已提交
561
		const wasDirty = this.dirty;
E
Erich Gamma 已提交
562 563 564 565
		this.setDirty(true);

		// Emit as Event if we turned dirty
		if (!wasDirty) {
566
			this._onDidStateChange.fire(StateChange.DIRTY);
E
Erich Gamma 已提交
567 568 569
		}
	}

570
	private doAutoSave(versionId: number): void {
I
isidor 已提交
571
		this.logService.trace(`doAutoSave() - enter for versionId ${versionId}`, this.resource);
E
Erich Gamma 已提交
572 573

		// Cancel any currently running auto saves to make this the one that succeeds
574
		this.autoSaveDisposable.clear();
E
Erich Gamma 已提交
575

576 577
		// Create new save timer and store it for disposal as needed
		const handle = setTimeout(() => {
E
Erich Gamma 已提交
578 579 580

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

585
		this.autoSaveDisposable.value = toDisposable(() => clearTimeout(handle));
E
Erich Gamma 已提交
586 587
	}

588
	async save(options: ISaveOptions = Object.create(null)): Promise<void> {
E
Erich Gamma 已提交
589
		if (!this.isResolved()) {
590
			return;
E
Erich Gamma 已提交
591 592
		}

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

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

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

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

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

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

616
			return this.saveSequentializer.pendingSave || Promise.resolve();
E
Erich Gamma 已提交
617 618
		}

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

629
			return Promise.resolve();
E
Erich Gamma 已提交
630 631
		}

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

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

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

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

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

B
Benjamin Pasero 已提交
665
			this.blockModelContentChange = true;
666
			saveParticipantPromise = TextFileEditorModel.saveParticipant.participate(this as IResolvedTextFileEditorModel, { reason: options.reason }).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
			if (this.disposed) {
679 680 681 682 683 684
				return;
			}

			// We require a resolved model from this point on, since we are about to write data to disk.
			if (!this.isResolved()) {
				return;
685 686
			}

B
Benjamin Pasero 已提交
687 688
			// 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.
689 690 691 692 693 694
			// 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 已提交
695
				return this.doTouch(newVersionId);
696 697
			}

698
			// update versionId with its new value (if pre-save changes happened)
J
Johannes Rieken 已提交
699 700 701 702 703 704 705 706 707
			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
708
			// mark the save operation as currently pending with the versionId (it might have changed from a save participant triggering)
B
Benjamin Pasero 已提交
709
			this.logService.trace(`doSave(${versionId}) - before write()`, this.resource);
710
			return this.saveSequentializer.setPending(newVersionId, this.textFileService.write(this.lastResolvedFileStat.resource, this.createSnapshot(), {
711 712
				overwriteReadonly: options.overwriteReadonly,
				overwriteEncoding: options.overwriteEncoding,
713
				mtime: this.lastResolvedFileStat.mtime,
J
Johannes Rieken 已提交
714
				encoding: this.getEncoding(),
715
				etag: this.lastResolvedFileStat.etag,
716
				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.updateLastResolvedFileStat(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 => {
I
isidor 已提交
757
				this.logService.error(`doSave(${versionId}) - exit - resulted in a save error: ${error.toString()}`, this.resource);
E
Erich Gamma 已提交
758

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

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

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

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

776
	private getTypeIfSettings(): string {
B
Benjamin Pasero 已提交
777
		if (extname(this.resource) !== '.json') {
778
			return '';
779
		}
780 781

		// Check for global settings file
S
Sandeep Somavarapu 已提交
782
		if (isEqual(this.resource, this.environmentService.settingsResource, !isLinux)) {
783 784 785 786
			return 'global-settings';
		}

		// Check for keybindings file
S
Sandeep Somavarapu 已提交
787
		if (isEqual(this.resource, this.environmentService.keybindingsResource, !isLinux)) {
788 789 790 791
			return 'keybindings';
		}

		// Check for locale file
792
		if (isEqual(this.resource, joinPath(this.environmentService.userRoamingDataHome, 'locale.json'), !isLinux)) {
793 794 795 796
			return 'locale';
		}

		// Check for snippets
797
		if (isEqualOrParent(this.resource, joinPath(this.environmentService.userRoamingDataHome, 'snippets'))) {
798
			return 'snippets';
799 800 801
		}

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

		return '';
813 814
	}

815 816 817
	private getTelemetryData(reason: number | undefined): object {
		const ext = extname(this.resource);
		const fileName = basename(this.resource);
818
		const path = this.resource.scheme === Schemas.file ? this.resource.fsPath : this.resource.path;
819
		const telemetryData = {
B
Benjamin Pasero 已提交
820
			mimeType: guessMimeTypes(this.resource).join(', '),
821
			ext,
822
			path: hash(path),
M
Matt Bierner 已提交
823 824
			reason,
			whitelistedjson: undefined as string | undefined
825 826 827 828 829 830 831 832 833 834 835 836 837
		};

		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" }
838
			}
839 840
		*/
		return telemetryData;
841 842
	}

J
Johannes Rieken 已提交
843
	private doTouch(versionId: number): Promise<void> {
844 845
		if (!this.isResolved()) {
			return Promise.resolve();
M
Matt Bierner 已提交
846
		}
847

848 849
		return this.saveSequentializer.setPending(versionId, this.textFileService.write(this.lastResolvedFileStat.resource, this.createSnapshot(), {
			mtime: this.lastResolvedFileStat.mtime,
B
Benjamin Pasero 已提交
850
			encoding: this.getEncoding(),
851
			etag: this.lastResolvedFileStat.etag
B
Benjamin Pasero 已提交
852
		}).then(stat => {
853 854

			// Updated resolved stat with updated stat since touching it might have changed mtime
855
			this.updateLastResolvedFileStat(stat);
B
Benjamin Pasero 已提交
856 857 858 859

			// Emit File Saved Event
			this._onDidStateChange.fire(StateChange.SAVED);

B
Benjamin Pasero 已提交
860
		}, error => onUnexpectedError(error) /* just log any error but do not notify the user since the file was not dirty */));
861 862
	}

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

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

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

887 888 889 890 891 892
	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)
893
		if (this.isResolved()) {
894 895 896 897
			this.bufferSavedVersionId = this.textEditorModel.getAlternativeVersionId();
		}
	}

898
	private updateLastResolvedFileStat(newFileStat: IFileStatWithMetadata): void {
E
Erich Gamma 已提交
899 900

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

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

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

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

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

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

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

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

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

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

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

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

				return;
			}

			this.updatePreferredEncoding(encoding);

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

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

		this.preferredEncoding = encoding;

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

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

		return true;
	}

1013 1014
	isResolved(): this is IResolvedTextFileEditorModel {
		return !!this.textEditorModel;
E
Erich Gamma 已提交
1015 1016
	}

B
Benjamin Pasero 已提交
1017
	isReadonly(): boolean {
1018
		return !!(this.lastResolvedFileStat && this.lastResolvedFileStat.isReadonly);
1019 1020
	}

B
Benjamin Pasero 已提交
1021
	isDisposed(): boolean {
E
Erich Gamma 已提交
1022 1023 1024
		return this.disposed;
	}

B
Benjamin Pasero 已提交
1025
	getResource(): URI {
E
Erich Gamma 已提交
1026 1027 1028
		return this.resource;
	}

1029
	getStat(): IFileStatWithMetadata {
1030
		return this.lastResolvedFileStat;
B
Benjamin Pasero 已提交
1031 1032
	}

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

		super.dispose();
	}
1041 1042
}

1043 1044
interface IPendingSave {
	versionId: number;
J
Johannes Rieken 已提交
1045
	promise: Promise<void>;
1046 1047
}

1048
interface ISaveOperation {
J
Johannes Rieken 已提交
1049
	promise: Promise<void>;
B
Benjamin Pasero 已提交
1050 1051
	promiseResolve: () => void;
	promiseReject: (error: Error) => void;
J
Johannes Rieken 已提交
1052
	run: () => Promise<void>;
1053 1054 1055
}

export class SaveSequentializer {
1056 1057
	private _pendingSave?: IPendingSave;
	private _nextSave?: ISaveOperation;
1058

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

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

		return !!this._pendingSave;
	}

1071
	get pendingSave(): Promise<void> | undefined {
R
Rob Lourens 已提交
1072
		return this._pendingSave ? this._pendingSave.promise : undefined;
1073 1074
	}

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

1078
		promise.then(() => this.donePending(versionId), () => this.donePending(versionId));
1079 1080 1081 1082 1083 1084

		return promise;
	}

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

			// only set pending to done if the promise finished that is associated with that versionId
R
Rob Lourens 已提交
1087
			this._pendingSave = undefined;
1088 1089 1090

			// schedule the next save now that we are free if we have any
			this.triggerNextSave();
1091 1092 1093
		}
	}

1094 1095 1096
	private triggerNextSave(): void {
		if (this._nextSave) {
			const saveOperation = this._nextSave;
R
Rob Lourens 已提交
1097
			this._nextSave = undefined;
1098 1099

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

J
Johannes Rieken 已提交
1104
	setNext(run: () => Promise<void>): Promise<void> {
1105 1106 1107 1108 1109

		// 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 已提交
1110 1111
			let promiseResolve: () => void;
			let promiseReject: (error: Error) => void;
B
Benjamin Pasero 已提交
1112 1113 1114
			const promise = new Promise<void>((resolve, reject) => {
				promiseResolve = resolve;
				promiseReject = reject;
1115 1116 1117 1118 1119
			});

			this._nextSave = {
				run,
				promise,
M
Matt Bierner 已提交
1120 1121
				promiseResolve: promiseResolve!,
				promiseReject: promiseReject!
1122 1123 1124 1125 1126 1127 1128 1129
			};
		}

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

M
Matt Bierner 已提交
1130
		return this._nextSave.promise;
1131 1132 1133
	}
}

1134 1135
class DefaultSaveErrorHandler implements ISaveErrorHandler {

1136
	constructor(@INotificationService private readonly notificationService: INotificationService) { }
1137

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