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

T
t-amqi 已提交
7
import * as path from 'vs/base/common/paths';
E
Erich Gamma 已提交
8
import nls = require('vs/nls');
J
Johannes Rieken 已提交
9
import Event, { Emitter } from 'vs/base/common/event';
10
import { TPromise, TValueCallback, ErrorCallback } from 'vs/base/common/winjs.base';
J
Johannes Rieken 已提交
11 12 13
import { onUnexpectedError } from 'vs/base/common/errors';
import { guessMimeTypes } from 'vs/base/common/mime';
import { toErrorMessage } from 'vs/base/common/errorMessage';
E
Erich Gamma 已提交
14
import URI from 'vs/base/common/uri';
J
Johannes Rieken 已提交
15
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
E
Erich Gamma 已提交
16 17 18
import paths = require('vs/base/common/paths');
import diagnostics = require('vs/base/common/diagnostics');
import types = require('vs/base/common/types');
J
Johannes Rieken 已提交
19
import { IMode } from 'vs/editor/common/modes';
20
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
21
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
22
import { ITextFileService, IAutoSaveConfiguration, ModelState, ITextFileEditorModel, ISaveOptions, ISaveErrorHandler, ISaveParticipant, StateChange, SaveReason, IRawTextContent } from 'vs/workbench/services/textfile/common/textfiles';
B
Benjamin Pasero 已提交
23
import { EncodingMode } from 'vs/workbench/common/editor';
J
Johannes Rieken 已提交
24
import { BaseTextEditorModel } from 'vs/workbench/common/editor/textEditorModel';
25
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
26
import { IFileService, IFileStat, FileOperationError, FileOperationResult, CONTENT_CHANGE_EVENT_BUFFER_DELAY, FileChangesEvent, FileChangeType } from 'vs/platform/files/common/files';
J
Johannes Rieken 已提交
27 28
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IModeService } from 'vs/editor/common/services/modeService';
29
import { IModelService } from 'vs/editor/common/services/modelService';
30
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
31
import { RunOnceScheduler } from 'vs/base/common/async';
32
import { ITextBufferFactory } from 'vs/editor/common/model';
R
Ramya Achutha Rao 已提交
33
import { IHashService } from 'vs/workbench/services/hash/common/hashService';
34
import { createTextBufferFactory } from 'vs/editor/common/model/textModel';
35
import { INotificationService } from 'vs/platform/notification/common/notification';
B
Benjamin Pasero 已提交
36

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

42
	public static DEFAULT_CONTENT_CHANGE_BUFFER_DELAY = CONTENT_CHANGE_EVENT_BUFFER_DELAY;
43
	public static DEFAULT_ORPHANED_CHANGE_BUFFER_DELAY = 100;
44

E
Erich Gamma 已提交
45
	private static saveErrorHandler: ISaveErrorHandler;
B
Benjamin Pasero 已提交
46
	private static saveParticipant: ISaveParticipant;
E
Erich Gamma 已提交
47 48 49 50 51 52 53

	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;
54
	private lastResolvedDiskStat: IFileStat;
55
	private toDispose: IDisposable[];
E
Erich Gamma 已提交
56
	private blockModelContentChange: boolean;
57
	private autoSaveAfterMillies: number;
58
	private autoSaveAfterMilliesEnabled: boolean;
59
	private autoSavePromise: TPromise<void>;
60
	private contentChangeEventScheduler: RunOnceScheduler;
61
	private orphanedChangeEventScheduler: RunOnceScheduler;
62
	private saveSequentializer: SaveSequentializer;
E
Erich Gamma 已提交
63
	private disposed: boolean;
B
Benjamin Pasero 已提交
64
	private lastSaveAttemptTime: number;
E
Erich Gamma 已提交
65
	private createTextEditorModelPromise: TPromise<TextFileEditorModel>;
M
Matt Bierner 已提交
66 67
	private readonly _onDidContentChange: Emitter<StateChange>;
	private readonly _onDidStateChange: Emitter<StateChange>;
E
Erich Gamma 已提交
68

69 70 71 72
	private inConflictMode: boolean;
	private inOrphanMode: boolean;
	private inErrorMode: boolean;

E
Erich Gamma 已提交
73 74 75
	constructor(
		resource: URI,
		preferredEncoding: string,
76
		@INotificationService private notificationService: INotificationService,
E
Erich Gamma 已提交
77 78 79 80
		@IModeService modeService: IModeService,
		@IModelService modelService: IModelService,
		@IFileService private fileService: IFileService,
		@IInstantiationService private instantiationService: IInstantiationService,
81
		@ITelemetryService private telemetryService: ITelemetryService,
82
		@ITextFileService private textFileService: ITextFileService,
83
		@IBackupFileService private backupFileService: IBackupFileService,
84
		@IEnvironmentService private environmentService: IEnvironmentService,
T
t-amqi 已提交
85
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
R
Ramya Achutha Rao 已提交
86
		@IHashService private hashService: IHashService
E
Erich Gamma 已提交
87 88 89
	) {
		super(modelService, modeService);
		this.resource = resource;
B
Benjamin Pasero 已提交
90
		this.toDispose = [];
91
		this._onDidContentChange = new Emitter<StateChange>();
92
		this._onDidStateChange = new Emitter<StateChange>();
93
		this.toDispose.push(this._onDidContentChange);
94
		this.toDispose.push(this._onDidStateChange);
E
Erich Gamma 已提交
95
		this.preferredEncoding = preferredEncoding;
96
		this.inOrphanMode = false;
E
Erich Gamma 已提交
97 98
		this.dirty = false;
		this.versionId = 0;
B
Benjamin Pasero 已提交
99
		this.lastSaveAttemptTime = 0;
100
		this.saveSequentializer = new SaveSequentializer();
101

102
		this.contentChangeEventScheduler = new RunOnceScheduler(() => this._onDidContentChange.fire(StateChange.CONTENT_CHANGE), TextFileEditorModel.DEFAULT_CONTENT_CHANGE_BUFFER_DELAY);
103
		this.toDispose.push(this.contentChangeEventScheduler);
E
Erich Gamma 已提交
104

105 106 107
		this.orphanedChangeEventScheduler = new RunOnceScheduler(() => this._onDidStateChange.fire(StateChange.ORPHANED_CHANGE), TextFileEditorModel.DEFAULT_ORPHANED_CHANGE_BUFFER_DELAY);
		this.toDispose.push(this.orphanedChangeEventScheduler);

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

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

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

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

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

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

131 132
	private onFileChanges(e: FileChangesEvent): void {

133
		// Track ADD and DELETES for updates of this model to orphan-mode
134 135 136 137 138 139 140 141 142 143 144
		const modelFileDeleted = e.contains(this.resource, FileChangeType.DELETED);
		const modelFileAdded = e.contains(this.resource, FileChangeType.ADDED);

		if (modelFileDeleted || modelFileAdded) {
			const newInOrphanModeGuess = modelFileDeleted && !modelFileAdded;
			if (this.inOrphanMode !== newInOrphanModeGuess) {
				let checkOrphanedPromise: TPromise<boolean>;
				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
145
					// file is really gone and not just a faulty file event.
146 147 148 149 150 151 152 153 154 155
					checkOrphanedPromise = TPromise.timeout(100).then(() => {
						if (this.disposed) {
							return true;
						}

						return this.fileService.existsFile(this.resource).then(exists => !exists);
					});
				} else {
					checkOrphanedPromise = TPromise.as(false);
				}
156

157 158 159 160
				checkOrphanedPromise.done(newInOrphanModeValidated => {
					if (this.inOrphanMode !== newInOrphanModeValidated && !this.disposed) {
						this.setOrphaned(newInOrphanModeValidated);
					}
161 162
				});
			}
163 164 165 166 167 168 169 170 171 172
		}
	}

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

173
	private updateAutoSaveConfiguration(config: IAutoSaveConfiguration): void {
174
		if (typeof config.autoSaveDelay === 'number' && config.autoSaveDelay > 0) {
175
			this.autoSaveAfterMillies = config.autoSaveDelay;
176
			this.autoSaveAfterMilliesEnabled = true;
E
Erich Gamma 已提交
177
		} else {
178
			this.autoSaveAfterMillies = void 0;
179
			this.autoSaveAfterMilliesEnabled = false;
E
Erich Gamma 已提交
180 181 182
		}
	}

183 184 185 186
	private onFilesAssociationChange(): void {
		this.updateTextEditorModelMode();
	}

B
Benjamin Pasero 已提交
187 188 189 190 191
	private updateTextEditorModelMode(modeId?: string): void {
		if (!this.textEditorModel) {
			return;
		}

A
Alex Dima 已提交
192
		const firstLineText = this.getFirstLineText(this.textEditorModel);
B
Benjamin Pasero 已提交
193 194 195 196 197
		const mode = this.getOrCreateMode(this.modeService, modeId, firstLineText);

		this.modelService.setMode(this.textEditorModel, mode);
	}

198
	public get onDidContentChange(): Event<StateChange> {
199 200 201
		return this._onDidContentChange.event;
	}

202 203 204 205
	public get onDidStateChange(): Event<StateChange> {
		return this._onDidStateChange.event;
	}

206 207 208 209 210 211 212
	/**
	 * The current version id of the model.
	 */
	public getVersionId(): number {
		return this.versionId;
	}

E
Erich Gamma 已提交
213 214 215 216 217 218 219
	/**
	 * Set a save error handler to install code that executes when save errors occur.
	 */
	public static setSaveErrorHandler(handler: ISaveErrorHandler): void {
		TextFileEditorModel.saveErrorHandler = handler;
	}

B
Benjamin Pasero 已提交
220 221 222 223 224 225 226
	/**
	 * Set a save participant handler to react on models getting saved.
	 */
	public static setSaveParticipant(handler: ISaveParticipant): void {
		TextFileEditorModel.saveParticipant = handler;
	}

E
Erich Gamma 已提交
227 228
	/**
	 * Discards any local changes and replaces the model with the contents of the version on disk.
229 230
	 *
	 * @param if the parameter soft is true, will not attempt to load the contents from disk.
E
Erich Gamma 已提交
231
	 */
232
	public revert(soft?: boolean): TPromise<void> {
E
Erich Gamma 已提交
233
		if (!this.isResolved()) {
234
			return TPromise.wrap<void>(null);
E
Erich Gamma 已提交
235 236
		}

237 238
		// Cancel any running auto-save
		this.cancelAutoSavePromise();
E
Erich Gamma 已提交
239 240

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

B
Benjamin Pasero 已提交
243
		let loadPromise: TPromise<TextFileEditorModel>;
244 245 246 247 248 249 250
		if (soft) {
			loadPromise = TPromise.as(this);
		} else {
			loadPromise = this.load(true /* force */);
		}

		return loadPromise.then(() => {
E
Erich Gamma 已提交
251 252

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

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

259
			return TPromise.wrapError(error);
E
Erich Gamma 已提交
260 261 262
		});
	}

B
Benjamin Pasero 已提交
263
	public load(force?: boolean /* bypass any caches and really go to disk */): TPromise<TextFileEditorModel> {
E
Erich Gamma 已提交
264 265 266 267 268 269 270 271 272 273 274
		diag('load() - enter', this.resource, new Date());

		// It is very important to not reload the model when the model is dirty. We only want to reload the model from the disk
		// if no save is pending to avoid data loss. This might cause a save conflict in case the file has been modified on the disk
		// meanwhile, but this is a very low risk.
		if (this.dirty) {
			diag('load() - exit - without loading because model is dirty', this.resource, new Date());

			return TPromise.as(this);
		}

275 276 277 278 279 280 281 282 283
		// Only for new models we support to load from backup
		if (!this.textEditorModel && !this.createTextEditorModelPromise) {
			return this.loadWithBackup(force);
		}

		// Otherwise load from file resource
		return this.loadFromFile(force);
	}

B
Benjamin Pasero 已提交
284
	private loadWithBackup(force: boolean): TPromise<TextFileEditorModel> {
285 286 287 288 289 290 291 292 293
		return this.backupFileService.loadBackupResource(this.resource).then(backup => {

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

			// If we have a backup, continue loading with it
			if (!!backup) {
294
				const content: IRawTextContent = {
295 296 297 298
					resource: this.resource,
					name: paths.basename(this.resource.fsPath),
					mtime: Date.now(),
					etag: void 0,
299
					value: createTextBufferFactory(''), /* will be filled later from backup */
300
					encoding: this.fileService.getEncoding(this.resource, this.preferredEncoding)
301 302 303 304 305 306 307 308 309 310
				};

				return this.loadWithContent(content, backup);
			}

			// Otherwise load from file
			return this.loadFromFile(force);
		});
	}

B
Benjamin Pasero 已提交
311
	private loadFromFile(force: boolean): TPromise<TextFileEditorModel> {
312

E
Erich Gamma 已提交
313 314 315
		// Decide on etag
		let etag: string;
		if (force) {
316
			etag = void 0; // bypass cache if force loading is true
317 318
		} else if (this.lastResolvedDiskStat) {
			etag = this.lastResolvedDiskStat.etag; // otherwise respect etag to support caching
E
Erich Gamma 已提交
319 320
		}

T
t-amqi 已提交
321 322 323
		// Resolve Content
		return this.textFileService
			.resolveTextContent(this.resource, { acceptTextOnly: true, etag, encoding: this.preferredEncoding })
T
t-amqi 已提交
324
			.then(content => this.handleLoadSuccess(content), error => this.handleLoadError(error));
325 326
	}

B
Benjamin Pasero 已提交
327
	private handleLoadSuccess(content: IRawTextContent): TPromise<TextFileEditorModel> {
328 329 330 331 332

		// Clear orphaned state when load was successful
		this.setOrphaned(false);

		return this.loadWithContent(content);
333
	}
E
Erich Gamma 已提交
334

335
	private handleLoadError(error: FileOperationError): TPromise<TextFileEditorModel> {
336
		const result = error.fileOperationResult;
E
Erich Gamma 已提交
337

338 339 340
		// Apply orphaned state based on error code
		this.setOrphaned(result === FileOperationResult.FILE_NOT_FOUND);

341 342 343
		// NotModified status is expected and can be handled gracefully
		if (result === FileOperationResult.FILE_NOT_MODIFIED_SINCE) {
			this.setDirty(false); // Ensure we are not tracking a stale state
E
Erich Gamma 已提交
344

B
Benjamin Pasero 已提交
345
			return TPromise.as<TextFileEditorModel>(this);
346 347
		}

348 349 350 351
		// 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) {
B
Benjamin Pasero 已提交
352
			return TPromise.as<TextFileEditorModel>(this);
353 354
		}

355
		// Otherwise bubble up the error
B
Benjamin Pasero 已提交
356
		return TPromise.wrapError<TextFileEditorModel>(error);
357
	}
E
Erich Gamma 已提交
358

359
	private loadWithContent(content: IRawTextContent, backup?: URI): TPromise<TextFileEditorModel> {
360
		return this.doLoadWithContent(content, backup).then(model => {
361

362 363 364 365 366 367 368 369 370 371 372
			// Telemetry: We log the fileGet telemetry event after the model has been loaded to ensure a good mimetype
			if (this.isSettingsFile()) {
				/* __GDPR__
					"settingsRead" : {}
				*/
				this.telemetryService.publicLog('settingsRead'); // 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" : {
						"mimeType" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
						"ext": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
K
kieferrm 已提交
373
						"path": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
374 375
					}
				*/
R
Ramya Achutha Rao 已提交
376
				this.telemetryService.publicLog('fileGet', { mimeType: guessMimeTypes(this.resource.fsPath).join(', '), ext: paths.extname(this.resource.fsPath), path: this.hashService.createSHA1(this.resource.fsPath) });
377
			}
378 379 380 381 382

			return model;
		});
	}

383
	private doLoadWithContent(content: IRawTextContent, backup?: URI): TPromise<TextFileEditorModel> {
384
		diag('load() - resolved content', this.resource, new Date());
385 386 387 388 389 390 391 392

		// Update our resolved disk stat model
		const resolvedStat: IFileStat = {
			resource: this.resource,
			name: content.name,
			mtime: content.mtime,
			etag: content.etag,
			isDirectory: false,
393
			isSymbolicLink: false,
B
Benjamin Pasero 已提交
394
			children: void 0
395
		};
396
		this.updateLastResolvedDiskStat(resolvedStat);
397 398 399 400 401 402 403 404 405 406 407

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

409 410
		// Update Existing Model
		if (this.textEditorModel) {
411
			return this.doUpdateTextModel(content.value);
412
		}
E
Erich Gamma 已提交
413

414 415 416
		// Join an existing request to create the editor model to avoid race conditions
		else if (this.createTextEditorModelPromise) {
			diag('load() - join existing text editor model promise', this.resource, new Date());
E
Erich Gamma 已提交
417

418 419
			return this.createTextEditorModelPromise;
		}
E
Erich Gamma 已提交
420

421
		// Create New Model
422
		return this.doCreateTextModel(content.resource, content.value, backup);
423
	}
E
Erich Gamma 已提交
424

425
	private doUpdateTextModel(value: ITextBufferFactory): TPromise<TextFileEditorModel> {
426
		diag('load() - updated text editor model', this.resource, new Date());
427

428 429
		// Ensure we are not tracking a stale state
		this.setDirty(false);
430

431
		// Update model value in a block that ignores model content change events
432 433 434 435 436 437 438
		this.blockModelContentChange = true;
		try {
			this.updateTextEditorModel(value);
		} finally {
			this.blockModelContentChange = false;
		}

439 440 441
		// Ensure we track the latest saved version ID given that the contents changed
		this.updateSavedVersionId();

B
Benjamin Pasero 已提交
442
		return TPromise.as<TextFileEditorModel>(this);
443 444
	}

445
	private doCreateTextModel(resource: URI, value: ITextBufferFactory, backup: URI): TPromise<TextFileEditorModel> {
446 447
		diag('load() - created text editor model', this.resource, new Date());

448
		this.createTextEditorModelPromise = this.doLoadBackup(backup).then(backupContent => {
449
			const hasBackupContent = !!backupContent;
450 451 452 453 454 455 456 457 458 459 460 461

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

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

464 465 466 467 468
				// Ensure we are not tracking a stale state
				else {
					this.setDirty(false);
				}

B
Benjamin Pasero 已提交
469 470
				// Model Listeners
				this.installModelListeners();
471 472 473 474 475

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

476
				return TPromise.wrapError<TextFileEditorModel>(error);
477
			});
478
		});
479

480 481 482
		return this.createTextEditorModelPromise;
	}

B
Benjamin Pasero 已提交
483 484
	private installModelListeners(): void {

485 486 487
		// 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 已提交
488 489 490

		// Content Change
		this.toDispose.push(this.textEditorModel.onDidChangeContent(() => this.onModelContentChanged()));
491 492
	}

493
	private doLoadBackup(backup: URI): TPromise<ITextBufferFactory> {
494 495 496
		if (!backup) {
			return TPromise.as(null);
		}
497

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

501
	protected getOrCreateMode(modeService: IModeService, preferredModeIds: string, firstLineText?: string): TPromise<IMode> {
E
Erich Gamma 已提交
502 503 504
		return modeService.getOrCreateModeByFilenameOrFirstLine(this.resource.fsPath, firstLineText);
	}

505 506
	private onModelContentChanged(): void {
		diag(`onModelContentChanged() - enter`, this.resource, new Date());
E
Erich Gamma 已提交
507 508 509

		// In any case increment the version id because it tracks the textual content state of the model at all times
		this.versionId++;
B
Benjamin Pasero 已提交
510
		diag(`onModelContentChanged() - new versionId ${this.versionId}`, this.resource, new Date());
E
Erich Gamma 已提交
511 512 513 514 515 516 517 518 519 520

		// 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.
521
		if (!this.autoSaveAfterMilliesEnabled && this.textEditorModel.getAlternativeVersionId() === this.bufferSavedVersionId) {
E
Erich Gamma 已提交
522 523 524
			diag('onModelContentChanged() - model content changed back to last saved version', this.resource, new Date());

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

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

			return;
		}

		diag('onModelContentChanged() - model content changed and marked as dirty', this.resource, new Date());

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

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

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

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

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

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

	private doAutoSave(versionId: number): TPromise<void> {
B
Benjamin Pasero 已提交
567
		diag(`doAutoSave() - enter for versionId ${versionId}`, this.resource, new Date());
E
Erich Gamma 已提交
568 569

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

572
		// Create new save promise and keep it
573
		this.autoSavePromise = TPromise.timeout(this.autoSaveAfterMillies).then(() => {
E
Erich Gamma 已提交
574 575 576

			// Only trigger save if the version id has not changed meanwhile
			if (versionId === this.versionId) {
577
				this.doSave(versionId, { reason: SaveReason.AUTO }).done(null, onUnexpectedError); // 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 已提交
578 579 580
			}
		});

581
		return this.autoSavePromise;
E
Erich Gamma 已提交
582 583
	}

584 585 586 587
	private cancelAutoSavePromise(): void {
		if (this.autoSavePromise) {
			this.autoSavePromise.cancel();
			this.autoSavePromise = void 0;
E
Erich Gamma 已提交
588 589 590 591 592 593
		}
	}

	/**
	 * Saves the current versionId of this editor model if it is dirty.
	 */
594
	public save(options: ISaveOptions = Object.create(null)): TPromise<void> {
E
Erich Gamma 已提交
595
		if (!this.isResolved()) {
596
			return TPromise.wrap<void>(null);
E
Erich Gamma 已提交
597 598 599 600 601
		}

		diag('save() - enter', this.resource, new Date());

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

604
		return this.doSave(this.versionId, options);
E
Erich Gamma 已提交
605 606
	}

607 608 609 610 611
	private doSave(versionId: number, options: ISaveOptions): TPromise<void> {
		if (types.isUndefinedOrNull(options.reason)) {
			options.reason = SaveReason.EXPLICIT;
		}

B
Benjamin Pasero 已提交
612
		diag(`doSave(${versionId}) - enter with versionId ' + versionId`, this.resource, new Date());
E
Erich Gamma 已提交
613 614

		// Lookup any running pending save for this versionId and return it if found
B
Benjamin Pasero 已提交
615 616 617 618
		//
		// Scenario: user invoked the save action multiple times quickly for the same contents
		//           while the save was not yet finished to disk
		//
619
		if (this.saveSequentializer.hasPendingSave(versionId)) {
B
Benjamin Pasero 已提交
620
			diag(`doSave(${versionId}) - exit - found a pending save for versionId ${versionId}`, this.resource, new Date());
E
Erich Gamma 已提交
621

622
			return this.saveSequentializer.pendingSave;
E
Erich Gamma 已提交
623 624
		}

625
		// Return early if not dirty (unless forced) or version changed meanwhile
B
Benjamin Pasero 已提交
626 627 628 629 630 631
		//
		// 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.
		//
632
		if ((!options.force && !this.dirty) || versionId !== this.versionId) {
B
Benjamin Pasero 已提交
633
			diag(`doSave(${versionId}) - exit - because not dirty and/or versionId is different (this.isDirty: ${this.dirty}, this.versionId: ${this.versionId})`, this.resource, new Date());
E
Erich Gamma 已提交
634

635
			return TPromise.wrap<void>(null);
E
Erich Gamma 已提交
636 637
		}

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

649
			// Register this as the next upcoming save and return
650
			return this.saveSequentializer.setNext(() => this.doSave(this.versionId /* make sure to use latest version id here */, options));
E
Erich Gamma 已提交
651 652 653 654
		}

		// 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
655
		if (!this.autoSaveAfterMilliesEnabled) {
E
Erich Gamma 已提交
656 657 658
			this.textEditorModel.pushStackElement();
		}

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

668
				return this.versionId;
B
💄  
Benjamin Pasero 已提交
669 670
			};

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

674
				return TextFileEditorModel.saveParticipant.participate(this, { reason: options.reason });
B
💄  
Benjamin Pasero 已提交
675
			}).then(onCompleteOrError, onCompleteOrError);
E
Erich Gamma 已提交
676 677
		}

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

681 682 683 684 685 686 687 688 689
			// Under certain conditions a save to the model will not cause the contents to the flushed on
			// disk because we can assume that the contents are already on disk. Instead, we just touch the
			// file to still trigger external file watchers for example.
			// 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) {
690
				return this.doTouch();
691 692
			}

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

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

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

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

				// Telemetry
716
				if (this.isSettingsFile()) {
K
kieferrm 已提交
717
					/* __GDPR__
K
kieferrm 已提交
718 719
						"settingsWritten" : {}
					*/
720
					this.telemetryService.publicLog('settingsWritten'); // Do not log write to user settings.json and .vscode folder as a filePUT event as it ruins our JSON usage data
721
				} else {
K
kieferrm 已提交
722
					/* __GDPR__
K
kieferrm 已提交
723 724 725 726 727
						"filePUT" : {
							"mimeType" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
							"ext": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
						}
					*/
728 729
					this.telemetryService.publicLog('filePUT', { mimeType: guessMimeTypes(this.resource.fsPath).join(', '), ext: paths.extname(this.lastResolvedDiskStat.resource.fsPath) });
				}
J
Johannes Rieken 已提交
730 731 732 733 734 735 736 737

				// Update dirty state unless model has changed meanwhile
				if (versionId === this.versionId) {
					diag(`doSave(${versionId}) - setting dirty to false because versionId did not change`, this.resource, new Date());
					this.setDirty(false);
				} else {
					diag(`doSave(${versionId}) - not setting dirty to false because versionId did change meanwhile`, this.resource, new Date());
				}
E
Erich Gamma 已提交
738

739
				// Updated resolved stat with updated stat
740
				this.updateLastResolvedDiskStat(stat);
E
Erich Gamma 已提交
741

742 743 744
				// Cancel any content change event promises as they are no longer valid
				this.contentChangeEventScheduler.cancel();

J
Johannes Rieken 已提交
745 746
				// Emit File Saved Event
				this._onDidStateChange.fire(StateChange.SAVED);
747
			}, error => {
J
Johannes Rieken 已提交
748
				diag(`doSave(${versionId}) - exit - resulted in a save error: ${error.toString()}`, this.resource, new Date());
E
Erich Gamma 已提交
749

750
				// Flag as error state in the model
J
Johannes Rieken 已提交
751
				this.inErrorMode = true;
E
Erich Gamma 已提交
752

753
				// Look out for a save conflict
754
				if ((<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_MODIFIED_SINCE) {
755 756 757
					this.inConflictMode = true;
				}

J
Johannes Rieken 已提交
758 759
				// Show to user
				this.onSaveError(error);
E
Erich Gamma 已提交
760

J
Johannes Rieken 已提交
761 762
				// Emit as event
				this._onDidStateChange.fire(StateChange.SAVE_ERROR);
763 764
			}));
		}));
E
Erich Gamma 已提交
765 766
	}

767 768 769 770 771 772 773 774
	private isSettingsFile(): boolean {

		// Check for global settings file
		if (this.resource.fsPath === this.environmentService.appSettingsPath) {
			return true;
		}

		// Check for workspace settings file
S
Sandeep Somavarapu 已提交
775
		return this.contextService.getWorkspace().folders.some(folder => {
776
			return paths.isEqualOrParent(this.resource.fsPath, path.join(folder.uri.fsPath, '.vscode'));
777
		});
778 779
	}

780 781 782 783 784 785 786 787
	private doTouch(): TPromise<void> {
		return this.fileService.touchFile(this.resource).then(stat => {

			// Updated resolved stat with updated stat since touching it might have changed mtime
			this.updateLastResolvedDiskStat(stat);
		}, () => void 0 /* gracefully ignore errors if just touching */);
	}

E
Erich Gamma 已提交
788
	private setDirty(dirty: boolean): () => void {
B
Benjamin Pasero 已提交
789
		const wasDirty = this.dirty;
790
		const wasInConflictMode = this.inConflictMode;
B
Benjamin Pasero 已提交
791 792
		const wasInErrorMode = this.inErrorMode;
		const oldBufferSavedVersionId = this.bufferSavedVersionId;
E
Erich Gamma 已提交
793 794 795

		if (!dirty) {
			this.dirty = false;
796
			this.inConflictMode = false;
E
Erich Gamma 已提交
797
			this.inErrorMode = false;
798
			this.updateSavedVersionId();
E
Erich Gamma 已提交
799 800 801 802 803 804 805
		} else {
			this.dirty = true;
		}

		// Return function to revert this call
		return () => {
			this.dirty = wasDirty;
806
			this.inConflictMode = wasInConflictMode;
E
Erich Gamma 已提交
807 808 809 810 811
			this.inErrorMode = wasInErrorMode;
			this.bufferSavedVersionId = oldBufferSavedVersionId;
		};
	}

812 813 814 815 816 817 818 819 820 821 822
	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();
		}
	}

823
	private updateLastResolvedDiskStat(newVersionOnDiskStat: IFileStat): void {
E
Erich Gamma 已提交
824 825

		// First resolve - just take
826 827
		if (!this.lastResolvedDiskStat) {
			this.lastResolvedDiskStat = newVersionOnDiskStat;
E
Erich Gamma 已提交
828 829 830 831 832
		}

		// Subsequent resolve - make sure that we only assign it if the mtime is equal or has advanced.
		// This is essential a If-Modified-Since check on the client ot prevent race conditions from loading
		// and saving. If a save comes in late after a revert was called, the mtime could be out of sync.
833 834
		else if (this.lastResolvedDiskStat.mtime <= newVersionOnDiskStat.mtime) {
			this.lastResolvedDiskStat = newVersionOnDiskStat;
E
Erich Gamma 已提交
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
		}
	}

	private onSaveError(error: any): void {

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

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

	/**
	 * Returns true if the content of this model has changes that are not yet saved back to the disk.
	 */
	public isDirty(): boolean {
		return this.dirty;
	}

	/**
B
Benjamin Pasero 已提交
857
	 * Returns the time in millies when this working copy was attempted to be saved.
E
Erich Gamma 已提交
858
	 */
B
Benjamin Pasero 已提交
859 860
	public getLastSaveAttemptTime(): number {
		return this.lastSaveAttemptTime;
E
Erich Gamma 已提交
861 862
	}

863 864 865 866 867
	/**
	 * Returns the time in millies when this working copy was last modified by the user or some other program.
	 */
	public getETag(): string {
		return this.lastResolvedDiskStat ? this.lastResolvedDiskStat.etag : null;
E
Erich Gamma 已提交
868 869 870
	}

	/**
871
	 * Answers if this model is in a specific state.
E
Erich Gamma 已提交
872
	 */
873 874 875 876 877 878 879 880 881 882 883 884 885 886
	public hasState(state: ModelState): boolean {
		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 已提交
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
		}
	}

	public getEncoding(): string {
		return this.preferredEncoding || this.contentEncoding;
	}

	public setEncoding(encoding: string, mode: EncodingMode): void {
		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();
			}

909
			if (!this.inConflictMode) {
B
Benjamin Pasero 已提交
910
				this.save({ overwriteEncoding: true }).done(null, onUnexpectedError);
E
Erich Gamma 已提交
911 912 913 914 915 916
			}
		}

		// Decode: Load with encoding
		else {
			if (this.isDirty()) {
917
				this.notificationService.info(nls.localize('saveFileFirst', "The file is dirty. Please save it first before reopening it with another encoding."));
E
Erich Gamma 已提交
918 919 920 921 922 923 924 925 926 927 928

				return;
			}

			this.updatePreferredEncoding(encoding);

			// Load
			this.load(true /* force because encoding has changed */).done(null, onUnexpectedError);
		}
	}

929
	public updatePreferredEncoding(encoding: string): void {
E
Erich Gamma 已提交
930 931 932 933 934 935 936
		if (!this.isNewEncoding(encoding)) {
			return;
		}

		this.preferredEncoding = encoding;

		// Emit
937
		this._onDidStateChange.fire(StateChange.ENCODING);
E
Erich Gamma 已提交
938 939 940 941 942 943 944 945
	}

	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) {
946
			return false; // also return if we don't have a preferred encoding but the content encoding is already the same
E
Erich Gamma 已提交
947 948 949 950 951 952
		}

		return true;
	}

	public isResolved(): boolean {
953
		return !types.isUndefinedOrNull(this.lastResolvedDiskStat);
E
Erich Gamma 已提交
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
	}

	/**
	 * Returns true if the dispose() method of this model has been called.
	 */
	public isDisposed(): boolean {
		return this.disposed;
	}

	/**
	 * Returns the full resource URI of the file this text file editor model is about.
	 */
	public getResource(): URI {
		return this.resource;
	}

B
Benjamin Pasero 已提交
970 971 972 973 974 975 976
	/**
	 * Stat accessor only used by tests.
	 */
	public getStat(): IFileStat {
		return this.lastResolvedDiskStat;
	}

E
Erich Gamma 已提交
977 978
	public dispose(): void {
		this.disposed = true;
979 980
		this.inConflictMode = false;
		this.inOrphanMode = false;
E
Erich Gamma 已提交
981 982
		this.inErrorMode = false;

983
		this.toDispose = dispose(this.toDispose);
E
Erich Gamma 已提交
984 985
		this.createTextEditorModelPromise = null;

986
		this.cancelAutoSavePromise();
D
Daniel Imms 已提交
987

E
Erich Gamma 已提交
988 989
		super.dispose();
	}
990 991
}

992 993 994 995 996
interface IPendingSave {
	versionId: number;
	promise: TPromise<void>;
}

997 998 999 1000 1001 1002 1003 1004
interface ISaveOperation {
	promise: TPromise<void>;
	promiseValue: TValueCallback<void>;
	promiseError: ErrorCallback;
	run: () => TPromise<void>;
}

export class SaveSequentializer {
1005
	private _pendingSave: IPendingSave;
1006
	private _nextSave: ISaveOperation;
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019

	public hasPendingSave(versionId?: number): boolean {
		if (!this._pendingSave) {
			return false;
		}

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

		return !!this._pendingSave;
	}

1020 1021 1022 1023
	public get pendingSave(): TPromise<void> {
		return this._pendingSave ? this._pendingSave.promise : void 0;
	}

1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
	public setPending(versionId: number, promise: TPromise<void>): TPromise<void> {
		this._pendingSave = { versionId, promise };

		promise.done(() => this.donePending(versionId), () => this.donePending(versionId));

		return promise;
	}

	private donePending(versionId: number): void {
		if (this._pendingSave && versionId === this._pendingSave.versionId) {
1034 1035 1036 1037 1038 1039

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

			// schedule the next save now that we are free if we have any
			this.triggerNextSave();
1040 1041 1042
		}
	}

1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
	private triggerNextSave(): void {
		if (this._nextSave) {
			const saveOperation = this._nextSave;
			this._nextSave = void 0;

			// Run next save and complete on the associated promise
			saveOperation.run().done(saveOperation.promiseValue, saveOperation.promiseError);
		}
	}

	public setNext(run: () => TPromise<void>): TPromise<void> {

		// 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) {
			let promiseValue: TValueCallback<void>;
			let promiseError: ErrorCallback;
			const promise = new TPromise<void>((c, e) => {
				promiseValue = c;
				promiseError = e;
			});

			this._nextSave = {
				run,
				promise,
				promiseValue,
				promiseError
			};
		}

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

		return this._nextSave.promise;
1080 1081 1082
	}
}

1083 1084
class DefaultSaveErrorHandler implements ISaveErrorHandler {

M
Matt Bierner 已提交
1085
	constructor(@INotificationService private notificationService: INotificationService) { }
1086 1087

	public onSaveError(error: any, model: TextFileEditorModel): void {
1088
		this.notificationService.error(nls.localize('genericSaveError', "Failed to save '{0}': {1}", paths.basename(model.getResource().fsPath), toErrorMessage(error, false)));
1089 1090 1091 1092 1093 1094 1095 1096 1097
	}
}

// Diagnostics support
let diag: (...args: any[]) => void;
if (!diag) {
	diag = diagnostics.register('TextFileEditorModelDiagnostics', function (...args: any[]) {
		console.log(args[1] + ' - ' + args[0] + ' (time: ' + args[2].getTime() + ' [' + args[2].toUTCString() + '])');
	});
1098
}