modelServiceImpl.ts 18.6 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';
27
import {IConfigurationService, ConfigurationServiceEventTypes, IConfigurationServiceEvent} from 'vs/platform/configuration/common/configuration';
28
import {DEFAULT_INDENTATION} from 'vs/editor/common/config/defaultConfig';
E
Erich Gamma 已提交
29 30

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

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

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

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

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

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

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

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

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

A
Alex Dima 已提交
72 73 74
class ModelMarkerHandler {

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

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

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

		modelData.acceptMarkerDecorations(newModelDecorations);
E
Erich Gamma 已提交
87 88
	}

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

				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 已提交
114
			let minColumn = model.getLineFirstNonWhitespaceColumn(rawMarker.startLineNumber);
E
Erich Gamma 已提交
115 116 117 118 119 120 121 122
			if (minColumn < ret.endColumn) {
				ret.startColumn = minColumn;
				rawMarker.startColumn = minColumn;
			}
		}
		return ret;
	}

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

		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 已提交
136
				className = editorCommon.ClassName.EditorWarningDecoration;
E
Erich Gamma 已提交
137 138 139 140 141
				color = 'rgba(18,136,18,0.7)';
				darkColor = 'rgba(18,136,18,0.7)';
				break;
			case Severity.Error:
			default:
A
Alex Dima 已提交
142
				className = editorCommon.ClassName.EditorErrorDecoration;
E
Erich Gamma 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155
				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];
		}

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

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

export class ModelServiceImpl implements IModelService {
	public serviceId = IModelService;

	private _markerService: IMarkerService;
	private _markerServiceSubscription: IDisposable;
	private _threadService: IThreadService;
179
	private _modeService: IModeService;
180 181
	private _configurationService: IConfigurationService;
	private _configurationServiceSubscription: IDisposable;
E
Erich Gamma 已提交
182 183
	private _workerHelper: ModelServiceWorkerHelper;

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

	private _modelCreationOptions: editorCommon.ITextModelCreationOptions;
A
Alex Dima 已提交
189 190 191 192 193

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

195 196 197 198 199 200
	constructor(
		threadService: IThreadService,
		markerService: IMarkerService,
		modeService: IModeService,
		configurationService: IConfigurationService
	) {
201
		this._modelCreationOptions = {
202 203 204
			tabSize: DEFAULT_INDENTATION.tabSize,
			insertSpaces: DEFAULT_INDENTATION.insertSpaces,
			detectIndentation: DEFAULT_INDENTATION.detectIndentation,
205 206
			defaultEOL: (platform.isLinux || platform.isMacintosh) ? editorCommon.DefaultEndOfLine.LF : editorCommon.DefaultEndOfLine.CRLF
		};
E
Erich Gamma 已提交
207 208
		this._threadService = threadService;
		this._markerService = markerService;
209
		this._modeService = modeService;
E
Erich Gamma 已提交
210
		this._workerHelper = this._threadService.getRemotable(ModelServiceWorkerHelper);
211 212 213
		this._configurationService = configurationService;

		let readDefaultEOL = (config:any) => {
J
Joao Moreno 已提交
214 215
			const eol = config.files && config.files.eol;

216
			let newTabSize = DEFAULT_INDENTATION.tabSize;
217 218 219 220 221 222 223
			if (config.editor && typeof config.editor.tabSize !== 'undefined') {
				let parsedTabSize = parseInt(config.editor.tabSize, 10);
				if (!isNaN(parsedTabSize)) {
					newTabSize = parsedTabSize;
				}
			}

224
			let newInsertSpaces = DEFAULT_INDENTATION.insertSpaces;
225 226 227 228 229
			if (config.editor && typeof config.editor.insertSpaces !== 'undefined') {
				newInsertSpaces = (config.editor.insertSpaces === 'false' ? false : Boolean(config.editor.insertSpaces));
			}

			let newDefaultEOL = this._modelCreationOptions.defaultEOL;
J
Joao Moreno 已提交
230
			if (eol === '\r\n') {
231
				newDefaultEOL = editorCommon.DefaultEndOfLine.CRLF;
J
Joao Moreno 已提交
232
			} else if (eol === '\n') {
233
				newDefaultEOL = editorCommon.DefaultEndOfLine.LF;
234
			}
235

236
			let detectIndentation = DEFAULT_INDENTATION.detectIndentation;
237 238 239 240

			this._modelCreationOptions = {
				tabSize: newTabSize,
				insertSpaces: newInsertSpaces,
241
				detectIndentation: detectIndentation,
242 243
				defaultEOL: newDefaultEOL
			};
244 245 246 247 248 249 250
		};
		this._configurationServiceSubscription = this._configurationService.addListener2(ConfigurationServiceEventTypes.UPDATED, (e: IConfigurationServiceEvent) => {
			readDefaultEOL(e.config);
		});
		this._configurationService.loadConfiguration().then((config) => {
			readDefaultEOL(config);
		});
E
Erich Gamma 已提交
251 252 253

		this._models = {};

A
Alex Dima 已提交
254 255 256
		this._onModelAdded = new Emitter<editorCommon.IModel>();
		this._onModelRemoved = new Emitter<editorCommon.IModel>();
		this._onModelModeChanged = new Emitter<{ model: editorCommon.IModel; oldModeId: string; }>();
E
Erich Gamma 已提交
257 258 259 260 261 262 263 264 265 266

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

	public dispose(): void {
		if(this._markerServiceSubscription) {
			this._markerServiceSubscription.dispose();
		}
267
		this._configurationServiceSubscription.dispose();
E
Erich Gamma 已提交
268 269 270
	}

	private _handleMarkerChange(changedResources: URI[]): void {
A
Alex Dima 已提交
271 272 273 274
		changedResources.forEach((resource) => {
			let modelId = MODEL_ID(resource);
			let modelData = this._models[modelId];
			if (!modelData) {
E
Erich Gamma 已提交
275 276
				return;
			}
A
Alex Dima 已提交
277
			ModelMarkerHandler.setMarkers(modelData, this._markerService.read({ resource: resource, take: 500 }));
E
Erich Gamma 已提交
278 279 280 281 282
		});
	}

	// --- begin IModelService

A
Alex Dima 已提交
283
	private _shouldSyncModelToWorkers(model:editorCommon.IModel): boolean {
284 285 286 287 288 289 290
		if (model.isTooLargeForHavingARichMode()) {
			return false;
		}
		// Only sync models with compat modes to the workers
		return this._modeService.isCompatMode(model.getMode().getId());
	}

A
Alex Dima 已提交
291
	private _createModelData(value:string, modeOrPromise:TPromise<IMode>|IMode, resource: URI): ModelData {
A
Alex Dima 已提交
292
		// create & save the model
293
		let model = new Model(value, this._modelCreationOptions, modeOrPromise, resource);
A
Alex Dima 已提交
294
		let modelId = MODEL_ID(model.getAssociatedResource());
E
Erich Gamma 已提交
295 296 297

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

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

A
Alex Dima 已提交
304
		return modelData;
E
Erich Gamma 已提交
305 306
	}

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

A
Alex Dima 已提交
310 311 312
		// handle markers (marker service => model)
		if (this._markerService) {
			ModelMarkerHandler.setMarkers(modelData, this._markerService.read({ resource: modelData.model.getAssociatedResource() }));
E
Erich Gamma 已提交
313 314
		}

315
		if (this._shouldSyncModelToWorkers(modelData.model)) {
A
Alex Dima 已提交
316
			// send this model to the workers
317
			this._beginWorkerSync(modelData);
E
Erich Gamma 已提交
318 319
		}

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

A
Alex Dima 已提交
322
		return modelData.model;
E
Erich Gamma 已提交
323 324
	}

J
Johannes Rieken 已提交
325
	public destroyModel(resource: URI): void {
A
Alex Dima 已提交
326 327 328 329
		// 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 已提交
330
		}
A
Alex Dima 已提交
331
		modelData.model.dispose();
E
Erich Gamma 已提交
332 333
	}

A
Alex Dima 已提交
334 335
	public getModels(): editorCommon.IModel[] {
		let ret: editorCommon.IModel[] = [];
A
Alex Dima 已提交
336
		for (let modelId in this._models) {
E
Erich Gamma 已提交
337 338 339 340 341 342 343
			if (this._models.hasOwnProperty(modelId)) {
				ret.push(this._models[modelId].model);
			}
		}
		return ret;
	}

A
Alex Dima 已提交
344
	public getModel(resource: URI): editorCommon.IModel {
A
Alex Dima 已提交
345 346 347 348
		let modelId = MODEL_ID(resource);
		let modelData = this._models[modelId];
		if (!modelData) {
			return null;
E
Erich Gamma 已提交
349
		}
A
Alex Dima 已提交
350
		return modelData.model;
E
Erich Gamma 已提交
351 352
	}

A
Alex Dima 已提交
353
	public get onModelAdded(): Event<editorCommon.IModel> {
354
		return this._onModelAdded ? this._onModelAdded.event : null;
E
Erich Gamma 已提交
355 356
	}

A
Alex Dima 已提交
357
	public get onModelRemoved(): Event<editorCommon.IModel> {
358
		return this._onModelRemoved ? this._onModelRemoved.event : null;
E
Erich Gamma 已提交
359 360
	}

A
Alex Dima 已提交
361
	public get onModelModeChanged(): Event<{ model: editorCommon.IModel; oldModeId: string; }> {
362
		return this._onModelModeChanged ? this._onModelModeChanged.event : null;
E
Erich Gamma 已提交
363 364 365 366
	}

	// --- end IModelService

367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
	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 已提交
384
	private _onModelDisposing(model:editorCommon.IModel): void {
A
Alex Dima 已提交
385 386 387 388 389 390 391 392 393 394 395 396 397 398
		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
399
			this._stopWorkerSync(modelData);
A
Alex Dima 已提交
400 401 402 403 404 405 406 407
		}

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

		this._onModelRemoved.fire(model);
	}

A
Alex Dima 已提交
408
	private static _getBoundModelData(model:editorCommon.IModel): IRawModelData {
E
Erich Gamma 已提交
409 410 411 412 413 414 415 416
		return {
			url: model.getAssociatedResource(),
			versionId: model.getVersionId(),
			value: model.toRawText(),
			modeId: model.getMode().getId()
		};
	}

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

419
		// First look for dispose
A
Alex Dima 已提交
420 421
		for (let i = 0, len = events.length; i < len; i++) {
			let e = events[i];
A
Alex Dima 已提交
422
			if (e.getType() === editorCommon.EventType.ModelDispose) {
423 424 425 426 427
				this._onModelDisposing(modelData.model);
				// no more processing since model got disposed
				return;
			}
		}
E
Erich Gamma 已提交
428

429 430 431
		// Second, look for mode change
		for (let i = 0, len = events.length; i < len; i++) {
			let e = events[i];
A
Alex Dima 已提交
432
			if (e.getType() === editorCommon.EventType.ModelModeChanged) {
433 434
				let wasSyncedToWorkers = modelData.isSyncedToWorkers;
				let shouldSyncToWorkers = this._shouldSyncModelToWorkers(modelData.model);
E
Erich Gamma 已提交
435

436 437
				this._onModelModeChanged.fire({
					model: modelData.model,
A
Alex Dima 已提交
438
					oldModeId: (<editorCommon.IModelModeChangedEvent>e.getData()).oldMode.getId()
439 440
				});

441 442 443
				if (wasSyncedToWorkers) {
					if (shouldSyncToWorkers) {
						// true -> true
A
Alex Dima 已提交
444
						// Forward mode change to all the workers
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
						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 已提交
464
					}
465 466 467 468 469 470 471 472 473 474 475 476 477
				}
			}
		}

		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 已提交
478 479
			if (e.getType() === editorCommon.EventType.ModelContentChanged) {
				eventsForWorkers.contentChanged.push(<editorCommon.IModelContentChangedEvent>e.getData());
E
Erich Gamma 已提交
480 481 482
			}
		}

A
Alex Dima 已提交
483
		if (eventsForWorkers.contentChanged.length > 0) {
E
Erich Gamma 已提交
484
			// Forward events to all the workers
A
Alex Dima 已提交
485
			this._workerHelper.$_acceptModelEvents(modelData.getModelId(), eventsForWorkers);
E
Erich Gamma 已提交
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
		}
	}
}

@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 已提交
504
	public $_acceptNewModel(data:IRawModelData): TPromise<void> {
E
Erich Gamma 已提交
505
		// Create & insert the mirror model eagerly in the resource service
A
Alex Dima 已提交
506
		let mirrorModel = new MirrorModel(this._resourceService, data.versionId, data.value, null, data.url);
E
Erich Gamma 已提交
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
		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);
		});
	}

524
	public $_acceptDidChangeModelMode(modelId:string, newModeId:string): TPromise<void> {
A
Alex Dima 已提交
525
		let mirrorModel = this._resourceService.get(URI.parse(modelId));
E
Erich Gamma 已提交
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541

		// 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 已提交
542
	public $_acceptDidDisposeModel(url:URI): void {
A
Alex Dima 已提交
543
		let model = <MirrorModel>this._resourceService.get(url);
E
Erich Gamma 已提交
544 545 546 547 548 549
		this._resourceService.remove(url);
		if (model) {
			model.dispose();
		}
	}

A
Alex Dima 已提交
550
	public $_acceptModelEvents(modelId: string, events:IMirrorModelEvents): void {
J
Johannes Rieken 已提交
551
		let model = <MirrorModel>this._resourceService.get(URI.parse(modelId));
A
Alex Dima 已提交
552 553 554 555 556 557
		if (!model) {
			throw new Error('Received model events for missing model ' + anonymize(modelId));
		}
		try {
			model.onEvents(events);
		} catch (err) {
A
Alex Dima 已提交
558
			onUnexpectedError(err);
E
Erich Gamma 已提交
559 560 561
		}
	}
}