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

A
Alex Dima 已提交
7 8
import {onUnexpectedError} from 'vs/base/common/errors';
import Event, {Emitter} from 'vs/base/common/event';
E
Erich Gamma 已提交
9 10
import {IEmitterEvent} from 'vs/base/common/eventEmitter';
import {IHTMLContentElement} from 'vs/base/common/htmlContent';
A
tslint  
Alex Dima 已提交
11
import {IDisposable} from 'vs/base/common/lifecycle';
A
Alex Dima 已提交
12 13
import Severity from 'vs/base/common/severity';
import URI from 'vs/base/common/uri';
E
Erich Gamma 已提交
14
import {TPromise} from 'vs/base/common/winjs.base';
A
Alex Dima 已提交
15
import {IMarker, IMarkerService} from 'vs/platform/markers/common/markers';
E
Erich Gamma 已提交
16
import {anonymize} from 'vs/platform/telemetry/common/telemetry';
A
Alex Dima 已提交
17 18 19 20
import {IThreadService, Remotable, ThreadAffinity} from 'vs/platform/thread/common/thread';
import {Range} from 'vs/editor/common/core/range';
import * as editorCommon from 'vs/editor/common/editorCommon';
import {IMirrorModelEvents, MirrorModel} from 'vs/editor/common/model/mirrorModel';
E
Erich Gamma 已提交
21
import {Model} from 'vs/editor/common/model/model';
A
Alex Dima 已提交
22 23 24 25
import {IMode} from 'vs/editor/common/modes';
import {IModeService} from 'vs/editor/common/services/modeService';
import {IModelService} from 'vs/editor/common/services/modelService';
import {IResourceService} from 'vs/editor/common/services/resourceService';
26
import * as platform from 'vs/base/common/platform';
E
Erich Gamma 已提交
27 28

export interface IRawModelData {
J
Johannes Rieken 已提交
29
	url:URI;
E
Erich Gamma 已提交
30
	versionId:number;
A
Alex Dima 已提交
31
	value:editorCommon.IRawText;
E
Erich Gamma 已提交
32 33 34
	modeId:string;
}

A
Alex Dima 已提交
35 36 37 38 39
function MODEL_ID(resource:URI): string {
	return resource.toString();
}

class ModelData implements IDisposable {
A
Alex Dima 已提交
40
	model: editorCommon.IModel;
A
Alex Dima 已提交
41
	isSyncedToWorkers: boolean;
E
Erich Gamma 已提交
42

A
Alex Dima 已提交
43 44
	private _markerDecorations: string[];
	private _modelEventsListener: IDisposable;
E
Erich Gamma 已提交
45

A
Alex Dima 已提交
46
	constructor(model: editorCommon.IModel, eventsHandler:(modelData:ModelData, events:IEmitterEvent[])=>void) {
E
Erich Gamma 已提交
47
		this.model = model;
A
Alex Dima 已提交
48 49 50 51
		this.isSyncedToWorkers = false;

		this._markerDecorations = [];
		this._modelEventsListener = model.addBulkListener2((events) => eventsHandler(this, events));
E
Erich Gamma 已提交
52 53 54
	}

	public dispose(): void {
A
Alex Dima 已提交
55 56 57
		this._markerDecorations = this.model.deltaDecorations(this._markerDecorations, []);
		this._modelEventsListener.dispose();
		this._modelEventsListener = null;
E
Erich Gamma 已提交
58
		this.model = null;
A
Alex Dima 已提交
59
	}
E
Erich Gamma 已提交
60

A
Alex Dima 已提交
61 62 63 64
	public getModelId(): string {
		return MODEL_ID(this.model.getAssociatedResource());
	}

A
Alex Dima 已提交
65
	public acceptMarkerDecorations(newDecorations:editorCommon.IModelDeltaDecoration[]): void {
A
Alex Dima 已提交
66
		this._markerDecorations = this.model.deltaDecorations(this._markerDecorations, newDecorations);
E
Erich Gamma 已提交
67
	}
A
Alex Dima 已提交
68
}
E
Erich Gamma 已提交
69

A
Alex Dima 已提交
70 71 72
class ModelMarkerHandler {

	public static setMarkers(modelData:ModelData, markers:IMarker[]):void {
E
Erich Gamma 已提交
73 74 75 76

		// Limit to the first 500 errors/warnings
		markers = markers.slice(0, 500);

A
Alex Dima 已提交
77
		let newModelDecorations:editorCommon.IModelDeltaDecoration[] = markers.map((marker) => {
A
Alex Dima 已提交
78 79
			return {
				range: this._createDecorationRange(modelData.model, marker),
E
Erich Gamma 已提交
80 81 82
				options: this._createDecorationOption(marker)
			};
		});
A
Alex Dima 已提交
83 84

		modelData.acceptMarkerDecorations(newModelDecorations);
E
Erich Gamma 已提交
85 86
	}

A
Alex Dima 已提交
87
	private static _createDecorationRange(model:editorCommon.IModel, rawMarker: IMarker): editorCommon.IRange {
A
Alex Dima 已提交
88
		let marker = model.validateRange(new Range(rawMarker.startLineNumber, rawMarker.startColumn, rawMarker.endLineNumber, rawMarker.endColumn));
A
Alex Dima 已提交
89
		let ret: editorCommon.IEditorRange = new Range(marker.startLineNumber, marker.startColumn, marker.endLineNumber, marker.endColumn);
E
Erich Gamma 已提交
90
		if (ret.isEmpty()) {
A
Alex Dima 已提交
91
			let word = model.getWordAtPosition(ret.getStartPosition());
E
Erich Gamma 已提交
92 93 94 95
			if (word) {
				ret.startColumn = word.startColumn;
				ret.endColumn = word.endColumn;
			} else {
A
Alex Dima 已提交
96 97
				let maxColumn = model.getLineLastNonWhitespaceColumn(marker.startLineNumber) ||
					model.getLineMaxColumn(marker.startLineNumber);
E
Erich Gamma 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111

				if (maxColumn === 1) {
					// empty line
//					console.warn('marker on empty line:', marker);
				} else if (ret.endColumn >= maxColumn) {
					// behind eol
					ret.endColumn = maxColumn;
					ret.startColumn = maxColumn - 1;
				} else {
					// extend marker to width = 1
					ret.endColumn += 1;
				}
			}
		} else if (rawMarker.endColumn === Number.MAX_VALUE && rawMarker.startColumn === 1 && ret.startLineNumber === ret.endLineNumber) {
A
Alex Dima 已提交
112
			let minColumn = model.getLineFirstNonWhitespaceColumn(rawMarker.startLineNumber);
E
Erich Gamma 已提交
113 114 115 116 117 118 119 120
			if (minColumn < ret.endColumn) {
				ret.startColumn = minColumn;
				rawMarker.startColumn = minColumn;
			}
		}
		return ret;
	}

A
Alex Dima 已提交
121
	private static _createDecorationOption(marker:IMarker): editorCommon.IModelDecorationOptions {
E
Erich Gamma 已提交
122 123 124 125 126 127 128 129 130 131 132 133

		let className: string;
		let color: string;
		let darkColor: string;
		let htmlMessage: IHTMLContentElement[] = null;

		switch (marker.severity) {
			case Severity.Ignore:
				// do something
				break;
			case Severity.Warning:
			case Severity.Info:
A
Alex Dima 已提交
134
				className = editorCommon.ClassName.EditorWarningDecoration;
E
Erich Gamma 已提交
135 136 137 138 139
				color = 'rgba(18,136,18,0.7)';
				darkColor = 'rgba(18,136,18,0.7)';
				break;
			case Severity.Error:
			default:
A
Alex Dima 已提交
140
				className = editorCommon.ClassName.EditorErrorDecoration;
E
Erich Gamma 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153
				color = 'rgba(255,18,18,0.7)';
				darkColor = 'rgba(255,18,18,0.7)';
				break;
		}

		if (typeof marker.message === 'string') {
			htmlMessage = [{ isText: true, text: marker.message }];
		} else if (Array.isArray(marker.message)) {
			htmlMessage = <IHTMLContentElement[]><any>marker.message;
		} else if (marker.message) {
			htmlMessage = [marker.message];
		}

154 155 156 157
		if (marker.source) {
			htmlMessage.unshift({ isText: true, text: `[${marker.source}] ` });
		}

E
Erich Gamma 已提交
158
		return {
A
Alex Dima 已提交
159
			stickiness: editorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
E
Erich Gamma 已提交
160 161 162 163 164
			className,
			htmlMessage: htmlMessage,
			overviewRuler: {
				color,
				darkColor,
A
Alex Dima 已提交
165
				position: editorCommon.OverviewRulerLane.Right
E
Erich Gamma 已提交
166 167 168 169 170 171 172 173 174 175 176
			}
		};
	}
}

export class ModelServiceImpl implements IModelService {
	public serviceId = IModelService;

	private _markerService: IMarkerService;
	private _markerServiceSubscription: IDisposable;
	private _threadService: IThreadService;
177
	private _modeService: IModeService;
E
Erich Gamma 已提交
178 179
	private _workerHelper: ModelServiceWorkerHelper;

A
Alex Dima 已提交
180 181 182
	private _onModelAdded: Emitter<editorCommon.IModel>;
	private _onModelRemoved: Emitter<editorCommon.IModel>;
	private _onModelModeChanged: Emitter<{ model: editorCommon.IModel; oldModeId: string; }>;
A
Alex Dima 已提交
183 184 185 186 187

	/**
	 * All the models known in the system.
	 */
	private _models: {[modelId:string]:ModelData;};
E
Erich Gamma 已提交
188

189
	constructor(threadService: IThreadService, markerService: IMarkerService, modeService:IModeService) {
E
Erich Gamma 已提交
190 191
		this._threadService = threadService;
		this._markerService = markerService;
192
		this._modeService = modeService;
E
Erich Gamma 已提交
193 194 195 196
		this._workerHelper = this._threadService.getRemotable(ModelServiceWorkerHelper);

		this._models = {};

A
Alex Dima 已提交
197 198 199
		this._onModelAdded = new Emitter<editorCommon.IModel>();
		this._onModelRemoved = new Emitter<editorCommon.IModel>();
		this._onModelModeChanged = new Emitter<{ model: editorCommon.IModel; oldModeId: string; }>();
E
Erich Gamma 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212

		if(this._markerService) {
			this._markerServiceSubscription = this._markerService.onMarkerChanged(this._handleMarkerChange, this);
		}
	}

	public dispose(): void {
		if(this._markerServiceSubscription) {
			this._markerServiceSubscription.dispose();
		}
	}

	private _handleMarkerChange(changedResources: URI[]): void {
A
Alex Dima 已提交
213 214 215 216
		changedResources.forEach((resource) => {
			let modelId = MODEL_ID(resource);
			let modelData = this._models[modelId];
			if (!modelData) {
E
Erich Gamma 已提交
217 218
				return;
			}
A
Alex Dima 已提交
219
			ModelMarkerHandler.setMarkers(modelData, this._markerService.read({ resource: resource, take: 500 }));
E
Erich Gamma 已提交
220 221 222 223 224
		});
	}

	// --- begin IModelService

A
Alex Dima 已提交
225
	private _shouldSyncModelToWorkers(model:editorCommon.IModel): boolean {
226 227 228 229 230 231 232
		if (model.isTooLargeForHavingARichMode()) {
			return false;
		}
		// Only sync models with compat modes to the workers
		return this._modeService.isCompatMode(model.getMode().getId());
	}

A
Alex Dima 已提交
233
	private _createModelData(value:string, modeOrPromise:TPromise<IMode>|IMode, resource: URI): ModelData {
234
		let defaultEOL = (platform.isLinux || platform.isMacintosh) ? editorCommon.DefaultEndOfLine.LF : editorCommon.DefaultEndOfLine.CRLF;
A
Alex Dima 已提交
235
		// create & save the model
236
		let model = new Model(value, defaultEOL, modeOrPromise, resource);
A
Alex Dima 已提交
237
		let modelId = MODEL_ID(model.getAssociatedResource());
E
Erich Gamma 已提交
238 239 240

		if (this._models[modelId]) {
			// There already exists a model with this id => this is a programmer error
A
Alex Dima 已提交
241
			throw new Error('ModelService: Cannot add model ' + anonymize(modelId) + ' because it already exists!');
E
Erich Gamma 已提交
242 243
		}

A
Alex Dima 已提交
244 245
		let modelData = new ModelData(model, (modelData, events) => this._onModelEvents(modelData, events));
		this._models[modelId] = modelData;
E
Erich Gamma 已提交
246

A
Alex Dima 已提交
247
		return modelData;
E
Erich Gamma 已提交
248 249
	}

A
Alex Dima 已提交
250
	public createModel(value:string, modeOrPromise:TPromise<IMode>|IMode, resource: URI): editorCommon.IModel {
A
Alex Dima 已提交
251
		let modelData = this._createModelData(value, modeOrPromise, resource);
E
Erich Gamma 已提交
252

A
Alex Dima 已提交
253 254 255
		// handle markers (marker service => model)
		if (this._markerService) {
			ModelMarkerHandler.setMarkers(modelData, this._markerService.read({ resource: modelData.model.getAssociatedResource() }));
E
Erich Gamma 已提交
256 257
		}

258
		if (this._shouldSyncModelToWorkers(modelData.model)) {
A
Alex Dima 已提交
259
			// send this model to the workers
260
			this._beginWorkerSync(modelData);
E
Erich Gamma 已提交
261 262
		}

A
Alex Dima 已提交
263
		this._onModelAdded.fire(modelData.model);
E
Erich Gamma 已提交
264

A
Alex Dima 已提交
265
		return modelData.model;
E
Erich Gamma 已提交
266 267
	}

J
Johannes Rieken 已提交
268
	public destroyModel(resource: URI): void {
A
Alex Dima 已提交
269 270 271 272
		// We need to support that not all models get disposed through this service (i.e. model.dispose() should work!)
		let modelData = this._models[MODEL_ID(resource)];
		if (!modelData) {
			return;
E
Erich Gamma 已提交
273
		}
A
Alex Dima 已提交
274
		modelData.model.dispose();
E
Erich Gamma 已提交
275 276
	}

A
Alex Dima 已提交
277 278
	public getModels(): editorCommon.IModel[] {
		let ret: editorCommon.IModel[] = [];
A
Alex Dima 已提交
279
		for (let modelId in this._models) {
E
Erich Gamma 已提交
280 281 282 283 284 285 286
			if (this._models.hasOwnProperty(modelId)) {
				ret.push(this._models[modelId].model);
			}
		}
		return ret;
	}

A
Alex Dima 已提交
287
	public getModel(resource: URI): editorCommon.IModel {
A
Alex Dima 已提交
288 289 290 291
		let modelId = MODEL_ID(resource);
		let modelData = this._models[modelId];
		if (!modelData) {
			return null;
E
Erich Gamma 已提交
292
		}
A
Alex Dima 已提交
293
		return modelData.model;
E
Erich Gamma 已提交
294 295
	}

A
Alex Dima 已提交
296
	public get onModelAdded(): Event<editorCommon.IModel> {
297
		return this._onModelAdded ? this._onModelAdded.event : null;
E
Erich Gamma 已提交
298 299
	}

A
Alex Dima 已提交
300
	public get onModelRemoved(): Event<editorCommon.IModel> {
301
		return this._onModelRemoved ? this._onModelRemoved.event : null;
E
Erich Gamma 已提交
302 303
	}

A
Alex Dima 已提交
304
	public get onModelModeChanged(): Event<{ model: editorCommon.IModel; oldModeId: string; }> {
305
		return this._onModelModeChanged ? this._onModelModeChanged.event : null;
E
Erich Gamma 已提交
306 307 308 309
	}

	// --- end IModelService

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
	private _beginWorkerSync(modelData:ModelData): void {
		if (modelData.isSyncedToWorkers) {
			throw new Error('Model is already being synced to workers!');
		}

		modelData.isSyncedToWorkers = true;
		this._workerHelper.$_acceptNewModel(ModelServiceImpl._getBoundModelData(modelData.model));
	}

	private _stopWorkerSync(modelData:ModelData): void {
		if (!modelData.isSyncedToWorkers) {
			throw new Error('Model is already not being synced to workers!');
		}
		modelData.isSyncedToWorkers = false;
		this._workerHelper.$_acceptDidDisposeModel(modelData.model.getAssociatedResource());
	}

A
Alex Dima 已提交
327
	private _onModelDisposing(model:editorCommon.IModel): void {
A
Alex Dima 已提交
328 329 330 331 332 333 334 335 336 337 338 339 340 341
		let modelId = MODEL_ID(model.getAssociatedResource());
		let modelData = this._models[modelId];

		// TODO@Joh why are we removing markers here?
		if (this._markerService) {
			var markers = this._markerService.read({ resource: model.getAssociatedResource() }),
				owners: { [o: string]: any } = Object.create(null);

			markers.forEach(marker => owners[marker.owner] = this);
			Object.keys(owners).forEach(owner => this._markerService.changeOne(owner, model.getAssociatedResource(), []));
		}

		if (modelData.isSyncedToWorkers) {
			// Dispose model in workers
342
			this._stopWorkerSync(modelData);
A
Alex Dima 已提交
343 344 345 346 347 348 349 350
		}

		delete this._models[modelId];
		modelData.dispose();

		this._onModelRemoved.fire(model);
	}

A
Alex Dima 已提交
351
	private static _getBoundModelData(model:editorCommon.IModel): IRawModelData {
E
Erich Gamma 已提交
352 353 354 355 356 357 358 359
		return {
			url: model.getAssociatedResource(),
			versionId: model.getVersionId(),
			value: model.toRawText(),
			modeId: model.getMode().getId()
		};
	}

A
Alex Dima 已提交
360
	private _onModelEvents(modelData:ModelData, events:IEmitterEvent[]): void {
E
Erich Gamma 已提交
361

362
		// First look for dispose
A
Alex Dima 已提交
363 364
		for (let i = 0, len = events.length; i < len; i++) {
			let e = events[i];
A
Alex Dima 已提交
365
			if (e.getType() === editorCommon.EventType.ModelDispose) {
366 367 368 369 370
				this._onModelDisposing(modelData.model);
				// no more processing since model got disposed
				return;
			}
		}
E
Erich Gamma 已提交
371

372 373 374
		// Second, look for mode change
		for (let i = 0, len = events.length; i < len; i++) {
			let e = events[i];
A
Alex Dima 已提交
375
			if (e.getType() === editorCommon.EventType.ModelModeChanged) {
376 377
				let wasSyncedToWorkers = modelData.isSyncedToWorkers;
				let shouldSyncToWorkers = this._shouldSyncModelToWorkers(modelData.model);
E
Erich Gamma 已提交
378

379 380
				this._onModelModeChanged.fire({
					model: modelData.model,
A
Alex Dima 已提交
381
					oldModeId: (<editorCommon.IModelModeChangedEvent>e.getData()).oldMode.getId()
382 383
				});

384 385 386
				if (wasSyncedToWorkers) {
					if (shouldSyncToWorkers) {
						// true -> true
A
Alex Dima 已提交
387
						// Forward mode change to all the workers
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
						this._workerHelper.$_acceptDidChangeModelMode(modelData.getModelId(), modelData.model.getMode().getId());
					} else {
						// true -> false
						// Stop worker sync for this model
						this._stopWorkerSync(modelData);
						// no more processing since we have removed the model from the workers
						return;
					}
				} else {
					if (shouldSyncToWorkers) {
						// false -> true
						// Begin syncing this model to the workers
						this._beginWorkerSync(modelData);
						// no more processing since we are sending the latest state
						return;
					} else {
						// false -> false
						// no more processing since this model was not synced and will not be synced
						return;
A
Alex Dima 已提交
407
					}
408 409 410 411 412 413 414 415 416 417 418 419 420
				}
			}
		}

		if (!modelData.isSyncedToWorkers) {
			return;
		}

		// Finally, look for model content changes
		let eventsForWorkers: IMirrorModelEvents = { contentChanged: [] };
		for (let i = 0, len = events.length; i < len; i++) {
			let e = events[i];

A
Alex Dima 已提交
421 422
			if (e.getType() === editorCommon.EventType.ModelContentChanged) {
				eventsForWorkers.contentChanged.push(<editorCommon.IModelContentChangedEvent>e.getData());
E
Erich Gamma 已提交
423 424 425
			}
		}

A
Alex Dima 已提交
426
		if (eventsForWorkers.contentChanged.length > 0) {
E
Erich Gamma 已提交
427
			// Forward events to all the workers
A
Alex Dima 已提交
428
			this._workerHelper.$_acceptModelEvents(modelData.getModelId(), eventsForWorkers);
E
Erich Gamma 已提交
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
		}
	}
}

@Remotable.WorkerContext('ModelServiceWorkerHelper', ThreadAffinity.All)
export class ModelServiceWorkerHelper {

	private _resourceService:IResourceService;
	private _modeService:IModeService;

	constructor(
		@IResourceService resourceService: IResourceService,
		@IModeService modeService: IModeService
	) {
		this._resourceService = resourceService;
		this._modeService = modeService;
	}

A
Alex Dima 已提交
447
	public $_acceptNewModel(data:IRawModelData): TPromise<void> {
E
Erich Gamma 已提交
448
		// Create & insert the mirror model eagerly in the resource service
A
Alex Dima 已提交
449
		let mirrorModel = new MirrorModel(this._resourceService, data.versionId, data.value, null, data.url);
E
Erich Gamma 已提交
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
		this._resourceService.insert(mirrorModel.getAssociatedResource(), mirrorModel);

		// Block worker execution until the mode is instantiated
		return this._modeService.getOrCreateMode(data.modeId).then((mode) => {
			// Changing mode should trigger a remove & an add, therefore:

			// (1) Remove from resource service
			this._resourceService.remove(mirrorModel.getAssociatedResource());

			// (2) Change mode
			mirrorModel.setMode(mode);

			// (3) Insert again to resource service (it will have the new mode)
			this._resourceService.insert(mirrorModel.getAssociatedResource(), mirrorModel);
		});
	}

467
	public $_acceptDidChangeModelMode(modelId:string, newModeId:string): TPromise<void> {
A
Alex Dima 已提交
468
		let mirrorModel = this._resourceService.get(URI.parse(modelId));
E
Erich Gamma 已提交
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484

		// Block worker execution until the mode is instantiated
		return this._modeService.getOrCreateMode(newModeId).then((mode) => {
			// Changing mode should trigger a remove & an add, therefore:

			// (1) Remove from resource service
			this._resourceService.remove(mirrorModel.getAssociatedResource());

			// (2) Change mode
			mirrorModel.setMode(mode);

			// (3) Insert again to resource service (it will have the new mode)
			this._resourceService.insert(mirrorModel.getAssociatedResource(), mirrorModel);
		});
	}

J
Johannes Rieken 已提交
485
	public $_acceptDidDisposeModel(url:URI): void {
A
Alex Dima 已提交
486
		let model = <MirrorModel>this._resourceService.get(url);
E
Erich Gamma 已提交
487 488 489 490 491 492
		this._resourceService.remove(url);
		if (model) {
			model.dispose();
		}
	}

A
Alex Dima 已提交
493
	public $_acceptModelEvents(modelId: string, events:IMirrorModelEvents): void {
J
Johannes Rieken 已提交
494
		let model = <MirrorModel>this._resourceService.get(URI.parse(modelId));
A
Alex Dima 已提交
495 496 497 498 499 500
		if (!model) {
			throw new Error('Received model events for missing model ' + anonymize(modelId));
		}
		try {
			model.onEvents(events);
		} catch (err) {
A
Alex Dima 已提交
501
			onUnexpectedError(err);
E
Erich Gamma 已提交
502 503 504
		}
	}
}