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

J
Johannes Rieken 已提交
7 8 9 10
import { onUnexpectedError } from 'vs/base/common/errors';
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { EmitterEvent } from 'vs/base/common/eventEmitter';
import { IModelService } from 'vs/editor/common/services/modelService';
11
import * as editorCommon from 'vs/editor/common/editorCommon';
J
Johannes Rieken 已提交
12
import { IThreadService } from 'vs/workbench/services/thread/common/threadService';
13
import URI from 'vs/base/common/uri';
J
Johannes Rieken 已提交
14 15 16 17 18 19 20 21 22
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { IEventService } from 'vs/platform/event/common/event';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { TextFileModelChangeEvent, ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { TPromise } from 'vs/base/common/winjs.base';
import { IFileService } from 'vs/platform/files/common/files';
import { IModeService } from 'vs/editor/common/services/modeService';
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { ExtHostContext, MainThreadDocumentsShape, ExtHostDocumentsShape } from './extHost.protocol';
23
import { ITextModelResolverService } from 'vs/platform/textmodelResolver/common/textModelResolverService';
24

A
Alex Dima 已提交
25
export class MainThreadDocuments extends MainThreadDocumentsShape {
26 27
	private _modelService: IModelService;
	private _modeService: IModeService;
B
Benjamin Pasero 已提交
28
	private _textModelResolverService: ITextModelResolverService;
29 30 31 32 33 34
	private _textFileService: ITextFileService;
	private _editorService: IWorkbenchEditorService;
	private _fileService: IFileService;
	private _untitledEditorService: IUntitledEditorService;
	private _toDispose: IDisposable[];
	private _modelToDisposeMap: { [modelUrl: string]: IDisposable; };
35
	private _proxy: ExtHostDocumentsShape;
36 37 38 39 40 41 42 43 44 45 46 47
	private _modelIsSynced: { [modelId: string]: boolean; };
	private _resourceContentProvider: { [handle: number]: IDisposable };
	private _virtualDocumentSet: { [resource: string]: boolean };

	constructor(
		@IThreadService threadService: IThreadService,
		@IModelService modelService: IModelService,
		@IModeService modeService: IModeService,
		@IEventService eventService: IEventService,
		@ITextFileService textFileService: ITextFileService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IFileService fileService: IFileService,
B
Benjamin Pasero 已提交
48
		@ITextModelResolverService textModelResolverService: ITextModelResolverService,
49 50
		@IUntitledEditorService untitledEditorService: IUntitledEditorService
	) {
A
Alex Dima 已提交
51
		super();
52 53
		this._modelService = modelService;
		this._modeService = modeService;
B
Benjamin Pasero 已提交
54
		this._textModelResolverService = textModelResolverService;
55 56 57 58 59 60 61 62 63 64 65 66
		this._textFileService = textFileService;
		this._editorService = editorService;
		this._fileService = fileService;
		this._untitledEditorService = untitledEditorService;
		this._proxy = threadService.get(ExtHostContext.ExtHostDocuments);
		this._modelIsSynced = {};

		this._toDispose = [];
		modelService.onModelAdded(this._onModelAdded, this, this._toDispose);
		modelService.onModelRemoved(this._onModelRemoved, this, this._toDispose);
		modelService.onModelModeChanged(this._onModelModeChanged, this, this._toDispose);

67
		this._toDispose.push(textFileService.models.onModelSaved(e => {
68
			if (this._shouldHandleFileEvent(e)) {
69
				this._proxy.$acceptModelSaved(e.resource.toString());
70 71
			}
		}));
72
		this._toDispose.push(textFileService.models.onModelReverted(e => {
73
			if (this._shouldHandleFileEvent(e)) {
74
				this._proxy.$acceptModelReverted(e.resource.toString());
75 76
			}
		}));
77
		this._toDispose.push(textFileService.models.onModelDirty(e => {
78
			if (this._shouldHandleFileEvent(e)) {
79
				this._proxy.$acceptModelDirty(e.resource.toString());
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
			}
		}));

		const handle = setInterval(() => this._runDocumentCleanup(), 1000 * 60 * 3);
		this._toDispose.push({ dispose() { clearInterval(handle); } });

		this._modelToDisposeMap = Object.create(null);
		this._resourceContentProvider = Object.create(null);
		this._virtualDocumentSet = Object.create(null);
	}

	public dispose(): void {
		Object.keys(this._modelToDisposeMap).forEach((modelUrl) => {
			this._modelToDisposeMap[modelUrl].dispose();
		});
		this._modelToDisposeMap = Object.create(null);
		this._toDispose = dispose(this._toDispose);
	}

99
	private _shouldHandleFileEvent(e: TextFileModelChangeEvent): boolean {
100 101 102 103 104 105 106 107 108 109 110 111 112
		const model = this._modelService.getModel(e.resource);
		return model && !model.isTooLargeForHavingARichMode();
	}

	private _onModelAdded(model: editorCommon.IModel): void {
		// Same filter as in mainThreadEditorsTracker
		if (model.isTooLargeForHavingARichMode()) {
			// don't synchronize too large models
			return null;
		}
		let modelUrl = model.uri;
		this._modelIsSynced[modelUrl.toString()] = true;
		this._modelToDisposeMap[modelUrl.toString()] = model.addBulkListener((events) => this._onModelEvents(modelUrl, events));
113
		this._proxy.$acceptModelAdd({
114 115 116 117 118 119 120 121 122 123 124 125 126 127
			url: model.uri,
			versionId: model.getVersionId(),
			value: model.toRawText(),
			modeId: model.getMode().getId(),
			isDirty: this._textFileService.isDirty(modelUrl)
		});
	}

	private _onModelModeChanged(event: { model: editorCommon.IModel; oldModeId: string; }): void {
		let {model, oldModeId} = event;
		let modelUrl = model.uri;
		if (!this._modelIsSynced[modelUrl.toString()]) {
			return;
		}
128
		this._proxy.$acceptModelModeChanged(model.uri.toString(), oldModeId, model.getMode().getId());
129 130 131 132 133 134 135 136 137 138
	}

	private _onModelRemoved(model: editorCommon.IModel): void {
		let modelUrl = model.uri;
		if (!this._modelIsSynced[modelUrl.toString()]) {
			return;
		}
		delete this._modelIsSynced[modelUrl.toString()];
		this._modelToDisposeMap[modelUrl.toString()].dispose();
		delete this._modelToDisposeMap[modelUrl.toString()];
139
		this._proxy.$acceptModelRemoved(modelUrl.toString());
140 141 142
	}

	private _onModelEvents(modelUrl: URI, events: EmitterEvent[]): void {
143 144 145 146 147 148 149
		let changedEvents: editorCommon.IModelContentChangedEvent2[] = [];
		for (let i = 0, len = events.length; i < len; i++) {
			let e = events[i];
			switch (e.getType()) {
				case editorCommon.EventType.ModelContentChanged2:
					changedEvents.push(<editorCommon.IModelContentChangedEvent2>e.getData());
					break;
150
			}
151 152 153 154
		}
		if (changedEvents.length > 0) {
			this._proxy.$acceptModelChanged(modelUrl.toString(), changedEvents, this._textFileService.isDirty(modelUrl));
		}
155 156 157 158
	}

	// --- from extension host process

159
	$trySaveDocument(uri: URI): TPromise<boolean> {
160 161 162
		return this._textFileService.save(uri);
	}

163
	$tryOpenDocument(uri: URI): TPromise<any> {
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

		if (!uri.scheme || !(uri.fsPath || uri.authority)) {
			return TPromise.wrapError(`Invalid uri. Scheme and authority or path must be set.`);
		}

		let promise: TPromise<boolean>;
		switch (uri.scheme) {
			case 'untitled':
				promise = this._handleUnititledScheme(uri);
				break;
			case 'file':
			default:
				promise = this._handleAsResourceInput(uri);
				break;
		}

		return promise.then(success => {
			if (!success) {
				return TPromise.wrapError('cannot open ' + uri.toString());
			}
		}, err => {
			return TPromise.wrapError('cannot open ' + uri.toString() + '. Detail: ' + toErrorMessage(err));
		});
	}

	private _handleAsResourceInput(uri: URI): TPromise<boolean> {
		return this._editorService.resolveEditorModel({ resource: uri }).then(model => {
			return !!model;
		});
	}

	private _handleUnititledScheme(uri: URI): TPromise<boolean> {
		let asFileUri = URI.file(uri.fsPath);
		return this._fileService.resolveFile(asFileUri).then(stats => {
			// don't create a new file ontop of an existing file
			return TPromise.wrapError<boolean>('file already exists on disk');
		}, err => {
201
			let input = this._untitledEditorService.createOrGet(asFileUri);
202 203
			return input.resolve(true).then(model => {
				if (input.getResource().toString() !== uri.toString()) {
J
Johannes Rieken 已提交
204
					throw new Error(`expected URI ${uri.toString()} BUT GOT ${input.getResource().toString()}`);
205 206 207 208
				}
				if (!this._modelIsSynced[uri.toString()]) {
					throw new Error(`expected URI ${uri.toString()} to have come to LIFE`);
				}
209
				return this._proxy.$acceptModelDirty(uri.toString()); // mark as dirty
210 211 212 213 214 215 216 217
			}).then(() => {
				return true;
			});
		});
	}

	// --- virtual document logic

J
Johannes Rieken 已提交
218
	$registerTextContentProvider(handle: number, scheme: string): void {
B
Benjamin Pasero 已提交
219
		this._resourceContentProvider[handle] = this._textModelResolverService.registerTextModelContentProvider(scheme, {
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
			provideTextContent: (uri: URI): TPromise<editorCommon.IModel> => {
				return this._proxy.$provideTextDocumentContent(handle, uri).then(value => {
					if (typeof value === 'string') {
						this._virtualDocumentSet[uri.toString()] = true;
						const firstLineText = value.substr(0, 1 + value.search(/\r?\n/));
						const mode = this._modeService.getOrCreateModeByFilenameOrFirstLine(uri.fsPath, firstLineText);
						return this._modelService.createModel(value, mode, uri);
					}
				});
			}
		});
	}

	$unregisterTextContentProvider(handle: number): void {
		const registration = this._resourceContentProvider[handle];
		if (registration) {
			registration.dispose();
			delete this._resourceContentProvider[handle];
		}
	}

	$onVirtualDocumentChange(uri: URI, value: string): void {
		const model = this._modelService.getModel(uri);
		if (model) {
			model.setValue(value);
		}
	}

	private _runDocumentCleanup(): void {

		const toBeDisposed: URI[] = [];

		TPromise.join(Object.keys(this._virtualDocumentSet).map(key => {
			let resource = URI.parse(key);
			return this._editorService.createInput({ resource }).then(input => {
				if (!this._editorService.isVisible(input, true)) {
					toBeDisposed.push(resource);
				}
B
💄  
Benjamin Pasero 已提交
258 259 260 261

				if (input) {
					input.dispose();
				}
262 263 264 265 266 267 268 269 270
			});
		})).then(() => {
			for (let resource of toBeDisposed) {
				this._modelService.destroyModel(resource);
				delete this._virtualDocumentSet[resource.toString()];
			}
		}, onUnexpectedError);
	}
}