Merge VS Code 1.26.1 (#2394)

* Squash merge commits for 1.26 (#1) (#2323)

* Polish tag search as per feedback (#55269)

* Polish tag search as per feedback

* Updated regex

* Allow users to opt-out of features that send online requests in the background (#55097)

* settings sweep #54690

* Minor css tweaks to enable eoverflow elipsis in more places (#55277)

* fix an issue with titlebarheight when not scaling with zoom

* Settings descriptions update #54690

* fixes #55209

* Settings editor - many padding fixes

* More space above level 2 label

* Fixing Cannot debug npm script using Yarn #55103

* Settings editor - show ellipsis when description overflows

* Settings editor - ... fix measuring around links, relayout

* Setting descriptions

* Settings editor - fix ... for some short lines, fix select container width

* Settings editor - overlay trees so scrollable shadow is full width

* Fix #54133 - missing extension settings after reload

* Settings color token description tweak

* Settings editor - disable overflow indicator temporarily, needs to be faster

* Added command to Run the selected npm script

* fixes #54452

* fixes #54929

* fixes #55248

* prefix command with extension name

* Contribute run selected to the context menu

* node-debug@1.26.6

* Allow terminal rendererType to be swapped out at runtime

Part of #53274
Fixes #55344

* Settings editor - fix not focusing search when restoring editor
setInput must be actually async. Will be fixed naturally when we aren't using winJS promises...

* Settings editor - TOC should only expand the section with a selected item

* Bump node-debug2

* Settings editor - Tree focus outlines

* Settings editor - don't blink the scrollbar when toc selection changes
And hide TOC correctly when the editor is narrow

* Settings editor - header rows should not be selectable

* fixes #54877

* change debug assignee to isi

* Settings sweep (#54690)

* workaround for #55051

* Settings sweep (#54690)

* settings sweep

#54690

* Don't try closing tags when you type > after another >

* Describe what implementation code lens does

Fixes #55370

* fix javadoc formatter setting description

* fixes #55325

* update to officical TS version

* Settings editor - Even more padding, use semibold instead of bold

* Fix #55357 - fix TOC twistie

* fixes #55288

* explorer: refresh on di change file system provider registration

fixes #53256

* Disable push to Linux repo to test standalone publisher

* New env var to notify log level to extensions #54001

* Disable snippets in extension search (when not in suggest dropdown) (#55281)

* Disable snippits in extension search (when not in suggest dropdown)

* Add monaco input contributions

* Fix bug preventing snippetSuggestions from taking effect in sub-editors

* Latest emmet helper to fix #52366

* Fix comment updates for threads within same file

* Allow extensions to log telemetry to log files #54001

* Pull latest css grammar

* files.exclude control - use same style for "add" vs "edit"

* files.exclude control - focus/keyboard behavior

* don't show menubar too early

* files.exclude - better styling

* Place cursor at end of extensions search box on autofill (#55254)

* Place cursor at end of extensions search box on autofill

* Use position instead of selection

* fix linux build issue (empty if block)

* Settings editor - fix extension category prefixes

* Settings editor - add simple ellipsis for first line that overflows, doesn't cover case when first line does not overflow but there is more text, TODO

* File/Text search provider docs

* Fixes #52655

* Include epoch (#55008)

* Fixes #53385

* Fixes #49480

*  VS Code Insiders (Users) not opening Fixes #55353

* Better handling of the case when the extension host fails to start

* Fixes #53966

*  Remove confusing Start from wordPartLeft commands ID

* vscode-xterm@3.6.0-beta12

Fixes #55488

* Initial size is set to infinity!! Fixes #55461

* Polish embeddedEditorBackground

* configuration service misses event

* Fix #55224 - fix duplicate results in multiroot workspace from splitting the diskseach query

* Select all not working in issue reporter on mac, fixes #55424

* Disable fuzzy matching for extensions autosuggest (#55498)

* Fix clipping of extensions search border in some third party themes (#55504)

* fixes #55538

* Fix bug causing an aria alert to not be shown the third time
 (and odd numbers thereafter)

* Settings editor - work around rendering glitch with webkit-line-clamp

* Settings editor - revert earlier '...' changes

* Settings editor - move enumDescription to its own div, because it disturbs -webkit-line-clamp for some reason

* Settings editor - better overflow indicator

* Don't show existing filters in autocomplete (#55495)

* Dont show existing filters in autocomplete

* Simplify

* Settings Editor: Add aria labels for input elements Fixes: #54836 (#55543)

* fixes #55223

* Update vscode-css-languageservice to 3.0.10-next.1

* Fix #55509 - settings navigation

* Fix #55519

* Fix #55520

* FIx #55524

* Fix #55556 - include wordSeparators in all search queries, so findTextInFiles can respect isWordMatch correctly

* oss updates for endgame

* Fix unit tests

* fixes #55522

* Avoid missing manifest error from bubbling up #54757

* Settings format crawl

* Search provider - Fix FileSearchProvider to return array, not progress

* Fix #55598

* Settings editor - fix NPE rendering settings with no description

* dont render inden guides in search box (#55600)

* fixes #55454

* More settings crawl

* Another change for #55598 - maxResults applies to FileSearch and TextSearch but not FileIndex

* Fix FileSearchProvider unit tests for progress change

* fixes #55561

* Settings description update for #54690

* Update setting descriptions for online services

* Minor edits

* fixes #55513

* fixes #55451

* Fix #55612 - fix findTextInFiles cancellation

* fixes #55539

* More setting description tweaks

* Setting to disable online experiments #54354

* fixes #55507

* fixes #55515

* Show online services action only in Insiders for now

* Settings editor - change toc behavior default to 'filter'

* Settings editor - nicer filter count style during search

* Fix #55617 - search viewlet icons

* Settings editor - better styling for element count indicator

* SearchProvider - fix NPE when searching extraFileResources

* Allow extends to work without json suffix

Fixes #16905

* Remove accessability options logic entirely

Follow up on #55451

* use latest version of DAP

* fixes #55490

* fixes #55122

* fixes #52332

* Avoid assumptions about git: URIs (fixes #36236)

* relative path for descriptions

* resourece: get rid of isFile context key

fixes #48275

* Register previous ids for compatibility (#53497)

* more tuning for #48275

* no need to always re-read "files explorer"

fixes #52003

* read out active composites properly

fixes #51967

* Update link colors for hc theme to meet color contrast ratio, fixes #55651

Also updated link color for `textLinkActiveForeground` to be the same as `textLinkForeground` as it wasn't properly updated

* detect 'winpty-agent.exe'; fixes #55672

* node-debug@1.26.7

* reset counter on new label

* Settings editor - fix multiple setting links in one description

* Settings editor - color code blocks in setting descriptions, fix #55532

* Settings editor - hover color in TOC

* Settings editor - fix navigation NPE

* Settings editor - fix text control width

* Settings editor - maybe fix #55684

* Fix bug causing cursor to not move on paste

* fixes #53582

* Use ctrlCmd instead of ctrl for go down from search box

* fixes #55264

* fixes #55456

* filter for spcaes before triggering search (#55611)

* Fix #55698 - don't lose filtered TOC counts when refreshing TOC

* fixes #55421

* fixes #28979

* fixes #55576

* only add check for updates to windows/linux help

* readonly files: append decoration to label

fixes #53022

* debug: do not show toolbar while initialising

fixes #55026

* Opening launch.json should not activate debug extensions

fixes #55029

* fixes #55435

* fixes #55434

* fixes #55439

* trigger menu only on altkey up

* Fix #50555 - fix settings editor memory leak

* Fix #55712 - no need to focus 'a' anymore when restoring control focus after tree render

* fixes #55335

* proper fix for readonly model

fixes #53022

* improve FoldingRangeKind spec (for #55686)

* Use class with static fields (fixes #55494)

* Fixes #53671

* fixes #54630

* [html] should disable ionic suggestions by default. Currently forces deprecated Ionic v1 suggestions in .html files while typing. Fixes #53324

* cleanup deps

* debug issues back to andre

* update electron for smoketest

* Fix #55757 - prevent settings tabs from overflowing

* Fix #53897 - revert setting menu defaults to old editor

* Add enum descriptions to `typescript.preferences.importModuleSpecifier`

* Fix #55767 - leaking style elements from settings editor

* Fix #55521 - prevent flashing when clicking in exclude control

* Update Git modified color for contrast ratio, fixes #53140

* Revert "Merge branch 'master' of github.com:Microsoft/vscode"

This reverts commit bf46b6bfbae0cab99c2863e1244a916181fa9fbc, reversing
changes made to e275a424483dfb4ed33b428c97d5e2c441d6b917.

* Revert "Revert "Merge branch 'master' of github.com:Microsoft/vscode""

This reverts commit 53949d963f39e40757557c6526332354a31d9154.

* don't ask to install an incomplete menu

* Fix NPE in terminal AccessibilityManager

Fixes #55744

* don't display fallback menu unless we've closed the last window

* fixes #55547

* Fix smoke tests for extension search box

* Update OSSREADME.json for Electron 2.0.5

* Update distro

Includes Chromium license changes

* fix #55455

* fix #55865

* fixes #55893

* Fix bug causing workspace recommendations to go away upon ignoring a recommendation (#55805)

* Fix bug causing workspace recommendations to go away upon ignoring a recommendation

* ONly show on @recommended or @recommended:workspace

* Make more consistant

* Fix #55911

* Understand json activity (#55926)

* Understand json file activity

* Refactoring

* adding composer.json

* Distro update for experiments

* use terminal.processId for auto-attach; fixes #55918

* Reject invalid URI with vscode.openFolder (for #55891)

* improve win32 setup system vs user detection

fixes #55840

fixes #55840

delay winreg import

related to #55840

show notification earlier

related to #55840

fix #55840

update inno setup message

related to #55840

* Fix #55593 - this code only operates on local paths, so use fsPath and Uri.file instead

* Bring back the old menu due to electron 2.0 issues (#55913)

* add the old menu back for native menus

* make menu labels match

* `vscode.openFolder`: treat missing URI schema gracefully (for #55891)

* delay EH reattach; fixes #55955

* Mark all json files under appSettingsHome as settings

* Use localized strings for telemetry opt-out

* Exception when saving file editor opened from remote file provider (fixes #55051)

* Remove terminal menu from stable

Fixes 56003

* VSCode Insiders crashes on open with TypeError: Cannot read property 'lastIndexOf' of undefined. Fixes #54933

* improve fix for #55891

* fix #55916

* Improve #55891

* increase EH debugging restart delay; fixes #55955

* Revert "Don't include non-resource entries in history quick pick"

This reverts commit 37209a838e9f7e9abe6dc53ed73cdf1e03b72060.

* Diff editor: horizontal scrollbar height is smaller (fixes #56062)

* improve openFolder uri fix (correctly treat backslashes)

* fixes #56116
repair ipc for native menubar keybindings

* Fix #56240 - Open the JSON settings editor instead of the UI editor

* Fix #55536

* uriDisplay: if no formatter is registered fall back to getPathlabel

fixes #56104

* VSCode hangs when opening python file. Fixes #56377

* VS Code Hangs When Opening Specific PowerShell File. Fixes #56430

* Fix #56433 - search extraFileResources even when no folders open

* Workaround #55649

* Fix in master #56371

* Fix tests #56371

* Fix in master #56317

* increase version to 1.26.1

* Fixes #56387: Handle SIGPIPE in extension host

* fixes #56185

* Fix merge issues (part 1)

* Fix build breaks (part 1)

* Build breaks (part 2)

* Build breaks (part 3)

* More build breaks (part 4)

* Fix build breaks (part 5)

* WIP

* Fix menus

* Render query result and message panels (#2363)

* Put back query editor hot exit changes

* Fix grid changes that broke profiler (#2365)

* Update APIs for saving query editor state

* Fix restore view state for profiler and edit data

* Updating custom default themes to support 4.5:1 contrast ratio

* Test updates

* Fix Extension Manager and Windows Setup

* Update license headers

* Add appveyor and travis files back

* Fix hidden modal dropdown issue
This commit is contained in:
Karl Burtram
2018-09-04 14:55:00 -07:00
committed by GitHub
parent 3763278366
commit 81329fa7fa
2638 changed files with 118456 additions and 64012 deletions

View File

@@ -12,13 +12,11 @@ import { onUnexpectedError } from 'vs/base/common/errors';
import { guessMimeTypes } from 'vs/base/common/mime';
import { toErrorMessage } from 'vs/base/common/errorMessage';
import URI from 'vs/base/common/uri';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import * as diagnostics from 'vs/base/common/diagnostics';
import * as types from 'vs/base/common/types';
import { isUndefinedOrNull } from 'vs/base/common/types';
import { IMode } from 'vs/editor/common/modes';
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, IRawTextContent, ILoadOptions } from 'vs/workbench/services/textfile/common/textfiles';
import { ITextFileService, IAutoSaveConfiguration, ModelState, ITextFileEditorModel, ISaveOptions, ISaveErrorHandler, ISaveParticipant, StateChange, SaveReason, IRawTextContent, ILoadOptions, LoadReason } 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';
@@ -32,17 +30,32 @@ import { ITextBufferFactory } from 'vs/editor/common/model';
import { IHashService } from 'vs/workbench/services/hash/common/hashService';
import { createTextBufferFactory } from 'vs/editor/common/model/textModel';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { isLinux } from 'vs/base/common/platform';
import { IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { ILogService } from 'vs/platform/log/common/log';
import { isEqual, isEqualOrParent, hasToIgnoreCase } from 'vs/base/common/resources';
/**
* 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 {
public static DEFAULT_CONTENT_CHANGE_BUFFER_DELAY = CONTENT_CHANGE_EVENT_BUFFER_DELAY;
public static DEFAULT_ORPHANED_CHANGE_BUFFER_DELAY = 100;
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;
static setSaveParticipant(handler: ISaveParticipant): void { TextFileEditorModel.saveParticipant = handler; }
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; }
private resource: URI;
private contentEncoding: string; // encoding as reported from disk
@@ -51,20 +64,16 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
private versionId: number;
private bufferSavedVersionId: number;
private lastResolvedDiskStat: IFileStat;
private toDispose: IDisposable[];
private blockModelContentChange: boolean;
private autoSaveAfterMillies: number;
private autoSaveAfterMilliesEnabled: boolean;
private autoSavePromise: TPromise<void>;
private autoSaveDisposable: IDisposable;
private contentChangeEventScheduler: RunOnceScheduler;
private orphanedChangeEventScheduler: RunOnceScheduler;
private saveSequentializer: SaveSequentializer;
private disposed: boolean;
private lastSaveAttemptTime: number;
private createTextEditorModelPromise: TPromise<TextFileEditorModel>;
private readonly _onDidContentChange: Emitter<StateChange>;
private readonly _onDidStateChange: Emitter<StateChange>;
private inConflictMode: boolean;
private inOrphanMode: boolean;
private inErrorMode: boolean;
@@ -82,15 +91,12 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
@IBackupFileService private backupFileService: IBackupFileService,
@IEnvironmentService private environmentService: IEnvironmentService,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@IHashService private hashService: IHashService
@IHashService private hashService: IHashService,
@ILogService private logService: ILogService
) {
super(modelService, modeService);
this.resource = resource;
this.toDispose = [];
this._onDidContentChange = new Emitter<StateChange>();
this._onDidStateChange = new Emitter<StateChange>();
this.toDispose.push(this._onDidContentChange);
this.toDispose.push(this._onDidStateChange);
this.preferredEncoding = preferredEncoding;
this.inOrphanMode = false;
this.dirty = false;
@@ -98,11 +104,8 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
this.lastSaveAttemptTime = 0;
this.saveSequentializer = new SaveSequentializer();
this.contentChangeEventScheduler = new RunOnceScheduler(() => this._onDidContentChange.fire(StateChange.CONTENT_CHANGE), TextFileEditorModel.DEFAULT_CONTENT_CHANGE_BUFFER_DELAY);
this.toDispose.push(this.contentChangeEventScheduler);
this.orphanedChangeEventScheduler = new RunOnceScheduler(() => this._onDidStateChange.fire(StateChange.ORPHANED_CHANGE), TextFileEditorModel.DEFAULT_ORPHANED_CHANGE_BUFFER_DELAY);
this.toDispose.push(this.orphanedChangeEventScheduler);
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));
this.updateAutoSaveConfiguration(textFileService.getAutoSaveConfiguration());
@@ -110,10 +113,10 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
}
private registerListeners(): void {
this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e)));
this.toDispose.push(this.textFileService.onAutoSaveConfigurationChange(config => this.updateAutoSaveConfiguration(config)));
this.toDispose.push(this.textFileService.onFilesAssociationChange(e => this.onFilesAssociationChange()));
this.toDispose.push(this.onDidStateChange(e => this.onStateChange(e)));
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 {
@@ -183,71 +186,34 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
}
private updateAutoSaveConfiguration(config: IAutoSaveConfiguration): void {
if (typeof config.autoSaveDelay === 'number' && config.autoSaveDelay > 0) {
this.autoSaveAfterMillies = config.autoSaveDelay;
this.autoSaveAfterMilliesEnabled = true;
} else {
this.autoSaveAfterMillies = void 0;
this.autoSaveAfterMilliesEnabled = false;
}
const autoSaveAfterMilliesEnabled = (typeof config.autoSaveDelay === 'number') && config.autoSaveDelay > 0;
this.autoSaveAfterMilliesEnabled = autoSaveAfterMilliesEnabled;
this.autoSaveAfterMillies = autoSaveAfterMilliesEnabled ? config.autoSaveDelay : void 0;
}
private onFilesAssociationChange(): void {
this.updateTextEditorModelMode();
}
private updateTextEditorModelMode(modeId?: string): void {
if (!this.textEditorModel) {
return;
}
const firstLineText = this.getFirstLineText(this.textEditorModel);
const mode = this.getOrCreateMode(this.modeService, modeId, firstLineText);
const mode = this.getOrCreateMode(this.modeService, void 0, firstLineText);
this.modelService.setMode(this.textEditorModel, mode);
}
public get onDidContentChange(): Event<StateChange> {
return this._onDidContentChange.event;
}
public get onDidStateChange(): Event<StateChange> {
return this._onDidStateChange.event;
}
/**
* The current version id of the model.
*/
public getVersionId(): number {
getVersionId(): number {
return this.versionId;
}
/**
* Set a save error handler to install code that executes when save errors occur.
*/
public static setSaveErrorHandler(handler: ISaveErrorHandler): void {
TextFileEditorModel.saveErrorHandler = handler;
}
/**
* Set a save participant handler to react on models getting saved.
*/
public static setSaveParticipant(handler: ISaveParticipant): void {
TextFileEditorModel.saveParticipant = handler;
}
/**
* Discards any local changes and replaces the model with the contents of the version on disk.
*
* @param if the parameter soft is true, will not attempt to load the contents from disk.
*/
public revert(soft?: boolean): TPromise<void> {
revert(soft?: boolean): TPromise<void> {
if (!this.isResolved()) {
return TPromise.wrap<void>(null);
}
// Cancel any running auto-save
this.cancelAutoSavePromise();
this.cancelPendingAutoSave();
// Unset flags
const undo = this.setDirty(false);
@@ -272,28 +238,28 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
});
}
public load(options?: ILoadOptions): TPromise<TextFileEditorModel> {
diag('load() - enter', this.resource, new Date());
load(options?: ILoadOptions): TPromise<TextFileEditorModel> {
this.logService.trace('load() - enter', this.resource);
// 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.
// 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()) {
diag('load() - exit - without loading because model is dirty or being saved', this.resource, new Date());
this.logService.trace('load() - exit - without loading because model is dirty or being saved', this.resource);
return TPromise.as(this);
}
// Only for new models we support to load from backup
if (!this.textEditorModel && !this.createTextEditorModelPromise) {
return this.loadWithBackup(options);
return this.loadFromBackup(options);
}
// Otherwise load from file resource
return this.loadFromFile(options);
}
private loadWithBackup(options?: ILoadOptions): TPromise<TextFileEditorModel> {
private loadFromBackup(options?: ILoadOptions): TPromise<TextFileEditorModel> {
return this.backupFileService.loadBackupResource(this.resource).then(backup => {
// Make sure meanwhile someone else did not suceed or start loading
@@ -309,10 +275,11 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
mtime: Date.now(),
etag: void 0,
value: createTextBufferFactory(''), /* will be filled later from backup */
encoding: this.fileService.encoding.getWriteEncoding(this.resource, this.preferredEncoding)
encoding: this.fileService.encoding.getWriteEncoding(this.resource, this.preferredEncoding),
isReadonly: false
};
return this.loadWithContent(content, backup);
return this.loadWithContent(content, options, backup);
}
// Otherwise load from file
@@ -332,62 +299,77 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
etag = this.lastResolvedDiskStat.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
return this.textFileService
.resolveTextContent(this.resource, { acceptTextOnly: !allowBinary, etag, encoding: this.preferredEncoding })
.then(content => this.handleLoadSuccess(content), error => this.handleLoadError(error));
.then(content => {
// Clear orphaned state when loading was successful
this.setOrphaned(false);
// Guard against the model having changed in the meantime
if (currentVersionId === this.versionId) {
return this.loadWithContent(content, options);
}
return this;
}, 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 TPromise.as<TextFileEditorModel>(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 TPromise.as<TextFileEditorModel>(this);
}
// Otherwise bubble up the error
return TPromise.wrapError<TextFileEditorModel>(error);
});
}
private handleLoadSuccess(content: IRawTextContent): TPromise<TextFileEditorModel> {
// Clear orphaned state when load was successful
this.setOrphaned(false);
return this.loadWithContent(content);
}
private handleLoadError(error: FileOperationError): TPromise<TextFileEditorModel> {
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) {
this.setDirty(false); // Ensure we are not tracking a stale state
return TPromise.as<TextFileEditorModel>(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 TPromise.as<TextFileEditorModel>(this);
}
// Otherwise bubble up the error
return TPromise.wrapError<TextFileEditorModel>(error);
}
private loadWithContent(content: IRawTextContent, backup?: URI): TPromise<TextFileEditorModel> {
private loadWithContent(content: IRawTextContent, options?: ILoadOptions, backup?: URI): TPromise<TextFileEditorModel> {
return this.doLoadWithContent(content, backup).then(model => {
// Telemetry: We log the fileGet telemetry event after the model has been loaded to ensure a good mimetype
if (this.isSettingsFile()) {
const settingsType = this.getTypeIfSettings();
if (settingsType) {
/* __GDPR__
"settingsRead" : {}
"settingsRead" : {
"settingsType": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
}
*/
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
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" : {
"mimeType" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"ext": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"path": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
"${include}": [
"${FileTelemetryData}"
]
}
*/
this.telemetryService.publicLog('fileGet', { mimeType: guessMimeTypes(this.resource.fsPath).join(', '), ext: path.extname(this.resource.fsPath), path: this.hashService.createSHA1(this.resource.fsPath) });
this.telemetryService.publicLog('fileGet', this.getTelemetryData(options && options.reason ? options.reason : LoadReason.OTHER));
}
return model;
@@ -395,19 +377,19 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
}
private doLoadWithContent(content: IRawTextContent, backup?: URI): TPromise<TextFileEditorModel> {
diag('load() - resolved content', this.resource, new Date());
this.logService.trace('load() - resolved content', this.resource);
// Update our resolved disk stat model
const resolvedStat: IFileStat = {
this.updateLastResolvedDiskStat({
resource: this.resource,
name: content.name,
mtime: content.mtime,
etag: content.etag,
isDirectory: false,
isSymbolicLink: false,
children: void 0
};
this.updateLastResolvedDiskStat(resolvedStat);
children: void 0,
isReadonly: content.isReadonly
} as IFileStat);
// Keep the original encoding to not loose it when saving
const oldEncoding = this.contentEncoding;
@@ -427,7 +409,7 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
// 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());
this.logService.trace('load() - join existing text editor model promise', this.resource);
return this.createTextEditorModelPromise;
}
@@ -437,7 +419,7 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
}
private doUpdateTextModel(value: ITextBufferFactory): TPromise<TextFileEditorModel> {
diag('load() - updated text editor model', this.resource, new Date());
this.logService.trace('load() - updated text editor model', this.resource);
// Ensure we are not tracking a stale state
this.setDirty(false);
@@ -457,7 +439,7 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
}
private doCreateTextModel(resource: URI, value: ITextBufferFactory, backup: URI): TPromise<TextFileEditorModel> {
diag('load() - created text editor model', this.resource, new Date());
this.logService.trace('load() - created text editor model', this.resource);
this.createTextEditorModelPromise = this.doLoadBackup(backup).then(backupContent => {
const hasBackupContent = !!backupContent;
@@ -501,7 +483,7 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
// where `value` was captured in the content change listener closure scope.
// Content Change
this.toDispose.push(this.textEditorModel.onDidChangeContent(() => this.onModelContentChanged()));
this._register(this.textEditorModel.onDidChangeContent(() => this.onModelContentChanged()));
}
private doLoadBackup(backup: URI): TPromise<ITextBufferFactory> {
@@ -517,11 +499,11 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
}
private onModelContentChanged(): void {
diag(`onModelContentChanged() - enter`, this.resource, new Date());
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++;
diag(`onModelContentChanged() - new versionId ${this.versionId}`, this.resource, new Date());
this.logService.trace(`onModelContentChanged() - new versionId ${this.versionId}`, this.resource);
// Ignore if blocking model changes
if (this.blockModelContentChange) {
@@ -533,7 +515,7 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
// 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.textEditorModel.getAlternativeVersionId() === this.bufferSavedVersionId) {
diag('onModelContentChanged() - model content changed back to last saved version', this.resource, new Date());
this.logService.trace('onModelContentChanged() - model content changed back to last saved version', this.resource);
// Clear flags
const wasDirty = this.dirty;
@@ -547,7 +529,7 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
return;
}
diag('onModelContentChanged() - model content changed and marked as dirty', this.resource, new Date());
this.logService.trace('onModelContentChanged() - model content changed and marked as dirty', this.resource);
// Mark as dirty
this.makeDirty();
@@ -557,7 +539,7 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
if (!this.inConflictMode) {
this.doAutoSave(this.versionId);
} else {
diag('makeDirty() - prevented save because we are in conflict resolution mode', this.resource, new Date());
this.logService.trace('makeDirty() - prevented save because we are in conflict resolution mode', this.resource);
}
}
@@ -577,53 +559,50 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
}
}
private doAutoSave(versionId: number): TPromise<void> {
diag(`doAutoSave() - enter for versionId ${versionId}`, this.resource, new Date());
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.cancelAutoSavePromise();
this.cancelPendingAutoSave();
// Create new save promise and keep it
this.autoSavePromise = TPromise.timeout(this.autoSaveAfterMillies).then(() => {
// Create new save timer and store it for disposal as needed
const handle = setTimeout(() => {
// Only trigger save if the version id has not changed meanwhile
if (versionId === this.versionId) {
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
}
});
}, this.autoSaveAfterMillies);
return this.autoSavePromise;
this.autoSaveDisposable = toDisposable(() => clearTimeout(handle));
}
private cancelAutoSavePromise(): void {
if (this.autoSavePromise) {
this.autoSavePromise.cancel();
this.autoSavePromise = void 0;
private cancelPendingAutoSave(): void {
if (this.autoSaveDisposable) {
this.autoSaveDisposable.dispose();
this.autoSaveDisposable = void 0;
}
}
/**
* Saves the current versionId of this editor model if it is dirty.
*/
public save(options: ISaveOptions = Object.create(null)): TPromise<void> {
save(options: ISaveOptions = Object.create(null)): TPromise<void> {
if (!this.isResolved()) {
return TPromise.wrap<void>(null);
}
diag('save() - enter', this.resource, new Date());
this.logService.trace('save() - enter', this.resource);
// Cancel any currently running auto saves to make this the one that succeeds
this.cancelAutoSavePromise();
this.cancelPendingAutoSave();
return this.doSave(this.versionId, options);
}
private doSave(versionId: number, options: ISaveOptions): TPromise<void> {
if (types.isUndefinedOrNull(options.reason)) {
if (isUndefinedOrNull(options.reason)) {
options.reason = SaveReason.EXPLICIT;
}
diag(`doSave(${versionId}) - enter with versionId ' + versionId`, this.resource, new Date());
this.logService.trace(`doSave(${versionId}) - enter with versionId ' + versionId`, this.resource);
// Lookup any running pending save for this versionId and return it if found
//
@@ -631,7 +610,7 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
// while the save was not yet finished to disk
//
if (this.saveSequentializer.hasPendingSave(versionId)) {
diag(`doSave(${versionId}) - exit - found a pending save for versionId ${versionId}`, this.resource, new Date());
this.logService.trace(`doSave(${versionId}) - exit - found a pending save for versionId ${versionId}`, this.resource);
return this.saveSequentializer.pendingSave;
}
@@ -644,7 +623,7 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
// Thus we avoid spawning multiple auto saves and only take the latest.
//
if ((!options.force && !this.dirty) || versionId !== this.versionId) {
diag(`doSave(${versionId}) - exit - because not dirty and/or versionId is different (this.isDirty: ${this.dirty}, this.versionId: ${this.versionId})`, this.resource, new Date());
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 TPromise.wrap<void>(null);
}
@@ -658,7 +637,7 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
// while the first save has not returned yet.
//
if (this.saveSequentializer.hasPendingSave()) {
diag(`doSave(${versionId}) - exit - because busy saving`, this.resource, new Date());
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));
@@ -692,6 +671,16 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
// 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 void 0;
}
// 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:
@@ -714,7 +703,7 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
// Save to Disk
// mark the save operation as currently pending with the versionId (it might have changed from a save participant triggering)
diag(`doSave(${versionId}) - before updateContent()`, this.resource, new Date());
this.logService.trace(`doSave(${versionId}) - before updateContent()`, this.resource);
return this.saveSequentializer.setPending(newVersionId, this.fileService.updateContent(this.lastResolvedDiskStat.resource, this.createSnapshot(), {
overwriteReadonly: options.overwriteReadonly,
overwriteEncoding: options.overwriteEncoding,
@@ -723,30 +712,34 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
etag: this.lastResolvedDiskStat.etag,
writeElevated: options.writeElevated
}).then(stat => {
diag(`doSave(${versionId}) - after updateContent()`, this.resource, new Date());
this.logService.trace(`doSave(${versionId}) - after updateContent()`, this.resource);
// Telemetry
if (this.isSettingsFile()) {
const settingsType = this.getTypeIfSettings();
if (settingsType) {
/* __GDPR__
"settingsWritten" : {}
"settingsWritten" : {
"settingsType": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
}
*/
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
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 {
/* __GDPR__
"filePUT" : {
"mimeType" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"ext": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
"${include}": [
"${FileTelemetryData}"
]
}
*/
this.telemetryService.publicLog('filePUT', { mimeType: guessMimeTypes(this.resource.fsPath).join(', '), ext: path.extname(this.lastResolvedDiskStat.resource.fsPath) });
this.telemetryService.publicLog('filePUT', this.getTelemetryData(options.reason));
}
// 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.logService.trace(`doSave(${versionId}) - setting dirty to false because versionId did not change`, this.resource);
this.setDirty(false);
} else {
diag(`doSave(${versionId}) - not setting dirty to false because versionId did change meanwhile`, this.resource, new Date());
this.logService.trace(`doSave(${versionId}) - not setting dirty to false because versionId did change meanwhile`, this.resource);
}
// Updated resolved stat with updated stat
@@ -758,7 +751,11 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
// Emit File Saved Event
this._onDidStateChange.fire(StateChange.SAVED);
}, error => {
diag(`doSave(${versionId}) - exit - resulted in a save error: ${error.toString()}`, this.resource, new Date());
if (!error) {
error = new Error('Unknown Save Error'); // TODO@remote we should never get null as error (https://github.com/Microsoft/vscode/issues/55051)
}
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;
@@ -777,18 +774,71 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
}));
}
private isSettingsFile(): boolean {
private getTypeIfSettings(): string {
if (path.extname(this.resource.fsPath) !== '.json') {
return '';
}
// Check for global settings file
if (this.resource.fsPath === this.environmentService.appSettingsPath) {
return true;
if (isEqual(this.resource, URI.file(this.environmentService.appSettingsPath), !isLinux)) {
return 'global-settings';
}
// Check for keybindings file
if (isEqual(this.resource, URI.file(this.environmentService.appKeybindingsPath), !isLinux)) {
return 'keybindings';
}
// Check for locale file
if (isEqual(this.resource, URI.file(path.join(this.environmentService.appSettingsHome, 'locale.json')), !isLinux)) {
return 'locale';
}
// Check for snippets
if (isEqualOrParent(this.resource, URI.file(path.join(this.environmentService.appSettingsHome, 'snippets')), hasToIgnoreCase(this.resource))) {
return 'snippets';
}
// Check for workspace settings file
return this.contextService.getWorkspace().folders.some(folder => {
const folders = this.contextService.getWorkspace().folders;
for (let i = 0; i < folders.length; i++) {
// {{SQL CARBON EDIT}}
return path.isEqualOrParent(this.resource.fsPath, path.join(folder.uri.fsPath, '.sqlops'));
});
if (isEqualOrParent(this.resource, folders[i].toResource('.sqlops'), hasToIgnoreCase(this.resource))) {
const filename = path.basename(this.resource.fsPath);
if (TextFileEditorModel.WHITELIST_WORKSPACE_JSON.indexOf(filename) > -1) {
// {{SQL CARBON EDIT}}
return `.sqlops/${filename}`;
}
}
}
return '';
}
private getTelemetryData(reason: number): Object {
const ext = path.extname(this.resource.fsPath);
const fileName = path.basename(this.resource.fsPath);
const telemetryData = {
mimeType: guessMimeTypes(this.resource.fsPath).join(', '),
ext,
path: this.hashService.createSHA1(this.resource.fsPath),
reason
};
if (ext === '.json' && TextFileEditorModel.WHITELIST_JSON.indexOf(fileName) > -1) {
telemetryData['whitelistedjson'] = fileName;
}
/* __GDPR__FRAGMENT__
"FileTelemetryData" : {
"mimeType" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"ext": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"path": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"reason": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"whitelistedjson": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
return telemetryData;
}
private doTouch(versionId: number): TPromise<void> {
@@ -864,31 +914,19 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
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 {
isDirty(): boolean {
return this.dirty;
}
/**
* Returns the time in millies when this working copy was attempted to be saved.
*/
public getLastSaveAttemptTime(): number {
getLastSaveAttemptTime(): number {
return this.lastSaveAttemptTime;
}
/**
* Returns the time in millies when this working copy was last modified by the user or some other program.
*/
public getETag(): string {
getETag(): string {
return this.lastResolvedDiskStat ? this.lastResolvedDiskStat.etag : null;
}
/**
* Answers if this model is in a specific state.
*/
public hasState(state: ModelState): boolean {
hasState(state: ModelState): boolean {
switch (state) {
case ModelState.CONFLICT:
return this.inConflictMode;
@@ -905,11 +943,11 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
}
}
public getEncoding(): string {
getEncoding(): string {
return this.preferredEncoding || this.contentEncoding;
}
public setEncoding(encoding: string, mode: EncodingMode): void {
setEncoding(encoding: string, mode: EncodingMode): void {
if (!this.isNewEncoding(encoding)) {
return; // return early if the encoding is already the same
}
@@ -946,7 +984,7 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
}
}
public updatePreferredEncoding(encoding: string): void {
updatePreferredEncoding(encoding: string): void {
if (!this.isNewEncoding(encoding)) {
return;
}
@@ -969,41 +1007,35 @@ export class TextFileEditorModel extends BaseTextEditorModel implements ITextFil
return true;
}
public isResolved(): boolean {
return !types.isUndefinedOrNull(this.lastResolvedDiskStat);
isResolved(): boolean {
return !isUndefinedOrNull(this.lastResolvedDiskStat);
}
/**
* Returns true if the dispose() method of this model has been called.
*/
public isDisposed(): boolean {
isReadonly(): boolean {
return this.lastResolvedDiskStat && this.lastResolvedDiskStat.isReadonly;
}
isDisposed(): boolean {
return this.disposed;
}
/**
* Returns the full resource URI of the file this text file editor model is about.
*/
public getResource(): URI {
getResource(): URI {
return this.resource;
}
/**
* Stat accessor only used by tests.
*/
public getStat(): IFileStat {
getStat(): IFileStat {
return this.lastResolvedDiskStat;
}
public dispose(): void {
dispose(): void {
this.disposed = true;
this.inConflictMode = false;
this.inOrphanMode = false;
this.inErrorMode = false;
this.toDispose = dispose(this.toDispose);
this.createTextEditorModelPromise = null;
this.cancelAutoSavePromise();
this.cancelPendingAutoSave();
super.dispose();
}
@@ -1025,7 +1057,7 @@ export class SaveSequentializer {
private _pendingSave: IPendingSave;
private _nextSave: ISaveOperation;
public hasPendingSave(versionId?: number): boolean {
hasPendingSave(versionId?: number): boolean {
if (!this._pendingSave) {
return false;
}
@@ -1037,11 +1069,11 @@ export class SaveSequentializer {
return !!this._pendingSave;
}
public get pendingSave(): TPromise<void> {
get pendingSave(): TPromise<void> {
return this._pendingSave ? this._pendingSave.promise : void 0;
}
public setPending(versionId: number, promise: TPromise<void>): TPromise<void> {
setPending(versionId: number, promise: TPromise<void>): TPromise<void> {
this._pendingSave = { versionId, promise };
promise.done(() => this.donePending(versionId), () => this.donePending(versionId));
@@ -1070,7 +1102,7 @@ export class SaveSequentializer {
}
}
public setNext(run: () => TPromise<void>): TPromise<void> {
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
@@ -1104,15 +1136,7 @@ class DefaultSaveErrorHandler implements ISaveErrorHandler {
constructor(@INotificationService private notificationService: INotificationService) { }
public onSaveError(error: any, model: TextFileEditorModel): void {
onSaveError(error: any, model: TextFileEditorModel): void {
this.notificationService.error(nls.localize('genericSaveError', "Failed to save '{0}': {1}", path.basename(model.getResource().fsPath), toErrorMessage(error, false)));
}
}
// 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() + '])');
});
}

View File

@@ -8,23 +8,38 @@ import { Event, Emitter, debounceEvent } from 'vs/base/common/event';
import { TPromise } from 'vs/base/common/winjs.base';
import URI from 'vs/base/common/uri';
import { TextFileEditorModel } from 'vs/workbench/services/textfile/common/textFileEditorModel';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { ITextFileEditorModel, ITextFileEditorModelManager, TextFileModelChangeEvent, StateChange, IModelLoadOrCreateOptions, ILoadOptions } from 'vs/workbench/services/textfile/common/textfiles';
import { dispose, IDisposable, Disposable } from 'vs/base/common/lifecycle';
import { ITextFileEditorModel, ITextFileEditorModelManager, TextFileModelChangeEvent, StateChange, IModelLoadOrCreateOptions } from 'vs/workbench/services/textfile/common/textfiles';
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ResourceMap } from 'vs/base/common/map';
import { onUnexpectedError } from 'vs/base/common/errors';
export class TextFileEditorModelManager implements ITextFileEditorModelManager {
private toUnbind: IDisposable[];
export class TextFileEditorModelManager extends Disposable implements ITextFileEditorModelManager {
private readonly _onModelDisposed: Emitter<URI>;
private readonly _onModelContentChanged: Emitter<TextFileModelChangeEvent>;
private readonly _onModelDirty: Emitter<TextFileModelChangeEvent>;
private readonly _onModelSaveError: Emitter<TextFileModelChangeEvent>;
private readonly _onModelSaved: Emitter<TextFileModelChangeEvent>;
private readonly _onModelReverted: Emitter<TextFileModelChangeEvent>;
private readonly _onModelEncodingChanged: Emitter<TextFileModelChangeEvent>;
private readonly _onModelOrphanedChanged: Emitter<TextFileModelChangeEvent>;
private readonly _onModelDisposed: Emitter<URI> = this._register(new Emitter<URI>());
get onModelDisposed(): Event<URI> { return this._onModelDisposed.event; }
private readonly _onModelContentChanged: Emitter<TextFileModelChangeEvent> = this._register(new Emitter<TextFileModelChangeEvent>());
get onModelContentChanged(): Event<TextFileModelChangeEvent> { return this._onModelContentChanged.event; }
private readonly _onModelDirty: Emitter<TextFileModelChangeEvent> = this._register(new Emitter<TextFileModelChangeEvent>());
get onModelDirty(): Event<TextFileModelChangeEvent> { return this._onModelDirty.event; }
private readonly _onModelSaveError: Emitter<TextFileModelChangeEvent> = this._register(new Emitter<TextFileModelChangeEvent>());
get onModelSaveError(): Event<TextFileModelChangeEvent> { return this._onModelSaveError.event; }
private readonly _onModelSaved: Emitter<TextFileModelChangeEvent> = this._register(new Emitter<TextFileModelChangeEvent>());
get onModelSaved(): Event<TextFileModelChangeEvent> { return this._onModelSaved.event; }
private readonly _onModelReverted: Emitter<TextFileModelChangeEvent> = this._register(new Emitter<TextFileModelChangeEvent>());
get onModelReverted(): Event<TextFileModelChangeEvent> { return this._onModelReverted.event; }
private readonly _onModelEncodingChanged: Emitter<TextFileModelChangeEvent> = this._register(new Emitter<TextFileModelChangeEvent>());
get onModelEncodingChanged(): Event<TextFileModelChangeEvent> { return this._onModelEncodingChanged.event; }
private readonly _onModelOrphanedChanged: Emitter<TextFileModelChangeEvent> = this._register(new Emitter<TextFileModelChangeEvent>());
get onModelOrphanedChanged(): Event<TextFileModelChangeEvent> { return this._onModelOrphanedChanged.event; }
private _onModelsDirtyEvent: Event<TextFileModelChangeEvent[]>;
private _onModelsSaveError: Event<TextFileModelChangeEvent[]>;
@@ -41,25 +56,7 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager {
@ILifecycleService private lifecycleService: ILifecycleService,
@IInstantiationService private instantiationService: IInstantiationService
) {
this.toUnbind = [];
this._onModelDisposed = new Emitter<URI>();
this._onModelContentChanged = new Emitter<TextFileModelChangeEvent>();
this._onModelDirty = new Emitter<TextFileModelChangeEvent>();
this._onModelSaveError = new Emitter<TextFileModelChangeEvent>();
this._onModelSaved = new Emitter<TextFileModelChangeEvent>();
this._onModelReverted = new Emitter<TextFileModelChangeEvent>();
this._onModelEncodingChanged = new Emitter<TextFileModelChangeEvent>();
this._onModelOrphanedChanged = new Emitter<TextFileModelChangeEvent>();
this.toUnbind.push(this._onModelDisposed);
this.toUnbind.push(this._onModelContentChanged);
this.toUnbind.push(this._onModelDirty);
this.toUnbind.push(this._onModelSaveError);
this.toUnbind.push(this._onModelSaved);
this.toUnbind.push(this._onModelReverted);
this.toUnbind.push(this._onModelEncodingChanged);
this.toUnbind.push(this._onModelOrphanedChanged);
super();
this.mapResourceToModel = new ResourceMap<ITextFileEditorModel>();
this.mapResourceToDisposeListener = new ResourceMap<IDisposable>();
@@ -76,39 +73,7 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager {
this.lifecycleService.onShutdown(this.dispose, this);
}
public get onModelDisposed(): Event<URI> {
return this._onModelDisposed.event;
}
public get onModelContentChanged(): Event<TextFileModelChangeEvent> {
return this._onModelContentChanged.event;
}
public get onModelDirty(): Event<TextFileModelChangeEvent> {
return this._onModelDirty.event;
}
public get onModelSaveError(): Event<TextFileModelChangeEvent> {
return this._onModelSaveError.event;
}
public get onModelSaved(): Event<TextFileModelChangeEvent> {
return this._onModelSaved.event;
}
public get onModelReverted(): Event<TextFileModelChangeEvent> {
return this._onModelReverted.event;
}
public get onModelEncodingChanged(): Event<TextFileModelChangeEvent> {
return this._onModelEncodingChanged.event;
}
public get onModelOrphanedChanged(): Event<TextFileModelChangeEvent> {
return this._onModelOrphanedChanged.event;
}
public get onModelsDirty(): Event<TextFileModelChangeEvent[]> {
get onModelsDirty(): Event<TextFileModelChangeEvent[]> {
if (!this._onModelsDirtyEvent) {
this._onModelsDirtyEvent = this.debounce(this.onModelDirty);
}
@@ -116,7 +81,7 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager {
return this._onModelsDirtyEvent;
}
public get onModelsSaveError(): Event<TextFileModelChangeEvent[]> {
get onModelsSaveError(): Event<TextFileModelChangeEvent[]> {
if (!this._onModelsSaveError) {
this._onModelsSaveError = this.debounce(this.onModelSaveError);
}
@@ -124,7 +89,7 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager {
return this._onModelsSaveError;
}
public get onModelsSaved(): Event<TextFileModelChangeEvent[]> {
get onModelsSaved(): Event<TextFileModelChangeEvent[]> {
if (!this._onModelsSaved) {
this._onModelsSaved = this.debounce(this.onModelSaved);
}
@@ -132,7 +97,7 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager {
return this._onModelsSaved;
}
public get onModelsReverted(): Event<TextFileModelChangeEvent[]> {
get onModelsReverted(): Event<TextFileModelChangeEvent[]> {
if (!this._onModelsReverted) {
this._onModelsReverted = this.debounce(this.onModelReverted);
}
@@ -155,11 +120,11 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager {
return 250;
}
public get(resource: URI): ITextFileEditorModel {
get(resource: URI): ITextFileEditorModel {
return this.mapResourceToModel.get(resource);
}
public loadOrCreate(resource: URI, options?: IModelLoadOrCreateOptions): TPromise<ITextFileEditorModel> {
loadOrCreate(resource: URI, options?: IModelLoadOrCreateOptions): TPromise<ITextFileEditorModel> {
// Return early if model is currently being loaded
const pendingLoad = this.mapResourceToPendingModelLoaders.get(resource);
@@ -167,18 +132,23 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager {
return pendingLoad;
}
let modelLoadOptions: ILoadOptions;
if (options && options.allowBinary) {
modelLoadOptions = { allowBinary: true };
}
let modelPromise: TPromise<ITextFileEditorModel>;
// Model exists
let model = this.get(resource);
if (model) {
if (options && options.reload) {
modelPromise = model.load(modelLoadOptions);
// async reload: trigger a reload but return immediately
if (options.reload.async) {
modelPromise = TPromise.as(model);
model.load(options).then(null, onUnexpectedError);
}
// sync reload: do not return until model reloaded
else {
modelPromise = model.load(options);
}
} else {
modelPromise = TPromise.as(model);
}
@@ -187,7 +157,7 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager {
// Model does not exist
else {
model = this.instantiationService.createInstance(TextFileEditorModel, resource, options ? options.encoding : void 0);
modelPromise = model.load(modelLoadOptions);
modelPromise = model.load(options);
// Install state change listener
this.mapResourceToStateChangeListener.set(resource, model.onDidStateChange(state => {
@@ -249,7 +219,7 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager {
});
}
public getAll(resource?: URI, filter?: (model: ITextFileEditorModel) => boolean): ITextFileEditorModel[] {
getAll(resource?: URI, filter?: (model: ITextFileEditorModel) => boolean): ITextFileEditorModel[] {
if (resource) {
const res = this.mapResourceToModel.get(resource);
@@ -266,7 +236,7 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager {
return res;
}
public add(resource: URI, model: ITextFileEditorModel): void {
add(resource: URI, model: ITextFileEditorModel): void {
const knownModel = this.mapResourceToModel.get(resource);
if (knownModel === model) {
return; // already cached
@@ -286,7 +256,7 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager {
}));
}
public remove(resource: URI): void {
remove(resource: URI): void {
this.mapResourceToModel.delete(resource);
const disposeListener = this.mapResourceToDisposeListener.get(resource);
@@ -308,7 +278,7 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager {
}
}
public clear(): void {
clear(): void {
// model caches
this.mapResourceToModel.clear();
@@ -327,7 +297,7 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager {
this.mapResourceToModelContentChangeListener.clear();
}
public disposeModel(model: TextFileEditorModel): void {
disposeModel(model: TextFileEditorModel): void {
if (!model) {
return; // we need data!
}
@@ -346,8 +316,4 @@ export class TextFileEditorModelManager implements ITextFileEditorModelManager {
model.dispose();
}
public dispose(): void {
this.toUnbind = dispose(this.toUnbind);
}
}

View File

@@ -14,13 +14,13 @@ import { Event, Emitter } from 'vs/base/common/event';
import * as platform from 'vs/base/common/platform';
import { IWindowsService } from 'vs/platform/windows/common/windows';
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
import { IResult, ITextFileOperationResult, ITextFileService, IRawTextContent, IAutoSaveConfiguration, AutoSaveMode, SaveReason, ITextFileEditorModelManager, ITextFileEditorModel, ModelState, ISaveOptions, AutoSaveContext } from 'vs/workbench/services/textfile/common/textfiles';
import { ConfirmResult } from 'vs/workbench/common/editor';
import { IResult, ITextFileOperationResult, ITextFileService, IRawTextContent, IAutoSaveConfiguration, AutoSaveMode, SaveReason, ITextFileEditorModelManager, ITextFileEditorModel, ModelState, ISaveOptions, AutoSaveContext, IWillMoveEvent } from 'vs/workbench/services/textfile/common/textfiles';
import { ConfirmResult, IRevertOptions } from 'vs/workbench/common/editor';
import { ILifecycleService, ShutdownReason } from 'vs/platform/lifecycle/common/lifecycle';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { IFileService, IResolveContentOptions, IFilesConfiguration, FileOperationError, FileOperationResult, AutoSaveConfiguration, HotExitConfiguration } from 'vs/platform/files/common/files';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { Disposable } from 'vs/base/common/lifecycle';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { UntitledEditorModel } from 'vs/workbench/common/editor/untitledEditorModel';
@@ -29,11 +29,11 @@ import { IInstantiationService } from 'vs/platform/instantiation/common/instanti
import { ResourceMap } from 'vs/base/common/map';
import { Schemas } from 'vs/base/common/network';
import { IHistoryService } from 'vs/workbench/services/history/common/history';
import { IRevertOptions } from 'vs/platform/editor/common/editor';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { createTextBufferFactoryFromSnapshot } from 'vs/editor/common/model/textModel';
import { IModelService } from 'vs/editor/common/services/modelService';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { isEqualOrParent, isEqual } from 'vs/base/common/resources';
export interface IBackupResult {
didBackup: boolean;
@@ -44,24 +44,26 @@ export interface IBackupResult {
*
* It also adds diagnostics and logging around file system operations.
*/
export abstract class TextFileService implements ITextFileService {
export abstract class TextFileService extends Disposable implements ITextFileService {
public _serviceBrand: any;
_serviceBrand: any;
private readonly _onFilesAssociationChange: Emitter<void> = this._register(new Emitter<void>());
get onAutoSaveConfigurationChange(): Event<IAutoSaveConfiguration> { return this._onAutoSaveConfigurationChange.event; }
private readonly _onAutoSaveConfigurationChange: Emitter<IAutoSaveConfiguration> = this._register(new Emitter<IAutoSaveConfiguration>());
get onFilesAssociationChange(): Event<void> { return this._onFilesAssociationChange.event; }
private readonly _onWillMove = this._register(new Emitter<IWillMoveEvent>());
get onWillMove(): Event<IWillMoveEvent> { return this._onWillMove.event; }
private toUnbind: IDisposable[];
private _models: TextFileEditorModelManager;
private readonly _onFilesAssociationChange: Emitter<void>;
private currentFilesAssociationConfig: { [key: string]: string; };
private readonly _onAutoSaveConfigurationChange: Emitter<IAutoSaveConfiguration>;
private configuredAutoSaveDelay: number;
private configuredAutoSaveOnFocusChange: boolean;
private configuredAutoSaveOnWindowChange: boolean;
private autoSaveContext: IContextKey<string>;
private configuredHotExit: string;
private autoSaveContext: IContextKey<string>;
constructor(
private lifecycleService: ILifecycleService,
@@ -78,13 +80,7 @@ export abstract class TextFileService implements ITextFileService {
contextKeyService: IContextKeyService,
private modelService: IModelService
) {
this.toUnbind = [];
this._onAutoSaveConfigurationChange = new Emitter<IAutoSaveConfiguration>();
this.toUnbind.push(this._onAutoSaveConfigurationChange);
this._onFilesAssociationChange = new Emitter<void>();
this.toUnbind.push(this._onFilesAssociationChange);
super();
this._models = this.instantiationService.createInstance(TextFileEditorModelManager);
this.autoSaveContext = AutoSaveContext.bindTo(contextKeyService);
@@ -97,7 +93,7 @@ export abstract class TextFileService implements ITextFileService {
this.registerListeners();
}
public get models(): ITextFileEditorModelManager {
get models(): ITextFileEditorModelManager {
return this._models;
}
@@ -107,14 +103,6 @@ export abstract class TextFileService implements ITextFileService {
abstract confirmSave(resources?: URI[]): TPromise<ConfirmResult>;
public get onAutoSaveConfigurationChange(): Event<IAutoSaveConfiguration> {
return this._onAutoSaveConfigurationChange.event;
}
public get onFilesAssociationChange(): Event<void> {
return this._onFilesAssociationChange.event;
}
private registerListeners(): void {
// Lifecycle
@@ -122,7 +110,7 @@ export abstract class TextFileService implements ITextFileService {
this.lifecycleService.onShutdown(this.dispose, this);
// Files configuration changes
this.toUnbind.push(this.configurationService.onDidChangeConfiguration(e => {
this._register(this.configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('files')) {
this.onFilesConfigurationChange(this.configurationService.getValue<IFilesConfiguration>());
}
@@ -365,7 +353,7 @@ export abstract class TextFileService implements ITextFileService {
}
}
public getDirty(resources?: URI[]): URI[] {
getDirty(resources?: URI[]): URI[] {
// Collect files
const dirty = this.getDirtyFileModels(resources).map(m => m.getResource());
@@ -376,7 +364,7 @@ export abstract class TextFileService implements ITextFileService {
return dirty;
}
public isDirty(resource?: URI): boolean {
isDirty(resource?: URI): boolean {
// Check for dirty file
if (this._models.getAll(resource).some(model => model.isDirty())) {
@@ -387,7 +375,7 @@ export abstract class TextFileService implements ITextFileService {
return this.untitledEditorService.getDirty().some(dirty => !resource || dirty.toString() === resource.toString());
}
public save(resource: URI, options?: ISaveOptions): TPromise<boolean> {
save(resource: URI, options?: ISaveOptions): TPromise<boolean> {
// Run a forced save if we detect the file is not dirty so that save participants can still run
if (options && options.force && this.fileService.canHandleResource(resource) && !this.isDirty(resource)) {
@@ -400,9 +388,9 @@ export abstract class TextFileService implements ITextFileService {
return this.saveAll([resource], options).then(result => result.results.length === 1 && result.results[0].success);
}
public saveAll(includeUntitled?: boolean, options?: ISaveOptions): TPromise<ITextFileOperationResult>;
public saveAll(resources: URI[], options?: ISaveOptions): TPromise<ITextFileOperationResult>;
public saveAll(arg1?: any, options?: ISaveOptions): TPromise<ITextFileOperationResult> {
saveAll(includeUntitled?: boolean, options?: ISaveOptions): TPromise<ITextFileOperationResult>;
saveAll(resources: URI[], options?: ISaveOptions): TPromise<ITextFileOperationResult>;
saveAll(arg1?: any, options?: ISaveOptions): TPromise<ITextFileOperationResult> {
// get all dirty
let toSave: URI[] = [];
@@ -436,16 +424,16 @@ export abstract class TextFileService implements ITextFileService {
for (let i = 0; i < untitledResources.length; i++) {
const untitled = untitledResources[i];
if (this.untitledEditorService.exists(untitled)) {
let targetPath: string;
let targetUri: URI;
// Untitled with associated file path don't need to prompt
if (this.untitledEditorService.hasAssociatedFilePath(untitled)) {
targetPath = untitled.fsPath;
targetUri = untitled.with({ scheme: Schemas.file });
}
// Otherwise ask user
else {
targetPath = await this.promptForPath(this.suggestFileName(untitled));
const targetPath = await this.promptForPath(this.suggestFileName(untitled));
if (!targetPath) {
return TPromise.as({
results: [...fileResources, ...untitledResources].map(r => {
@@ -455,9 +443,11 @@ export abstract class TextFileService implements ITextFileService {
})
});
}
targetUri = URI.file(targetPath);
}
targetsForUntitled.push(URI.file(targetPath));
targetsForUntitled.push(targetUri);
}
}
@@ -532,7 +522,7 @@ export abstract class TextFileService implements ITextFileService {
return this.getFileModels(arg1).filter(model => model.isDirty());
}
public saveAs(resource: URI, target?: URI, options?: ISaveOptions): TPromise<URI> {
saveAs(resource: URI, target?: URI, options?: ISaveOptions): TPromise<URI> {
// Get to target resource
let targetPromise: TPromise<URI>;
@@ -649,11 +639,11 @@ export abstract class TextFileService implements ITextFileService {
return untitledFileName;
}
public revert(resource: URI, options?: IRevertOptions): TPromise<boolean> {
revert(resource: URI, options?: IRevertOptions): TPromise<boolean> {
return this.revertAll([resource], options).then(result => result.results.length === 1 && result.results[0].success);
}
public revertAll(resources?: URI[], options?: IRevertOptions): TPromise<ITextFileOperationResult> {
revertAll(resources?: URI[], options?: IRevertOptions): TPromise<ITextFileOperationResult> {
// Revert files first
return this.doRevertAllFiles(resources, options).then(operation => {
@@ -702,7 +692,107 @@ export abstract class TextFileService implements ITextFileService {
});
}
public getAutoSaveMode(): AutoSaveMode {
create(resource: URI, contents?: string, options?: { overwrite?: boolean }): TPromise<void> {
const existingModel = this.models.get(resource);
return this.fileService.createFile(resource, contents, options).then(() => {
// If we had an existing model for the given resource, load
// it again to make sure it is up to date with the contents
// we just wrote into the underlying resource by calling
// revert()
if (existingModel && !existingModel.isDisposed()) {
return existingModel.revert();
}
return void 0;
});
}
delete(resource: URI, options?: { useTrash?: boolean, recursive?: boolean }): TPromise<void> {
const dirtyFiles = this.getDirty().filter(dirty => isEqualOrParent(dirty, resource, !platform.isLinux /* ignorecase */));
return this.revertAll(dirtyFiles, { soft: true }).then(() => this.fileService.del(resource, options));
}
move(source: URI, target: URI, overwrite?: boolean): TPromise<void> {
const waitForPromises: TPromise[] = [];
this._onWillMove.fire({
oldResource: source,
newResource: target,
waitUntil(p: TPromise<any>) {
waitForPromises.push(TPromise.wrap(p).then(undefined, errors.onUnexpectedError));
}
});
// prevent async waitUntil-calls
Object.freeze(waitForPromises);
return TPromise.join(waitForPromises).then(() => {
// Handle target models if existing (if target URI is a folder, this can be multiple)
let handleTargetModelPromise: TPromise<any> = TPromise.as(void 0);
const dirtyTargetModels = this.getDirtyFileModels().filter(model => isEqualOrParent(model.getResource(), target, !platform.isLinux /* ignorecase */));
if (dirtyTargetModels.length) {
handleTargetModelPromise = this.revertAll(dirtyTargetModels.map(targetModel => targetModel.getResource()), { soft: true });
}
return handleTargetModelPromise.then(() => {
// Handle dirty source models if existing (if source URI is a folder, this can be multiple)
let handleDirtySourceModels: TPromise<any>;
const dirtySourceModels = this.getDirtyFileModels().filter(model => isEqualOrParent(model.getResource(), source, !platform.isLinux /* ignorecase */));
const dirtyTargetModels: URI[] = [];
if (dirtySourceModels.length) {
handleDirtySourceModels = TPromise.join(dirtySourceModels.map(sourceModel => {
const sourceModelResource = sourceModel.getResource();
let targetModelResource: URI;
// If the source is the actual model, just use target as new resource
if (isEqual(sourceModelResource, source, !platform.isLinux /* ignorecase */)) {
targetModelResource = target;
}
// Otherwise a parent folder of the source is being moved, so we need
// to compute the target resource based on that
else {
targetModelResource = sourceModelResource.with({ path: paths.join(target.path, sourceModelResource.path.substr(source.path.length + 1)) });
}
// Remember as dirty target model to load after the operation
dirtyTargetModels.push(targetModelResource);
// Backup dirty source model to the target resource it will become later
return this.backupFileService.backupResource(targetModelResource, sourceModel.createSnapshot(), sourceModel.getVersionId());
}));
} else {
handleDirtySourceModels = TPromise.as(void 0);
}
return handleDirtySourceModels.then(() => {
// Soft revert the dirty source files if any
return this.revertAll(dirtySourceModels.map(dirtySourceModel => dirtySourceModel.getResource()), { soft: true }).then(() => {
// Rename to target
return this.fileService.moveFile(source, target, overwrite).then(() => {
// Load models that were dirty before
return TPromise.join(dirtyTargetModels.map(dirtyTargetModel => this.models.loadOrCreate(dirtyTargetModel))).then(() => void 0);
}, error => {
// In case of an error, discard any dirty target backups that were made
return TPromise.join(dirtyTargetModels.map(dirtyTargetModel => this.backupFileService.discardResourceBackup(dirtyTargetModel)))
.then(() => TPromise.wrapError(error));
});
});
});
});
});
}
getAutoSaveMode(): AutoSaveMode {
if (this.configuredAutoSaveOnFocusChange) {
return AutoSaveMode.ON_FOCUS_CHANGE;
}
@@ -718,7 +808,7 @@ export abstract class TextFileService implements ITextFileService {
return AutoSaveMode.OFF;
}
public getAutoSaveConfiguration(): IAutoSaveConfiguration {
getAutoSaveConfiguration(): IAutoSaveConfiguration {
return {
autoSaveDelay: this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0 ? this.configuredAutoSaveDelay : void 0,
autoSaveFocusChange: this.configuredAutoSaveOnFocusChange,
@@ -726,14 +816,15 @@ export abstract class TextFileService implements ITextFileService {
};
}
public get isHotExitEnabled(): boolean {
get isHotExitEnabled(): boolean {
return !this.environmentService.isExtensionDevelopment && this.configuredHotExit !== HotExitConfiguration.OFF;
}
public dispose(): void {
this.toUnbind = dispose(this.toUnbind);
dispose(): void {
// Clear all caches
this._models.clear();
super.dispose();
}
}

View File

@@ -8,12 +8,11 @@ import { TPromise } from 'vs/base/common/winjs.base';
import URI from 'vs/base/common/uri';
import { Event } from 'vs/base/common/event';
import { IDisposable } from 'vs/base/common/lifecycle';
import { IEncodingSupport, ConfirmResult } from 'vs/workbench/common/editor';
import { IEncodingSupport, ConfirmResult, IRevertOptions } from 'vs/workbench/common/editor';
import { IBaseStat, IResolveContentOptions, ITextSnapshot } from 'vs/platform/files/common/files';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ITextEditorModel } from 'vs/editor/common/services/resolverService';
import { ITextBufferFactory } from 'vs/editor/common/model';
import { IRevertOptions } from 'vs/platform/editor/common/editor';
import { RawContextKey } from 'vs/platform/contextkey/common/contextkey';
/**
@@ -81,11 +80,11 @@ export class TextFileModelChangeEvent {
this._kind = kind;
}
public get resource(): URI {
get resource(): URI {
return this._resource;
}
public get kind(): StateChange {
get kind(): StateChange {
return this._kind;
}
}
@@ -124,6 +123,12 @@ export enum SaveReason {
WINDOW_CHANGE = 4
}
export enum LoadReason {
EDITOR = 1,
REFERENCE = 2,
OTHER = 3
}
export const ITextFileService = createDecorator<ITextFileService>(TEXT_FILE_SERVICE_ID);
export interface IRawTextContent extends IBaseStat {
@@ -141,6 +146,10 @@ export interface IRawTextContent extends IBaseStat {
export interface IModelLoadOrCreateOptions {
/**
* Context why the model is being loaded or created.
*/
reason?: LoadReason;
/**
* The encoding to use when resolving the model text content.
@@ -148,9 +157,16 @@ export interface IModelLoadOrCreateOptions {
encoding?: string;
/**
* Wether to reload the model if it already exists.
* If the model was already loaded before, allows to trigger
* a reload of it to fetch the latest contents:
* - async: loadOrCreate() will return immediately and trigger
* a reload that will run in the background.
* - sync: loadOrCreate() will only return resolved when the
* model has finished reloading.
*/
reload?: boolean;
reload?: {
async: boolean
};
/**
* Allow to load a model even if we think it is a binary file.
@@ -204,6 +220,11 @@ export interface ILoadOptions {
* Allow to load a model even if we think it is a binary file.
*/
allowBinary?: boolean;
/**
* Context why the model is being loaded.
*/
reason?: LoadReason;
}
export interface ITextFileEditorModel extends ITextEditorModel, IEncodingSupport {
@@ -233,18 +254,32 @@ export interface ITextFileEditorModel extends ITextEditorModel, IEncodingSupport
isResolved(): boolean;
isReadonly(): boolean;
isDisposed(): boolean;
}
export interface IWillMoveEvent {
oldResource: URI;
newResource: URI;
waitUntil(p: TPromise<any>): void;
}
export interface ITextFileService extends IDisposable {
_serviceBrand: any;
onAutoSaveConfigurationChange: Event<IAutoSaveConfiguration>;
onFilesAssociationChange: Event<void>;
readonly onAutoSaveConfigurationChange: Event<IAutoSaveConfiguration>;
readonly onFilesAssociationChange: Event<void>;
onWillMove: Event<IWillMoveEvent>;
readonly isHotExitEnabled: boolean;
/**
* Access to the manager of text file editor models providing further methods to work with them.
*/
models: ITextFileEditorModelManager;
readonly models: ITextFileEditorModelManager;
/**
* Resolve the contents of a file identified by the resource.
@@ -308,6 +343,22 @@ export interface ITextFileService extends IDisposable {
*/
revertAll(resources?: URI[], options?: IRevertOptions): TPromise<ITextFileOperationResult>;
/**
* Create a file. If the file exists it will be overwritten with the contents if
* the options enable to overwrite.
*/
create(resource: URI, contents?: string, options?: { overwrite?: boolean }): TPromise<void>;
/**
* Delete a file. If the file is dirty, it will get reverted and then deleted from disk.
*/
delete(resource: URI, options?: { useTrash?: boolean, recursive?: boolean }): TPromise<void>;
/**
* Move a file. If the file is dirty, its contents will be preserved and restored.
*/
move(source: URI, target: URI, overwrite?: boolean): TPromise<void>;
/**
* Brings up the confirm dialog to either save, don't save or cancel.
*
@@ -325,9 +376,4 @@ export interface ITextFileService extends IDisposable {
* Convinient fast access to the raw configured auto save settings.
*/
getAutoSaveConfiguration(): IAutoSaveConfiguration;
/**
* Convinient fast access to the hot exit file setting.
*/
isHotExitEnabled: boolean;
}

View File

@@ -28,9 +28,8 @@ import { IWindowsService, IWindowService } from 'vs/platform/windows/common/wind
import { IHistoryService } from 'vs/workbench/services/history/common/history';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IModelService } from 'vs/editor/common/services/modelService';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { getConfirmMessage, IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { Severity } from 'vs/editor/common/standalone/standaloneBase';
export class TextFileService extends AbstractTextFileService {
@@ -55,7 +54,7 @@ export class TextFileService extends AbstractTextFileService {
super(lifecycleService, contextService, configurationService, fileService, untitledEditorService, instantiationService, notificationService, environmentService, backupFileService, windowsService, historyService, contextKeyService, modelService);
}
public resolveTextContent(resource: URI, options?: IResolveContentOptions): TPromise<IRawTextContent> {
resolveTextContent(resource: URI, options?: IResolveContentOptions): TPromise<IRawTextContent> {
return this.fileService.resolveStreamContent(resource, options).then(streamContent => {
return createTextBufferFactoryFromStream(streamContent.value).then(res => {
const r: IRawTextContent = {
@@ -64,6 +63,7 @@ export class TextFileService extends AbstractTextFileService {
mtime: streamContent.mtime,
etag: streamContent.etag,
encoding: streamContent.encoding,
isReadonly: streamContent.isReadonly,
value: res
};
return r;
@@ -71,7 +71,7 @@ export class TextFileService extends AbstractTextFileService {
});
}
public confirmSave(resources?: URI[]): TPromise<ConfirmResult> {
confirmSave(resources?: URI[]): TPromise<ConfirmResult> {
if (this.environmentService.isExtensionDevelopment) {
return TPromise.wrap(ConfirmResult.DONT_SAVE); // no veto when we are in extension dev mode because we cannot assum we run interactive (e.g. tests)
}
@@ -102,7 +102,7 @@ export class TextFileService extends AbstractTextFileService {
});
}
public promptForPath(defaultPath: string): TPromise<string> {
promptForPath(defaultPath: string): TPromise<string> {
return this.windowService.showSaveDialog(this.getSaveDialogOptions(defaultPath));
}

View File

@@ -16,7 +16,11 @@ import { toResource } from 'vs/base/test/common/utils';
import { TextFileEditorModelManager } from 'vs/workbench/services/textfile/common/textFileEditorModelManager';
import { FileOperationResult, FileOperationError, IFileService, snapshotToString } from 'vs/platform/files/common/files';
import { IModelService } from 'vs/editor/common/services/modelService';
import { timeout } from 'vs/base/common/async';
import { timeout as thenableTimeout } from 'vs/base/common/async';
function timeout(n: number) {
return TPromise.wrap(thenableTimeout(n));
}
class ServiceAccessor {
constructor(@ITextFileService public textFileService: TestTextFileService, @IModelService public modelService: IModelService, @IFileService public fileService: TestFileService) {

View File

@@ -10,8 +10,7 @@ import URI from 'vs/base/common/uri';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { TextFileEditorModelManager } from 'vs/workbench/services/textfile/common/textFileEditorModelManager';
import { join } from 'vs/base/common/paths';
import { workbenchInstantiationService, TestEditorGroupService, TestFileService } from 'vs/workbench/test/workbenchTestServices';
import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService';
import { workbenchInstantiationService, TestFileService } from 'vs/workbench/test/workbenchTestServices';
import { TextFileEditorModel } from 'vs/workbench/services/textfile/common/textFileEditorModel';
import { IFileService, FileChangesEvent, FileChangeType } from 'vs/platform/files/common/files';
import { IModelService } from 'vs/editor/common/services/modelService';
@@ -26,7 +25,6 @@ export class TestTextFileEditorModelManager extends TextFileEditorModelManager {
class ServiceAccessor {
constructor(
@IEditorGroupService public editorGroupService: TestEditorGroupService,
@IFileService public fileService: TestFileService,
@IModelService public modelService: IModelService
) {
@@ -107,7 +105,7 @@ suite('Files - TextFileEditorModelManager', () => {
const resource = URI.file('/test.html');
const encoding = 'utf8';
return manager.loadOrCreate(resource, { encoding, reload: true }).then(model => {
return manager.loadOrCreate(resource, { encoding }).then(model => {
assert.ok(model);
assert.equal(model.getEncoding(), encoding);
assert.equal(manager.get(resource), model);

View File

@@ -5,10 +5,12 @@
'use strict';
import * as assert from 'assert';
import * as sinon from 'sinon';
import * as platform from 'vs/base/common/platform';
import URI from 'vs/base/common/uri';
import { TPromise } from 'vs/base/common/winjs.base';
import { ILifecycleService, ShutdownEvent, ShutdownReason } from 'vs/platform/lifecycle/common/lifecycle';
import { workbenchInstantiationService, TestLifecycleService, TestTextFileService, TestWindowsService, TestContextService } from 'vs/workbench/test/workbenchTestServices';
import { workbenchInstantiationService, TestLifecycleService, TestTextFileService, TestWindowsService, TestContextService, TestFileService } from 'vs/workbench/test/workbenchTestServices';
import { toResource } from 'vs/base/test/common/utils';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IWindowsService } from 'vs/platform/windows/common/windows';
@@ -17,9 +19,12 @@ import { ITextFileService } from 'vs/workbench/services/textfile/common/textfile
import { ConfirmResult } from 'vs/workbench/common/editor';
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { UntitledEditorModel } from 'vs/workbench/common/editor/untitledEditorModel';
import { HotExitConfiguration } from 'vs/platform/files/common/files';
import { HotExitConfiguration, IFileService } from 'vs/platform/files/common/files';
import { TextFileEditorModelManager } from 'vs/workbench/services/textfile/common/textFileEditorModelManager';
import { IWorkspaceContextService, Workspace } from 'vs/platform/workspace/common/workspace';
import { IModelService } from 'vs/editor/common/services/modelService';
import { ModelServiceImpl } from 'vs/editor/common/services/modelServiceImpl';
import { Schemas } from 'vs/base/common/network';
class ServiceAccessor {
constructor(
@@ -27,7 +32,9 @@ class ServiceAccessor {
@ITextFileService public textFileService: TestTextFileService,
@IUntitledEditorService public untitledEditorService: IUntitledEditorService,
@IWindowsService public windowsService: TestWindowsService,
@IWorkspaceContextService public contextService: TestContextService
@IWorkspaceContextService public contextService: TestContextService,
@IModelService public modelService: ModelServiceImpl,
@IFileService public fileService: TestFileService
) {
}
}
@@ -194,6 +201,34 @@ suite('Files - TextFileService', () => {
});
});
test('save - UNC path', function () {
const untitledUncUri = URI.from({ scheme: 'untitled', authority: 'server', path: '/share/path/file.txt' });
model = instantiationService.createInstance(TextFileEditorModel, untitledUncUri, 'utf8');
(<TextFileEditorModelManager>accessor.textFileService.models).add(model.getResource(), model);
const mockedFileUri = untitledUncUri.with({ scheme: Schemas.file });
const mockedEditorInput = instantiationService.createInstance(TextFileEditorModel, mockedFileUri, 'utf8');
const loadOrCreateStub = sinon.stub(accessor.textFileService.models, 'loadOrCreate', () => TPromise.wrap(mockedEditorInput));
sinon.stub(accessor.untitledEditorService, 'exists', () => true);
sinon.stub(accessor.untitledEditorService, 'hasAssociatedFilePath', () => true);
sinon.stub(accessor.modelService, 'updateModel', () => { });
return model.load().then(() => {
model.textEditorModel.setValue('foo');
return accessor.textFileService.saveAll(true).then(res => {
assert.ok(loadOrCreateStub.calledOnce);
assert.equal(res.results.length, 1);
assert.ok(res.results[0].success);
assert.equal(res.results[0].target.scheme, Schemas.file);
assert.equal(res.results[0].target.authority, untitledUncUri.authority);
assert.equal(res.results[0].target.path, untitledUncUri.path);
});
});
});
test('saveAll - file', function () {
model = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/file.txt'), 'utf8');
(<TextFileEditorModelManager>accessor.textFileService.models).add(model.getResource(), model);
@@ -252,6 +287,45 @@ suite('Files - TextFileService', () => {
});
});
test('delete - dirty file', function () {
model = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/file.txt'), 'utf8');
(<TextFileEditorModelManager>accessor.textFileService.models).add(model.getResource(), model);
const service = accessor.textFileService;
return model.load().then(() => {
model.textEditorModel.setValue('foo');
assert.ok(service.isDirty(model.getResource()));
return service.delete(model.getResource()).then(() => {
assert.ok(!service.isDirty(model.getResource()));
});
});
});
test('move - dirty file', function () {
let sourceModel: TextFileEditorModel = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/file.txt'), 'utf8');
let targetModel: TextFileEditorModel = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/file_target.txt'), 'utf8');
(<TextFileEditorModelManager>accessor.textFileService.models).add(sourceModel.getResource(), sourceModel);
(<TextFileEditorModelManager>accessor.textFileService.models).add(targetModel.getResource(), targetModel);
const service = accessor.textFileService;
return sourceModel.load().then(() => {
sourceModel.textEditorModel.setValue('foo');
assert.ok(service.isDirty(sourceModel.getResource()));
return service.move(sourceModel.getResource(), targetModel.getResource(), true).then(() => {
assert.ok(!service.isDirty(sourceModel.getResource()));
sourceModel.dispose();
targetModel.dispose();
});
});
});
// {{SQL CARBON EDIT}}
/*
suite('Hot Exit', () => {