-
Notifications
You must be signed in to change notification settings - Fork 30.4k
/
Copy pathtextFileEditorModel.ts
1125 lines (901 loc) · 39.9 KB
/
textFileEditorModel.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { Event, Emitter } from 'vs/base/common/event';
import { guessMimeTypes } from 'vs/base/common/mime';
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { URI } from 'vs/base/common/uri';
import { isUndefinedOrNull, assertIsDefined } from 'vs/base/common/types';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { ITextFileService, IAutoSaveConfiguration, ModelState, ITextFileEditorModel, ISaveOptions, ISaveErrorHandler, ISaveParticipant, StateChange, SaveReason, ITextFileStreamContent, ILoadOptions, LoadReason, IResolvedTextFileEditorModel } from 'vs/workbench/services/textfile/common/textfiles';
import { EncodingMode } from 'vs/workbench/common/editor';
import { BaseTextEditorModel } from 'vs/workbench/common/editor/textEditorModel';
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
import { IFileService, FileOperationError, FileOperationResult, CONTENT_CHANGE_EVENT_BUFFER_DELAY, FileChangesEvent, FileChangeType, IFileStatWithMetadata, ETAG_DISABLED } from 'vs/platform/files/common/files';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IModeService } from 'vs/editor/common/services/modeService';
import { IModelService } from 'vs/editor/common/services/modelService';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { RunOnceScheduler, timeout } from 'vs/base/common/async';
import { ITextBufferFactory } from 'vs/editor/common/model';
import { hash } from 'vs/base/common/hash';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { toDisposable, MutableDisposable } from 'vs/base/common/lifecycle';
import { ILogService } from 'vs/platform/log/common/log';
import { isEqual, isEqualOrParent, extname, basename, joinPath } from 'vs/base/common/resources';
import { onUnexpectedError } from 'vs/base/common/errors';
import { Schemas } from 'vs/base/common/network';
export interface IBackupMetaData {
mtime: number;
size: number;
etag: string;
orphaned: boolean;
}
type FileTelemetryDataFragment = {
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' };
};
type TelemetryData = {
mimeType: string;
ext: string;
path: number;
reason?: number;
whitelistedjson?: string;
};
/**
* 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.
*/
export class TextFileEditorModel extends BaseTextEditorModel implements ITextFileEditorModel {
static DEFAULT_CONTENT_CHANGE_BUFFER_DELAY = CONTENT_CHANGE_EVENT_BUFFER_DELAY;
static DEFAULT_ORPHANED_CHANGE_BUFFER_DELAY = 100;
static WHITELIST_JSON = ['package.json', 'package-lock.json', 'tsconfig.json', 'jsconfig.json', 'bower.json', '.eslintrc.json', 'tslint.json', 'composer.json'];
static WHITELIST_WORKSPACE_JSON = ['settings.json', 'extensions.json', 'tasks.json', 'launch.json'];
private static saveErrorHandler: ISaveErrorHandler;
static setSaveErrorHandler(handler: ISaveErrorHandler): void { TextFileEditorModel.saveErrorHandler = handler; }
private static saveParticipant: ISaveParticipant | null;
static setSaveParticipant(handler: ISaveParticipant | null): void { TextFileEditorModel.saveParticipant = handler; }
private readonly _onDidContentChange: Emitter<StateChange> = this._register(new Emitter<StateChange>());
readonly onDidContentChange: Event<StateChange> = this._onDidContentChange.event;
private readonly _onDidStateChange: Emitter<StateChange> = this._register(new Emitter<StateChange>());
readonly onDidStateChange: Event<StateChange> = this._onDidStateChange.event;
private contentEncoding: string | undefined; // encoding as reported from disk
private versionId = 0;
private bufferSavedVersionId: number | undefined;
private blockModelContentChange = false;
private lastResolvedFileStat: IFileStatWithMetadata | undefined;
private autoSaveAfterMillies: number | undefined;
private autoSaveAfterMilliesEnabled: boolean | undefined;
private readonly autoSaveDisposable = this._register(new MutableDisposable());
private readonly saveSequentializer = new SaveSequentializer();
private lastSaveAttemptTime = 0;
private readonly contentChangeEventScheduler = this._register(new RunOnceScheduler(() => this._onDidContentChange.fire(StateChange.CONTENT_CHANGE), TextFileEditorModel.DEFAULT_CONTENT_CHANGE_BUFFER_DELAY));
private readonly orphanedChangeEventScheduler = this._register(new RunOnceScheduler(() => this._onDidStateChange.fire(StateChange.ORPHANED_CHANGE), TextFileEditorModel.DEFAULT_ORPHANED_CHANGE_BUFFER_DELAY));
private dirty = false;
private inConflictMode = false;
private inOrphanMode = false;
private inErrorMode = false;
private disposed = false;
constructor(
private resource: URI,
private preferredEncoding: string | undefined, // encoding as chosen by the user
private preferredMode: string | undefined, // mode as chosen by the user
@INotificationService private readonly notificationService: INotificationService,
@IModeService modeService: IModeService,
@IModelService modelService: IModelService,
@IFileService private readonly fileService: IFileService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@ITextFileService private readonly textFileService: ITextFileService,
@IBackupFileService private readonly backupFileService: IBackupFileService,
@IEnvironmentService private readonly environmentService: IEnvironmentService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@ILogService private readonly logService: ILogService
) {
super(modelService, modeService);
this.updateAutoSaveConfiguration(textFileService.getAutoSaveConfiguration());
this.registerListeners();
}
private registerListeners(): void {
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)));
}
private onStateChange(e: StateChange): void {
if (e === StateChange.REVERTED) {
// 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);
}
}
private async onFileChanges(e: FileChangesEvent): Promise<void> {
let fileEventImpactsModel = false;
let newInOrphanModeGuess: boolean | undefined;
// 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;
}
}
// Otherwise we check if the model file was deleted
else {
const modelFileDeleted = e.contains(this.resource, FileChangeType.DELETED);
if (modelFileDeleted) {
newInOrphanModeGuess = true;
fileEventImpactsModel = true;
}
}
if (fileEventImpactsModel && this.inOrphanMode !== newInOrphanModeGuess) {
let newInOrphanModeValidated: boolean = false;
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.
await timeout(100);
if (this.disposed) {
newInOrphanModeValidated = true;
} else {
const exists = await this.fileService.exists(this.resource);
newInOrphanModeValidated = !exists;
}
}
if (this.inOrphanMode !== newInOrphanModeValidated && !this.disposed) {
this.setOrphaned(newInOrphanModeValidated);
}
}
}
private setOrphaned(orphaned: boolean): void {
if (this.inOrphanMode !== orphaned) {
this.inOrphanMode = orphaned;
this.orphanedChangeEventScheduler.schedule();
}
}
private updateAutoSaveConfiguration(config: IAutoSaveConfiguration): void {
const autoSaveAfterMilliesEnabled = (typeof config.autoSaveDelay === 'number') && config.autoSaveDelay > 0;
this.autoSaveAfterMilliesEnabled = autoSaveAfterMilliesEnabled;
this.autoSaveAfterMillies = autoSaveAfterMilliesEnabled ? config.autoSaveDelay : undefined;
}
private onFilesAssociationChange(): void {
if (!this.isResolved()) {
return;
}
const firstLineText = this.getFirstLineText(this.textEditorModel);
const languageSelection = this.getOrCreateMode(this.resource, this.modeService, this.preferredMode, firstLineText);
this.modelService.setMode(this.textEditorModel, languageSelection);
}
setMode(mode: string): void {
super.setMode(mode);
this.preferredMode = mode;
}
async backup(target = this.resource): Promise<void> {
if (this.isResolved()) {
// Only fill in model metadata if resource matches
let meta: IBackupMetaData | undefined = undefined;
if (isEqual(target, this.resource) && this.lastResolvedFileStat) {
meta = {
mtime: this.lastResolvedFileStat.mtime,
size: this.lastResolvedFileStat.size,
etag: this.lastResolvedFileStat.etag,
orphaned: this.inOrphanMode
};
}
return this.backupFileService.backupResource<IBackupMetaData>(target, this.createSnapshot(), this.versionId, meta);
}
}
hasBackup(): boolean {
return this.backupFileService.hasBackupSync(this.resource, this.versionId);
}
async revert(soft?: boolean): Promise<void> {
if (!this.isResolved()) {
return;
}
// Cancel any running auto-save
this.autoSaveDisposable.clear();
// Unset flags
const undo = this.setDirty(false);
// Force read from disk unless reverting soft
if (!soft) {
try {
await this.load({ forceReadFromDisk: true });
} catch (error) {
// Set flags back to previous values, we are still dirty if revert failed
undo();
throw error;
}
}
// Emit file change event
this._onDidStateChange.fire(StateChange.REVERTED);
}
async load(options?: ILoadOptions): Promise<ITextFileEditorModel> {
this.logService.trace('load() - enter', this.resource);
// 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.
if (this.dirty || this.saveSequentializer.hasPendingSave()) {
this.logService.trace('load() - exit - without loading because model is dirty or being saved', this.resource);
return this;
}
// Only for new models we support to load from backup
if (!this.isResolved()) {
const backup = await this.backupFileService.loadBackupResource(this.resource);
if (this.isResolved()) {
return this; // Make sure meanwhile someone else did not suceed in loading
}
if (backup) {
try {
return await this.loadFromBackup(backup, options);
} catch (error) {
this.logService.error(error); // ignore error and continue to load as file below
}
}
}
// Otherwise load from file resource
return this.loadFromFile(options);
}
private async loadFromBackup(backup: URI, options?: ILoadOptions): Promise<TextFileEditorModel> {
// Resolve actual backup contents
const resolvedBackup = await this.backupFileService.resolveBackupContent<IBackupMetaData>(backup);
if (this.isResolved()) {
return this; // Make sure meanwhile someone else did not suceed in loading
}
// Load with backup
this.loadFromContent({
resource: this.resource,
name: basename(this.resource),
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!
value: resolvedBackup.value,
encoding: this.textFileService.encoding.getPreferredWriteEncoding(this.resource, this.preferredEncoding).encoding,
isReadonly: false
}, options, true /* from backup */);
// Restore orphaned flag based on state
if (resolvedBackup.meta && resolvedBackup.meta.orphaned) {
this.setOrphaned(true);
}
return this;
}
private async loadFromFile(options?: ILoadOptions): Promise<TextFileEditorModel> {
const forceReadFromDisk = options && options.forceReadFromDisk;
const allowBinary = this.isResolved() /* always allow if we resolved previously */ || (options && options.allowBinary);
// Decide on etag
let etag: string | undefined;
if (forceReadFromDisk) {
etag = ETAG_DISABLED; // disable ETag if we enforce to read from disk
} else if (this.lastResolvedFileStat) {
etag = this.lastResolvedFileStat.etag; // otherwise respect etag to support caching
}
// 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;
// Resolve Content
try {
const content = await this.textFileService.readStream(this.resource, { acceptTextOnly: !allowBinary, etag, encoding: this.preferredEncoding });
// Clear orphaned state when loading was successful
this.setOrphaned(false);
if (currentVersionId !== this.versionId) {
return this; // Make sure meanwhile someone else did not suceed loading
}
return this.loadFromContent(content, options);
} catch (error) {
const result = error.fileOperationResult;
// Apply orphaned state based on error code
this.setOrphaned(result === FileOperationResult.FILE_NOT_FOUND);
// NotModified status is expected and can be handled gracefully
if (result === FileOperationResult.FILE_NOT_MODIFIED_SINCE) {
// Guard against the model having changed in the meantime
if (currentVersionId === this.versionId) {
this.setDirty(false); // Ensure we are not tracking a stale state
}
return this;
}
// 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;
}
}
private loadFromContent(content: ITextFileStreamContent, options?: ILoadOptions, fromBackup?: boolean): TextFileEditorModel {
this.logService.trace('load() - resolved content', this.resource);
// Update our resolved disk stat model
this.updateLastResolvedFileStat({
resource: this.resource,
name: content.name,
mtime: content.mtime,
size: content.size,
etag: content.etag,
isDirectory: false,
isSymbolicLink: false,
isReadonly: content.isReadonly
});
// 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);
}
// Update Existing Model
if (this.isResolved()) {
this.doUpdateTextModel(content.value);
}
// Create New Model
else {
this.doCreateTextModel(content.resource, content.value, !!fromBackup);
}
// Telemetry: We log the fileGet telemetry event after the model has been loaded to ensure a good mimetype
const settingsType = this.getTypeIfSettings();
if (settingsType) {
type SettingsReadClassification = {
settingsType: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
};
this.telemetryService.publicLog2<{ settingsType: string }, SettingsReadClassification>('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 {
type FileGetClassification = {} & FileTelemetryDataFragment;
this.telemetryService.publicLog2<TelemetryData, FileGetClassification>('fileGet', this.getTelemetryData(options && options.reason ? options.reason : LoadReason.OTHER));
}
return this;
}
private doCreateTextModel(resource: URI, value: ITextBufferFactory, fromBackup: boolean): void {
this.logService.trace('load() - created text editor model', this.resource);
// Create model
this.createTextEditorModel(value, resource, this.preferredMode);
// 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.doMakeDirty();
if (this.autoSaveAfterMilliesEnabled) {
this.doAutoSave(this.versionId);
}
}
// Ensure we are not tracking a stale state
else {
this.setDirty(false);
}
// Model Listeners
this.installModelListeners();
}
private doUpdateTextModel(value: ITextBufferFactory): void {
this.logService.trace('load() - updated text editor model', this.resource);
// Ensure we are not tracking a stale state
this.setDirty(false);
// Update model value in a block that ignores model content change events
this.blockModelContentChange = true;
try {
this.updateTextEditorModel(value, this.preferredMode);
} finally {
this.blockModelContentChange = false;
}
// Ensure we track the latest saved version ID given that the contents changed
this.updateSavedVersionId();
}
private installModelListeners(): void {
// 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.
// Content Change
if (this.isResolved()) {
this._register(this.textEditorModel.onDidChangeContent(() => this.onModelContentChanged()));
}
}
private onModelContentChanged(): void {
this.logService.trace(`onModelContentChanged() - enter`, this.resource);
// In any case increment the version id because it tracks the textual content state of the model at all times
this.versionId++;
this.logService.trace(`onModelContentChanged() - new versionId ${this.versionId}`, this.resource);
// 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.
if (!this.autoSaveAfterMilliesEnabled && this.isResolved() && this.textEditorModel.getAlternativeVersionId() === this.bufferSavedVersionId) {
this.logService.trace('onModelContentChanged() - model content changed back to last saved version', this.resource);
// Clear flags
const wasDirty = this.dirty;
this.setDirty(false);
// Emit event
if (wasDirty) {
this._onDidStateChange.fire(StateChange.REVERTED);
}
return;
}
this.logService.trace('onModelContentChanged() - model content changed and marked as dirty', this.resource);
// Mark as dirty
this.doMakeDirty();
// Start auto save process unless we are in conflict resolution mode and unless it is disabled
if (this.autoSaveAfterMilliesEnabled) {
if (!this.inConflictMode) {
this.doAutoSave(this.versionId);
} else {
this.logService.trace('makeDirty() - prevented save because we are in conflict resolution mode', this.resource);
}
}
// Handle content change events
this.contentChangeEventScheduler.schedule();
}
makeDirty(): void {
if (!this.isResolved()) {
return; // only resolved models can be marked dirty
}
this.doMakeDirty();
}
private doMakeDirty(): void {
// Track dirty state and version id
const wasDirty = this.dirty;
this.setDirty(true);
// Emit as Event if we turned dirty
if (!wasDirty) {
this._onDidStateChange.fire(StateChange.DIRTY);
}
}
private doAutoSave(versionId: number): void {
this.logService.trace(`doAutoSave() - enter for versionId ${versionId}`, this.resource);
// Cancel any currently running auto saves to make this the one that succeeds
this.autoSaveDisposable.clear();
// Create new save timer and store it for disposal as needed
const handle = setTimeout(() => {
// Clear the timeout now that we are running
this.autoSaveDisposable.clear();
// Only trigger save if the version id has not changed meanwhile
if (versionId === this.versionId) {
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
}
}, this.autoSaveAfterMillies);
this.autoSaveDisposable.value = toDisposable(() => clearTimeout(handle));
}
async save(options: ISaveOptions = Object.create(null)): Promise<void> {
if (!this.isResolved()) {
return;
}
this.logService.trace('save() - enter', this.resource);
// Cancel any currently running auto saves to make this the one that succeeds
this.autoSaveDisposable.clear();
return this.doSave(this.versionId, options);
}
private doSave(versionId: number, options: ISaveOptions): Promise<void> {
if (isUndefinedOrNull(options.reason)) {
options.reason = SaveReason.EXPLICIT;
}
this.logService.trace(`doSave(${versionId}) - enter with versionId ' + versionId`, this.resource);
// Lookup any running pending save for this versionId and return it if found
//
// Scenario: user invoked the save action multiple times quickly for the same contents
// while the save was not yet finished to disk
//
if (this.saveSequentializer.hasPendingSave(versionId)) {
this.logService.trace(`doSave(${versionId}) - exit - found a pending save for versionId ${versionId}`, this.resource);
return this.saveSequentializer.pendingSave || Promise.resolve();
}
// Return early if not dirty (unless forced) or version changed meanwhile
//
// 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.
//
if ((!options.force && !this.dirty) || versionId !== this.versionId) {
this.logService.trace(`doSave(${versionId}) - exit - because not dirty and/or versionId is different (this.isDirty: ${this.dirty}, this.versionId: ${this.versionId})`, this.resource);
return Promise.resolve();
}
// Return if currently saving by storing this save request as the next save that should happen.
// Never ever must 2 saves execute at the same time because this can lead to dirty writes and race conditions.
//
// Scenario A: auto save was triggered and is currently busy saving to disk. this takes long enough that another auto save
// kicks in.
// 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.
//
if (this.saveSequentializer.hasPendingSave()) {
this.logService.trace(`doSave(${versionId}) - exit - because busy saving`, this.resource);
// Register this as the next upcoming save and return
return this.saveSequentializer.setNext(() => this.doSave(this.versionId /* make sure to use latest version id here */, options));
}
// 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
if (!this.autoSaveAfterMilliesEnabled && this.isResolved()) {
this.textEditorModel.pushStackElement();
}
// A save participant can still change the model now and since we are so close to saving
// 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
// Save participants can also be skipped through API.
let saveParticipantPromise: Promise<number> = Promise.resolve(versionId);
if (TextFileEditorModel.saveParticipant && !options.skipSaveParticipants) {
const onCompleteOrError = () => {
this.blockModelContentChange = false;
return this.versionId;
};
this.blockModelContentChange = true;
saveParticipantPromise = TextFileEditorModel.saveParticipant.participate(this as IResolvedTextFileEditorModel, { reason: options.reason }).then(onCompleteOrError, onCompleteOrError);
}
// mark the save participant as current pending save operation
return this.saveSequentializer.setPending(versionId, saveParticipantPromise.then(newVersionId => {
// 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).
// To fix this issue, we will not store the contents to disk when we got disposed.
if (this.disposed) {
return;
}
// We require a resolved model from this point on, since we are about to write data to disk.
if (!this.isResolved()) {
return;
}
// 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.
// 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) {
return this.doTouch(newVersionId);
}
// update versionId with its new value (if pre-save changes happened)
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
// mark the save operation as currently pending with the versionId (it might have changed from a save participant triggering)
this.logService.trace(`doSave(${versionId}) - before write()`, this.resource);
const lastResolvedFileStat = assertIsDefined(this.lastResolvedFileStat);
return this.saveSequentializer.setPending(newVersionId, this.textFileService.write(lastResolvedFileStat.resource, this.createSnapshot(), {
overwriteReadonly: options.overwriteReadonly,
overwriteEncoding: options.overwriteEncoding,
mtime: lastResolvedFileStat.mtime,
encoding: this.getEncoding(),
etag: lastResolvedFileStat.etag,
writeElevated: options.writeElevated
}).then(stat => {
this.logService.trace(`doSave(${versionId}) - after write()`, this.resource);
// Update dirty state unless model has changed meanwhile
if (versionId === this.versionId) {
this.logService.trace(`doSave(${versionId}) - setting dirty to false because versionId did not change`, this.resource);
this.setDirty(false);
} else {
this.logService.trace(`doSave(${versionId}) - not setting dirty to false because versionId did change meanwhile`, this.resource);
}
// Updated resolved stat with updated stat
this.updateLastResolvedFileStat(stat);
// Cancel any content change event promises as they are no longer valid
this.contentChangeEventScheduler.cancel();
// Emit File Saved Event
this._onDidStateChange.fire(StateChange.SAVED);
// Telemetry
const settingsType = this.getTypeIfSettings();
if (settingsType) {
type SettingsWrittenClassification = {
settingsType: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
};
this.telemetryService.publicLog2<{ settingsType: string }, SettingsWrittenClassification>('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 {
type FilePutClassfication = {} & FileTelemetryDataFragment;
this.telemetryService.publicLog2<TelemetryData, FilePutClassfication>('filePUT', this.getTelemetryData(options.reason));
}
}, error => {
this.logService.error(`doSave(${versionId}) - exit - resulted in a save error: ${error.toString()}`, this.resource);
// Flag as error state in the model
this.inErrorMode = true;
// Look out for a save conflict
if ((<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_MODIFIED_SINCE) {
this.inConflictMode = true;
}
// Show to user
this.onSaveError(error);
// Emit as event
this._onDidStateChange.fire(StateChange.SAVE_ERROR);
}));
}));
}
private getTypeIfSettings(): string {
if (extname(this.resource) !== '.json') {
return '';
}
// Check for global settings file
if (isEqual(this.resource, this.environmentService.settingsResource)) {
return 'global-settings';
}
// Check for keybindings file
if (isEqual(this.resource, this.environmentService.keybindingsResource)) {
return 'keybindings';
}
// Check for snippets
if (isEqualOrParent(this.resource, joinPath(this.environmentService.userRoamingDataHome, 'snippets'))) {
return 'snippets';
}
// Check for workspace settings file
const folders = this.contextService.getWorkspace().folders;
for (const folder of folders) {
if (isEqualOrParent(this.resource, folder.toResource('.vscode'))) {
const filename = basename(this.resource);
if (TextFileEditorModel.WHITELIST_WORKSPACE_JSON.indexOf(filename) > -1) {
return `.vscode/${filename}`;
}
}
}
return '';
}
private getTelemetryData(reason: number | undefined): TelemetryData {
const ext = extname(this.resource);
const fileName = basename(this.resource);
const path = this.resource.scheme === Schemas.file ? this.resource.fsPath : this.resource.path;
const telemetryData = {
mimeType: guessMimeTypes(this.resource).join(', '),
ext,
path: hash(path),
reason,
whitelistedjson: undefined as string | undefined
};
if (ext === '.json' && TextFileEditorModel.WHITELIST_JSON.indexOf(fileName) > -1) {
telemetryData['whitelistedjson'] = fileName;
}
return telemetryData;
}
private doTouch(versionId: number): Promise<void> {
if (!this.isResolved()) {
return Promise.resolve();
}
const lastResolvedFileStat = assertIsDefined(this.lastResolvedFileStat);
return this.saveSequentializer.setPending(versionId, this.textFileService.write(lastResolvedFileStat.resource, this.createSnapshot(), {
mtime: lastResolvedFileStat.mtime,
encoding: this.getEncoding(),
etag: lastResolvedFileStat.etag
}).then(stat => {
// Updated resolved stat with updated stat since touching it might have changed mtime
this.updateLastResolvedFileStat(stat);
// Emit File Saved Event
this._onDidStateChange.fire(StateChange.SAVED);
}, error => onUnexpectedError(error) /* just log any error but do not notify the user since the file was not dirty */));
}
private setDirty(dirty: boolean): () => void {
const wasDirty = this.dirty;
const wasInConflictMode = this.inConflictMode;
const wasInErrorMode = this.inErrorMode;
const oldBufferSavedVersionId = this.bufferSavedVersionId;
if (!dirty) {
this.dirty = false;
this.inConflictMode = false;
this.inErrorMode = false;
this.updateSavedVersionId();
} else {
this.dirty = true;
}
// Return function to revert this call
return () => {
this.dirty = wasDirty;
this.inConflictMode = wasInConflictMode;
this.inErrorMode = wasInErrorMode;
this.bufferSavedVersionId = oldBufferSavedVersionId;
};
}
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.isResolved()) {
this.bufferSavedVersionId = this.textEditorModel.getAlternativeVersionId();
}
}
private updateLastResolvedFileStat(newFileStat: IFileStatWithMetadata): void {
// First resolve - just take
if (!this.lastResolvedFileStat) {
this.lastResolvedFileStat = newFileStat;
}
// Subsequent resolve - make sure that we only assign it if the mtime is equal or has advanced.
// 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.
else if (this.lastResolvedFileStat.mtime <= newFileStat.mtime) {
this.lastResolvedFileStat = newFileStat;
}
}
private onSaveError(error: Error): void {
// Prepare handler
if (!TextFileEditorModel.saveErrorHandler) {
TextFileEditorModel.setSaveErrorHandler(this.instantiationService.createInstance(DefaultSaveErrorHandler));
}
// Handle
TextFileEditorModel.saveErrorHandler.onSaveError(error, this);
}
isDirty(): this is IResolvedTextFileEditorModel {
return this.dirty;
}
getLastSaveAttemptTime(): number {
return this.lastSaveAttemptTime;
}
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.PENDING_AUTO_SAVE:
return !!this.autoSaveDisposable.value;
case ModelState.SAVED:
return !this.dirty;
}
}
getEncoding(): string | undefined {
return this.preferredEncoding || this.contentEncoding;
}
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();
}
if (!this.inConflictMode) {
this.save({ overwriteEncoding: true });
}
}
// Decode: Load with encoding
else {
if (this.isDirty()) {
this.notificationService.info(nls.localize('saveFileFirst', "The file is dirty. Please save it first before reopening it with another encoding."));
return;
}
this.updatePreferredEncoding(encoding);
// Load
this.load({
forceReadFromDisk: true // because encoding has changed
});
}
}
updatePreferredEncoding(encoding: string | undefined): void {
if (!this.isNewEncoding(encoding)) {
return;
}
this.preferredEncoding = encoding;
// Emit
this._onDidStateChange.fire(StateChange.ENCODING);
}
private isNewEncoding(encoding: string | undefined): boolean {
if (this.preferredEncoding === encoding) {
return false; // return early if the encoding is already the same
}
if (!this.preferredEncoding && this.contentEncoding === encoding) {
return false; // also return if we don't have a preferred encoding but the content encoding is already the same
}
return true;
}
isResolved(): this is IResolvedTextFileEditorModel {
return !!this.textEditorModel;
}