modelServiceImpl.ts 20.9 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
import * as nls from 'vs/nls';
A
Alex Dima 已提交
8 9
import {onUnexpectedError} from 'vs/base/common/errors';
import Event, {Emitter} from 'vs/base/common/event';
E
Erich Gamma 已提交
10 11
import {IEmitterEvent} from 'vs/base/common/eventEmitter';
import {IHTMLContentElement} from 'vs/base/common/htmlContent';
A
tslint  
Alex Dima 已提交
12
import {IDisposable} from 'vs/base/common/lifecycle';
A
Alex Dima 已提交
13 14
import Severity from 'vs/base/common/severity';
import URI from 'vs/base/common/uri';
E
Erich Gamma 已提交
15
import {TPromise} from 'vs/base/common/winjs.base';
A
Alex Dima 已提交
16
import {IMarker, IMarkerService} from 'vs/platform/markers/common/markers';
E
Erich Gamma 已提交
17
import {anonymize} from 'vs/platform/telemetry/common/telemetry';
A
Alex Dima 已提交
18 19 20 21
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 已提交
22
import {Model} from 'vs/editor/common/model/model';
A
Alex Dima 已提交
23 24 25 26
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';
27
import * as platform from 'vs/base/common/platform';
28
import {IConfigurationService, ConfigurationServiceEventTypes, IConfigurationServiceEvent} from 'vs/platform/configuration/common/configuration';
29
import {DEFAULT_INDENTATION} from 'vs/editor/common/config/defaultConfig';
A
Alex Dima 已提交
30
import {IMessageService} from 'vs/platform/message/common/message';
E
Erich Gamma 已提交
31 32

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

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

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

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

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

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

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

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

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

A
Alex Dima 已提交
74 75 76
class ModelMarkerHandler {

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

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

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

		modelData.acceptMarkerDecorations(newModelDecorations);
E
Erich Gamma 已提交
89 90
	}

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

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

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

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

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

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

175 176 177 178 179 180 181 182 183 184 185
interface IRawConfig {
	files?: {
		eol?: any;
	};
	editor?: {
		tabSize?: any;
		insertSpaces?: any;
		detectIndentation?: any;
	};
}

E
Erich Gamma 已提交
186 187 188 189 190 191
export class ModelServiceImpl implements IModelService {
	public serviceId = IModelService;

	private _markerService: IMarkerService;
	private _markerServiceSubscription: IDisposable;
	private _threadService: IThreadService;
192
	private _modeService: IModeService;
A
Alex Dima 已提交
193
	private _messageService: IMessageService;
194 195
	private _configurationService: IConfigurationService;
	private _configurationServiceSubscription: IDisposable;
E
Erich Gamma 已提交
196 197
	private _workerHelper: ModelServiceWorkerHelper;

A
Alex Dima 已提交
198 199 200
	private _onModelAdded: Emitter<editorCommon.IModel>;
	private _onModelRemoved: Emitter<editorCommon.IModel>;
	private _onModelModeChanged: Emitter<{ model: editorCommon.IModel; oldModeId: string; }>;
201 202

	private _modelCreationOptions: editorCommon.ITextModelCreationOptions;
A
Alex Dima 已提交
203

A
Alex Dima 已提交
204 205
	private _hasShownMigrationMessage: boolean;

A
Alex Dima 已提交
206 207 208 209
	/**
	 * All the models known in the system.
	 */
	private _models: {[modelId:string]:ModelData;};
E
Erich Gamma 已提交
210

211 212 213 214
	constructor(
		threadService: IThreadService,
		markerService: IMarkerService,
		modeService: IModeService,
A
Alex Dima 已提交
215 216
		configurationService: IConfigurationService,
		messageService: IMessageService
217
	) {
218
		this._modelCreationOptions = {
219 220 221
			tabSize: DEFAULT_INDENTATION.tabSize,
			insertSpaces: DEFAULT_INDENTATION.insertSpaces,
			detectIndentation: DEFAULT_INDENTATION.detectIndentation,
222 223
			defaultEOL: (platform.isLinux || platform.isMacintosh) ? editorCommon.DefaultEndOfLine.LF : editorCommon.DefaultEndOfLine.CRLF
		};
E
Erich Gamma 已提交
224 225
		this._threadService = threadService;
		this._markerService = markerService;
226
		this._modeService = modeService;
E
Erich Gamma 已提交
227
		this._workerHelper = this._threadService.getRemotable(ModelServiceWorkerHelper);
228
		this._configurationService = configurationService;
A
Alex Dima 已提交
229 230
		this._messageService = messageService;
		this._hasShownMigrationMessage = false;
231

232
		let readConfig = (config:IRawConfig) => {
J
Joao Moreno 已提交
233 234
			const eol = config.files && config.files.eol;

A
Alex Dima 已提交
235 236
			let shouldShowMigrationMessage = false;

237
			let tabSize = DEFAULT_INDENTATION.tabSize;
238 239 240
			if (config.editor && typeof config.editor.tabSize !== 'undefined') {
				let parsedTabSize = parseInt(config.editor.tabSize, 10);
				if (!isNaN(parsedTabSize)) {
241
					tabSize = parsedTabSize;
242
				}
A
Alex Dima 已提交
243
				shouldShowMigrationMessage = shouldShowMigrationMessage || (config.editor.tabSize === 'auto');
244 245
			}

246
			let insertSpaces = DEFAULT_INDENTATION.insertSpaces;
247
			if (config.editor && typeof config.editor.insertSpaces !== 'undefined') {
248
				insertSpaces = (config.editor.insertSpaces === 'false' ? false : Boolean(config.editor.insertSpaces));
A
Alex Dima 已提交
249
				shouldShowMigrationMessage = shouldShowMigrationMessage || (config.editor.insertSpaces === 'auto');
250 251 252
			}

			let newDefaultEOL = this._modelCreationOptions.defaultEOL;
J
Joao Moreno 已提交
253
			if (eol === '\r\n') {
254
				newDefaultEOL = editorCommon.DefaultEndOfLine.CRLF;
J
Joao Moreno 已提交
255
			} else if (eol === '\n') {
256
				newDefaultEOL = editorCommon.DefaultEndOfLine.LF;
257
			}
258

259
			let detectIndentation = DEFAULT_INDENTATION.detectIndentation;
260 261 262
			if (config.editor && typeof config.editor.detectIndentation !== 'undefined') {
				detectIndentation = (config.editor.detectIndentation === 'false' ? false : Boolean(config.editor.detectIndentation));
			}
263

264 265 266
			this._setModelOptions({
				tabSize: tabSize,
				insertSpaces: insertSpaces,
267
				detectIndentation: detectIndentation,
268
				defaultEOL: newDefaultEOL
269 270
			});

A
Alex Dima 已提交
271 272 273 274 275

			if (shouldShowMigrationMessage && !this._hasShownMigrationMessage) {
				this._hasShownMigrationMessage = true;
				this._messageService.show(Severity.Info, nls.localize('indentAutoMigrate', "Please update your settings: `editor.detectIndentation` replaces `editor.tabSize`: \"auto\" or `editor.insertSpaces`: \"auto\""));
			}
276 277
		};
		this._configurationServiceSubscription = this._configurationService.addListener2(ConfigurationServiceEventTypes.UPDATED, (e: IConfigurationServiceEvent) => {
278
			readConfig(e.config);
279 280
		});
		this._configurationService.loadConfiguration().then((config) => {
281
			readConfig(config);
282
		});
E
Erich Gamma 已提交
283 284 285

		this._models = {};

A
Alex Dima 已提交
286 287 288
		this._onModelAdded = new Emitter<editorCommon.IModel>();
		this._onModelRemoved = new Emitter<editorCommon.IModel>();
		this._onModelModeChanged = new Emitter<{ model: editorCommon.IModel; oldModeId: string; }>();
E
Erich Gamma 已提交
289 290 291 292 293 294

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

295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
	public getCreationOptions(): editorCommon.ITextModelCreationOptions {
		return this._modelCreationOptions;
	}

	private _setModelOptions(newOpts: editorCommon.ITextModelCreationOptions): void {
		if (
			(this._modelCreationOptions.detectIndentation === newOpts.detectIndentation)
			&& (this._modelCreationOptions.insertSpaces === newOpts.insertSpaces)
			&& (this._modelCreationOptions.tabSize === newOpts.tabSize)
		) {
			// Same indent opts, no need to touch created models
			this._modelCreationOptions = newOpts;
			return;
		}
		this._modelCreationOptions = newOpts;

311
		// Update options on all models
A
Alex Dima 已提交
312 313 314 315
		let keys = Object.keys(this._models);
		for (let i = 0, len = keys.length; i < len; i++) {
			let modelId = keys[i];
			let modelData = this._models[modelId];
316

A
Alex Dima 已提交
317 318 319 320 321 322 323
			if (this._modelCreationOptions.detectIndentation) {
				modelData.model.detectIndentation(this._modelCreationOptions.insertSpaces, this._modelCreationOptions.tabSize);
			} else {
				modelData.model.updateOptions({
					insertSpaces: this._modelCreationOptions.insertSpaces,
					tabSize:  this._modelCreationOptions.tabSize
				});
324 325
			}
		}
326 327
	}

E
Erich Gamma 已提交
328 329 330 331
	public dispose(): void {
		if(this._markerServiceSubscription) {
			this._markerServiceSubscription.dispose();
		}
332
		this._configurationServiceSubscription.dispose();
E
Erich Gamma 已提交
333 334 335
	}

	private _handleMarkerChange(changedResources: URI[]): void {
A
Alex Dima 已提交
336 337 338 339
		changedResources.forEach((resource) => {
			let modelId = MODEL_ID(resource);
			let modelData = this._models[modelId];
			if (!modelData) {
E
Erich Gamma 已提交
340 341
				return;
			}
A
Alex Dima 已提交
342
			ModelMarkerHandler.setMarkers(modelData, this._markerService.read({ resource: resource, take: 500 }));
E
Erich Gamma 已提交
343 344 345 346 347
		});
	}

	// --- begin IModelService

A
Alex Dima 已提交
348
	private _shouldSyncModelToWorkers(model:editorCommon.IModel): boolean {
349 350 351 352 353 354 355
		if (model.isTooLargeForHavingARichMode()) {
			return false;
		}
		// Only sync models with compat modes to the workers
		return this._modeService.isCompatMode(model.getMode().getId());
	}

A
Alex Dima 已提交
356
	private _createModelData(value:string, modeOrPromise:TPromise<IMode>|IMode, resource: URI): ModelData {
A
Alex Dima 已提交
357
		// create & save the model
358
		let model = new Model(value, this._modelCreationOptions, modeOrPromise, resource);
A
Alex Dima 已提交
359
		let modelId = MODEL_ID(model.getAssociatedResource());
E
Erich Gamma 已提交
360 361 362

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

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

A
Alex Dima 已提交
369
		return modelData;
E
Erich Gamma 已提交
370 371
	}

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

A
Alex Dima 已提交
375 376 377
		// handle markers (marker service => model)
		if (this._markerService) {
			ModelMarkerHandler.setMarkers(modelData, this._markerService.read({ resource: modelData.model.getAssociatedResource() }));
E
Erich Gamma 已提交
378 379
		}

380
		if (this._shouldSyncModelToWorkers(modelData.model)) {
A
Alex Dima 已提交
381
			// send this model to the workers
382
			this._beginWorkerSync(modelData);
E
Erich Gamma 已提交
383 384
		}

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

A
Alex Dima 已提交
387
		return modelData.model;
E
Erich Gamma 已提交
388 389
	}

J
Johannes Rieken 已提交
390
	public destroyModel(resource: URI): void {
A
Alex Dima 已提交
391 392 393 394
		// 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 已提交
395
		}
A
Alex Dima 已提交
396
		modelData.model.dispose();
E
Erich Gamma 已提交
397 398
	}

A
Alex Dima 已提交
399 400
	public getModels(): editorCommon.IModel[] {
		let ret: editorCommon.IModel[] = [];
A
Alex Dima 已提交
401 402 403 404 405

		let keys = Object.keys(this._models);
		for (let i = 0, len = keys.length; i < len; i++) {
			let modelId = keys[i];
			ret.push(this._models[modelId].model);
E
Erich Gamma 已提交
406
		}
A
Alex Dima 已提交
407

E
Erich Gamma 已提交
408 409 410
		return ret;
	}

A
Alex Dima 已提交
411
	public getModel(resource: URI): editorCommon.IModel {
A
Alex Dima 已提交
412 413 414 415
		let modelId = MODEL_ID(resource);
		let modelData = this._models[modelId];
		if (!modelData) {
			return null;
E
Erich Gamma 已提交
416
		}
A
Alex Dima 已提交
417
		return modelData.model;
E
Erich Gamma 已提交
418 419
	}

A
Alex Dima 已提交
420
	public get onModelAdded(): Event<editorCommon.IModel> {
421
		return this._onModelAdded ? this._onModelAdded.event : null;
E
Erich Gamma 已提交
422 423
	}

A
Alex Dima 已提交
424
	public get onModelRemoved(): Event<editorCommon.IModel> {
425
		return this._onModelRemoved ? this._onModelRemoved.event : null;
E
Erich Gamma 已提交
426 427
	}

A
Alex Dima 已提交
428
	public get onModelModeChanged(): Event<{ model: editorCommon.IModel; oldModeId: string; }> {
429
		return this._onModelModeChanged ? this._onModelModeChanged.event : null;
E
Erich Gamma 已提交
430 431 432 433
	}

	// --- end IModelService

434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
	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 已提交
451
	private _onModelDisposing(model:editorCommon.IModel): void {
A
Alex Dima 已提交
452 453 454 455 456 457 458 459 460 461 462 463 464 465
		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
466
			this._stopWorkerSync(modelData);
A
Alex Dima 已提交
467 468 469 470 471 472 473 474
		}

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

		this._onModelRemoved.fire(model);
	}

A
Alex Dima 已提交
475
	private static _getBoundModelData(model:editorCommon.IModel): IRawModelData {
E
Erich Gamma 已提交
476 477 478 479 480 481 482 483
		return {
			url: model.getAssociatedResource(),
			versionId: model.getVersionId(),
			value: model.toRawText(),
			modeId: model.getMode().getId()
		};
	}

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

486
		// First look for dispose
A
Alex Dima 已提交
487 488
		for (let i = 0, len = events.length; i < len; i++) {
			let e = events[i];
A
Alex Dima 已提交
489
			if (e.getType() === editorCommon.EventType.ModelDispose) {
490 491 492 493 494
				this._onModelDisposing(modelData.model);
				// no more processing since model got disposed
				return;
			}
		}
E
Erich Gamma 已提交
495

496 497 498
		// Second, look for mode change
		for (let i = 0, len = events.length; i < len; i++) {
			let e = events[i];
A
Alex Dima 已提交
499
			if (e.getType() === editorCommon.EventType.ModelModeChanged) {
500 501
				let wasSyncedToWorkers = modelData.isSyncedToWorkers;
				let shouldSyncToWorkers = this._shouldSyncModelToWorkers(modelData.model);
E
Erich Gamma 已提交
502

503 504
				this._onModelModeChanged.fire({
					model: modelData.model,
A
Alex Dima 已提交
505
					oldModeId: (<editorCommon.IModelModeChangedEvent>e.getData()).oldMode.getId()
506 507
				});

508 509 510
				if (wasSyncedToWorkers) {
					if (shouldSyncToWorkers) {
						// true -> true
A
Alex Dima 已提交
511
						// Forward mode change to all the workers
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
						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 已提交
531
					}
532 533 534 535 536 537 538 539 540 541 542 543 544
				}
			}
		}

		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 已提交
545 546
			if (e.getType() === editorCommon.EventType.ModelContentChanged) {
				eventsForWorkers.contentChanged.push(<editorCommon.IModelContentChangedEvent>e.getData());
E
Erich Gamma 已提交
547 548 549
			}
		}

A
Alex Dima 已提交
550
		if (eventsForWorkers.contentChanged.length > 0) {
E
Erich Gamma 已提交
551
			// Forward events to all the workers
A
Alex Dima 已提交
552
			this._workerHelper.$_acceptModelEvents(modelData.getModelId(), eventsForWorkers);
E
Erich Gamma 已提交
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
		}
	}
}

@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 已提交
571
	public $_acceptNewModel(data:IRawModelData): TPromise<void> {
E
Erich Gamma 已提交
572
		// Create & insert the mirror model eagerly in the resource service
A
Alex Dima 已提交
573
		let mirrorModel = new MirrorModel(this._resourceService, data.versionId, data.value, null, data.url);
E
Erich Gamma 已提交
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
		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);
		});
	}

591
	public $_acceptDidChangeModelMode(modelId:string, newModeId:string): TPromise<void> {
A
Alex Dima 已提交
592
		let mirrorModel = this._resourceService.get(URI.parse(modelId));
E
Erich Gamma 已提交
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608

		// 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 已提交
609
	public $_acceptDidDisposeModel(url:URI): void {
A
Alex Dima 已提交
610
		let model = <MirrorModel>this._resourceService.get(url);
E
Erich Gamma 已提交
611 612 613 614 615 616
		this._resourceService.remove(url);
		if (model) {
			model.dispose();
		}
	}

A
Alex Dima 已提交
617
	public $_acceptModelEvents(modelId: string, events:IMirrorModelEvents): void {
J
Johannes Rieken 已提交
618
		let model = <MirrorModel>this._resourceService.get(URI.parse(modelId));
A
Alex Dima 已提交
619 620 621 622 623 624
		if (!model) {
			throw new Error('Received model events for missing model ' + anonymize(modelId));
		}
		try {
			model.onEvents(events);
		} catch (err) {
A
Alex Dima 已提交
625
			onUnexpectedError(err);
E
Erich Gamma 已提交
626 627 628
		}
	}
}