commonCodeEditor.ts 31.2 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';

7
import * as nls from 'vs/nls';
A
Alex Dima 已提交
8
import {IAction, IActionProvider, isAction} from 'vs/base/common/actions';
9
import {onUnexpectedError} from 'vs/base/common/errors';
A
Alex Dima 已提交
10
import {EventEmitter, IEventEmitter, ListenerUnbind} from 'vs/base/common/eventEmitter';
J
Joao Moreno 已提交
11
import {IDisposable, dispose} from 'vs/base/common/lifecycle';
A
Alex Dima 已提交
12 13 14
import * as objects from 'vs/base/common/objects';
import * as timer from 'vs/base/common/timer';
import {TPromise} from 'vs/base/common/winjs.base';
15
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
16
import {ServiceCollection} from 'vs/platform/instantiation/common/serviceCollection';
A
Alex Dima 已提交
17 18
import {IKeybindingContextKey, IKeybindingScopeLocation, IKeybindingService} from 'vs/platform/keybinding/common/keybindingService';
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
19
import {CommonEditorConfiguration} from 'vs/editor/common/config/commonEditorConfig';
A
Alex Dima 已提交
20
import {DefaultConfig} from 'vs/editor/common/config/defaultConfig';
21 22 23
import {Cursor} from 'vs/editor/common/controller/cursor';
import {CursorMoveHelper} from 'vs/editor/common/controller/cursorMoveHelper';
import {IViewModelHelper} from 'vs/editor/common/controller/oneCursor';
A
Alex Dima 已提交
24
import {EditorState} from 'vs/editor/common/core/editorState';
25
import {Position} from 'vs/editor/common/core/position';
A
Alex Dima 已提交
26
import {Range} from 'vs/editor/common/core/range';
27
import {Selection} from 'vs/editor/common/core/selection';
A
Alex Dima 已提交
28 29 30 31 32
import {DynamicEditorAction} from 'vs/editor/common/editorAction';
import * as editorCommon from 'vs/editor/common/editorCommon';
import {ICodeEditorService} from 'vs/editor/common/services/codeEditorService';
import {CharacterHardWrappingLineMapperFactory} from 'vs/editor/common/viewModel/characterHardWrappingLineMapper';
import {SplitLinesCollection} from 'vs/editor/common/viewModel/splitLinesCollection';
33
import {ViewModel} from 'vs/editor/common/viewModel/viewModelImpl';
34 35 36

var EDITOR_ID = 0;

A
Alex Dima 已提交
37
export abstract class CommonCodeEditor extends EventEmitter implements IActionProvider, editorCommon.ICommonCodeEditor {
38 39 40 41 42 43 44 45 46 47

	protected domElement: IKeybindingScopeLocation;

	protected id:number;

	_lifetimeDispose: IDisposable[];
	_configuration:CommonEditorConfiguration;

	_telemetryService:ITelemetryService;

A
Alex Dima 已提交
48
	protected contributions:{ [key:string]:editorCommon.IEditorContribution; };
49 50

	// --- Members logically associated to a model
A
Alex Dima 已提交
51 52
	protected model:editorCommon.IModel;
	protected listenersToRemove:ListenerUnbind[];
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
	protected hasView: boolean;

	protected viewModel:ViewModel;
	protected cursor:Cursor;

	protected _instantiationService: IInstantiationService;
	protected _keybindingService: IKeybindingService;

	private _decorationTypeKeysToIds: {[decorationTypeKey:string]:string[];};

	private _codeEditorService: ICodeEditorService;
	private _editorIdContextKey: IKeybindingContextKey<string>;
	protected _editorFocusContextKey: IKeybindingContextKey<boolean>;
	private _editorTabMovesFocusKey: IKeybindingContextKey<boolean>;
	private _hasMultipleSelectionsKey: IKeybindingContextKey<boolean>;
	private _hasNonEmptySelectionKey: IKeybindingContextKey<boolean>;
	private _langIdKey: IKeybindingContextKey<string>;

	constructor(
		domElement: IKeybindingScopeLocation,
73
		options:editorCommon.IEditorOptions,
74 75 76 77 78 79 80
		instantiationService: IInstantiationService,
		codeEditorService: ICodeEditorService,
		keybindingService: IKeybindingService,
		telemetryService: ITelemetryService
	) {
		super();

A
Alex Dima 已提交
81 82
		this.domElement = domElement;

83 84 85
		this.id = (++EDITOR_ID);
		this._codeEditorService = codeEditorService;

A
Alex Dima 已提交
86
		var timerEvent = timer.start(timer.Topic.EDITOR, 'CodeEditor.ctor');
87 88 89 90 91

		this._lifetimeDispose = [];

		this._keybindingService = keybindingService.createScoped(domElement);
		this._editorIdContextKey = this._keybindingService.createKey('editorId', this.getId());
A
Alex Dima 已提交
92 93 94 95 96
		this._editorFocusContextKey = this._keybindingService.createKey(editorCommon.KEYBINDING_CONTEXT_EDITOR_FOCUS, undefined);
		this._editorTabMovesFocusKey = this._keybindingService.createKey(editorCommon.KEYBINDING_CONTEXT_EDITOR_TAB_MOVES_FOCUS, false);
		this._hasMultipleSelectionsKey = this._keybindingService.createKey(editorCommon.KEYBINDING_CONTEXT_EDITOR_HAS_MULTIPLE_SELECTIONS, false);
		this._hasNonEmptySelectionKey = this._keybindingService.createKey(editorCommon.KEYBINDING_CONTEXT_EDITOR_HAS_NON_EMPTY_SELECTION, false);
		this._langIdKey = this._keybindingService.createKey<string>(editorCommon.KEYBINDING_CONTEXT_EDITOR_LANGUAGE_ID, undefined);
97 98 99 100 101

		// listeners that are kept during the whole editor lifetime
		this._decorationTypeKeysToIds = {};

		options = options || {};
102 103 104 105 106
		if (typeof options.ariaLabel === 'undefined') {
			options.ariaLabel = DefaultConfig.editor.ariaLabel;
		}
		options.ariaLabel += this._ariaLabelAppendMessage();

107
		this._configuration = this._createConfiguration(options);
108 109 110
		if (this._configuration.editor.tabFocusMode) {
			this._editorTabMovesFocusKey.set(true);
		}
A
Alex Dima 已提交
111
		this._lifetimeDispose.push(this._configuration.onDidChange((e) => this.emit(editorCommon.EventType.ConfigurationChanged, e)));
112 113

		this._telemetryService = telemetryService;
114
		this._instantiationService = instantiationService.createChild(new ServiceCollection([IKeybindingService, this._keybindingService]));
115

116
		this._attachModel(null);
117 118 119 120 121 122 123 124 125 126

		// Create editor contributions
		this.contributions = {};


		timerEvent.stop();

		this._codeEditorService.addCodeEditor(this);
	}

127
	protected abstract _createConfiguration(options:editorCommon.ICodeEditorWidgetCreationOptions): CommonEditorConfiguration;
128 129 130 131 132 133

	public getId(): string {
		return this.getEditorType() + ':' + this.id;
	}

	public getEditorType(): string {
A
Alex Dima 已提交
134
		return editorCommon.EditorType.ICodeEditor;
135 136 137 138 139 140 141 142
	}

	public destroy(): void {
		this.dispose();
	}

	public dispose(): void {
		this._codeEditorService.removeCodeEditor(this);
J
Joao Moreno 已提交
143
		this._lifetimeDispose = dispose(this._lifetimeDispose);
144

A
Alex Dima 已提交
145 146 147 148
		let keys = Object.keys(this.contributions);
		for (let i = 0, len = keys.length; i < len; i++) {
			let contributionId = keys[i];
			this.contributions[contributionId].dispose();
149
		}
A
Alex Dima 已提交
150

151 152 153 154 155
		this.contributions = {};

		this._postDetachModelCleanup(this._detachModel());
		this._configuration.dispose();
		this._keybindingService.dispose();
A
Alex Dima 已提交
156
		this.emit(editorCommon.EventType.Disposed, {});
157 158 159
		super.dispose();
	}

A
Alex Dima 已提交
160
	public captureState(...flags:editorCommon.CodeEditorStateFlag[]): editorCommon.ICodeEditorState {
161 162 163
		return new EditorState(this, flags);
	}

164
	private _ariaLabelAppendMessage(): string {
A
Alex Dima 已提交
165
		let keybindings = this._keybindingService.lookupKeybindings(editorCommon.SHOW_ACCESSIBILITY_HELP_ACTION_ID);
166
		if (keybindings.length > 0) {
167
			return nls.localize('showAccessibilityHelp', "Press {0} if you are using a screen reader.", this._keybindingService.getAriaLabelFor(keybindings[0]));
168 169 170 171
		}
		return '';
	}

A
Alex Dima 已提交
172
	public updateOptions(newOptions:editorCommon.IEditorOptions): void {
173 174 175
		if (typeof newOptions.ariaLabel !== 'undefined') {
			newOptions.ariaLabel += this._ariaLabelAppendMessage();
		}
176 177 178 179 180 181 182 183
		this._configuration.updateOptions(newOptions);
		if (this._configuration.editor.tabFocusMode) {
			this._editorTabMovesFocusKey.set(true);
		} else {
			this._editorTabMovesFocusKey.reset();
		}
	}

184
	public getConfiguration(): editorCommon.InternalEditorOptions {
A
Alex Dima 已提交
185
		return this._configuration.editorClone;
186 187
	}

A
Alex Dima 已提交
188
	public getRawConfiguration(): editorCommon.IEditorOptions {
189 190 191 192 193 194
		return this._configuration.getRawOptions();
	}

	public getValue(options:{ preserveBOM:boolean; lineEnding:string; }=null): string {
		if (this.model) {
			var preserveBOM:boolean = (options && options.preserveBOM) ? true : false;
A
Alex Dima 已提交
195
			var eolPreference = editorCommon.EndOfLinePreference.TextDefined;
196
			if (options && options.lineEnding && options.lineEnding === '\n') {
A
Alex Dima 已提交
197
				eolPreference = editorCommon.EndOfLinePreference.LF;
198
			} else if (options  && options.lineEnding && options.lineEnding === '\r\n') {
A
Alex Dima 已提交
199
				eolPreference = editorCommon.EndOfLinePreference.CRLF;
200 201 202 203 204 205 206 207 208 209 210 211
			}
			return this.model.getValue(eolPreference, preserveBOM);
		}
		return '';
	}

	public setValue(newValue:string): void {
		if (this.model) {
			this.model.setValue(newValue);
		}
	}

A
Alex Dima 已提交
212
	public getModel(): editorCommon.IModel {
213 214 215
		return this.model;
	}

A
Alex Dima 已提交
216
	public setModel(model:editorCommon.IModel = null): void {
217 218 219 220 221
		if (this.model === model) {
			// Current model is the new model
			return;
		}

A
Alex Dima 已提交
222
		var timerEvent = timer.start(timer.Topic.EDITOR, 'CodeEditor.setModel');
223 224 225 226 227 228 229 230 231 232 233 234 235

		var detachedModel = this._detachModel();
		this._attachModel(model);

		var oldModelUrl: string = null;
		var newModelUrl: string = null;

		if (detachedModel) {
			oldModelUrl = detachedModel.getAssociatedResource().toString();
		}
		if (model) {
			newModelUrl = model.getAssociatedResource().toString();
		}
A
Alex Dima 已提交
236
		var e: editorCommon.IModelChangedEvent = {
237 238 239 240 241 242
			oldModelUrl: oldModelUrl,
			newModelUrl: newModelUrl
		};

		timerEvent.stop();

A
Alex Dima 已提交
243
		this.emit(editorCommon.EventType.ModelChanged, e);
244 245 246
		this._postDetachModelCleanup(detachedModel);
	}

A
Alex Dima 已提交
247
	public abstract getCenteredRangeInViewport(): editorCommon.IEditorRange;
248

A
Alex Dima 已提交
249
	public getVisibleColumnFromPosition(rawPosition:editorCommon.IPosition): number {
250 251 252 253
		if (!this.model) {
			return rawPosition.column;
		}

254 255
		let position = this.model.validatePosition(rawPosition);
		let tabSize = this.model.getOptions().tabSize;
256

257
		return CursorMoveHelper.visibleColumnFromColumn(this.model, position.lineNumber, position.column, tabSize) + 1;
258 259
	}

A
Alex Dima 已提交
260
	public getPosition(): editorCommon.IEditorPosition {
261 262 263 264 265 266
		if (!this.cursor) {
			return null;
		}
		return this.cursor.getPosition().clone();
	}

A
Alex Dima 已提交
267
	public setPosition(position:editorCommon.IPosition, reveal:boolean = false, revealVerticalInCenter:boolean = false, revealHorizontal:boolean = false): void {
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
		if (!this.cursor) {
			return;
		}
		if (!Position.isIPosition(position)) {
			throw new Error('Invalid arguments');
		}
		this.cursor.setSelections('api', [{
			selectionStartLineNumber: position.lineNumber,
			selectionStartColumn: position.column,
			positionLineNumber: position.lineNumber,
			positionColumn: position.column
		}]);
		if (reveal) {
			this.revealPosition(position, revealVerticalInCenter, revealHorizontal);
		}
	}

A
Alex Dima 已提交
285
	private _sendRevealRange(range: editorCommon.IRange, verticalType: editorCommon.VerticalRevealType, revealHorizontal: boolean): void {
286 287 288 289 290 291 292 293
		if (!this.model || !this.cursor) {
			return;
		}
		if (!Range.isIRange(range)) {
			throw new Error('Invalid arguments');
		}
		var validatedRange = this.model.validateRange(range);

A
Alex Dima 已提交
294
		var revealRangeEvent: editorCommon.ICursorRevealRangeEvent = {
295 296 297 298 299
			range: validatedRange,
			viewRange: null,
			verticalType: verticalType,
			revealHorizontal: revealHorizontal
		};
A
Alex Dima 已提交
300
		this.cursor.emit(editorCommon.EventType.CursorRevealRange, revealRangeEvent);
301 302 303 304 305 306 307 308
	}

	public revealLine(lineNumber: number): void {
		this._sendRevealRange({
			startLineNumber: lineNumber,
			startColumn: 1,
			endLineNumber: lineNumber,
			endColumn: 1
A
Alex Dima 已提交
309
		}, editorCommon.VerticalRevealType.Simple, false);
310 311 312 313 314 315 316 317
	}

	public revealLineInCenter(lineNumber: number): void {
		this._sendRevealRange({
			startLineNumber: lineNumber,
			startColumn: 1,
			endLineNumber: lineNumber,
			endColumn: 1
A
Alex Dima 已提交
318
		}, editorCommon.VerticalRevealType.Center, false);
319 320 321 322 323 324 325 326
	}

	public revealLineInCenterIfOutsideViewport(lineNumber: number): void {
		this._sendRevealRange({
			startLineNumber: lineNumber,
			startColumn: 1,
			endLineNumber: lineNumber,
			endColumn: 1
A
Alex Dima 已提交
327
		}, editorCommon.VerticalRevealType.CenterIfOutsideViewport, false);
328 329
	}

A
Alex Dima 已提交
330
	public revealPosition(position: editorCommon.IPosition, revealVerticalInCenter:boolean=false, revealHorizontal:boolean=false): void {
331 332 333 334 335 336 337 338
		if (!Position.isIPosition(position)) {
			throw new Error('Invalid arguments');
		}
		this._sendRevealRange({
			startLineNumber: position.lineNumber,
			startColumn: position.column,
			endLineNumber: position.lineNumber,
			endColumn: position.column
A
Alex Dima 已提交
339
		}, revealVerticalInCenter ? editorCommon.VerticalRevealType.Center : editorCommon.VerticalRevealType.Simple, revealHorizontal);
340 341
	}

A
Alex Dima 已提交
342
	public revealPositionInCenter(position: editorCommon.IPosition): void {
343 344 345 346 347 348 349 350
		if (!Position.isIPosition(position)) {
			throw new Error('Invalid arguments');
		}
		this._sendRevealRange({
			startLineNumber: position.lineNumber,
			startColumn: position.column,
			endLineNumber: position.lineNumber,
			endColumn: position.column
A
Alex Dima 已提交
351
		}, editorCommon.VerticalRevealType.Center, true);
352 353
	}

A
Alex Dima 已提交
354
	public revealPositionInCenterIfOutsideViewport(position: editorCommon.IPosition): void {
355 356 357 358 359 360 361 362
		if (!Position.isIPosition(position)) {
			throw new Error('Invalid arguments');
		}
		this._sendRevealRange({
			startLineNumber: position.lineNumber,
			startColumn: position.column,
			endLineNumber: position.lineNumber,
			endColumn: position.column
A
Alex Dima 已提交
363
		}, editorCommon.VerticalRevealType.CenterIfOutsideViewport, true);
364 365
	}

A
Alex Dima 已提交
366
	public getSelection(): editorCommon.IEditorSelection {
367 368 369 370 371 372
		if (!this.cursor) {
			return null;
		}
		return this.cursor.getSelection().clone();
	}

A
Alex Dima 已提交
373
	public getSelections(): editorCommon.IEditorSelection[] {
374 375 376 377
		if (!this.cursor) {
			return null;
		}
		var selections = this.cursor.getSelections();
A
Alex Dima 已提交
378
		var result:editorCommon.IEditorSelection[] = [];
379 380 381 382 383 384
		for (var i = 0, len = selections.length; i < len; i++) {
			result[i] = selections[i].clone();
		}
		return result;
	}

A
Alex Dima 已提交
385 386 387 388
	public setSelection(range:editorCommon.IRange, reveal?:boolean, revealVerticalInCenter?:boolean, revealHorizontal?:boolean): void;
	public setSelection(editorRange:editorCommon.IEditorRange, reveal?:boolean, revealVerticalInCenter?:boolean, revealHorizontal?:boolean): void;
	public setSelection(selection:editorCommon.ISelection, reveal?:boolean, revealVerticalInCenter?:boolean, revealHorizontal?:boolean): void;
	public setSelection(editorSelection:editorCommon.IEditorSelection, reveal?:boolean, revealVerticalInCenter?:boolean, revealHorizontal?:boolean): void;
389 390 391 392 393 394 395 396 397
	public setSelection(something:any, reveal:boolean = false, revealVerticalInCenter:boolean = false, revealHorizontal:boolean = false): void {
		var isSelection = Selection.isISelection(something);
		var isRange = Range.isIRange(something);

		if (!isSelection && !isRange) {
			throw new Error('Invalid arguments');
		}

		if (isSelection) {
A
Alex Dima 已提交
398
			this._setSelectionImpl(<editorCommon.ISelection>something, reveal, revealVerticalInCenter, revealHorizontal);
399 400
		} else if (isRange) {
			// act as if it was an IRange
A
Alex Dima 已提交
401
			var selection:editorCommon.ISelection = {
402 403 404 405 406 407 408 409 410
				selectionStartLineNumber: something.startLineNumber,
				selectionStartColumn: something.startColumn,
				positionLineNumber: something.endLineNumber,
				positionColumn: something.endColumn
			};
			this._setSelectionImpl(selection, reveal, revealVerticalInCenter, revealHorizontal);
		}
	}

A
Alex Dima 已提交
411
	private _setSelectionImpl(sel:editorCommon.ISelection, reveal:boolean, revealVerticalInCenter:boolean, revealHorizontal:boolean): void {
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
		if (!this.cursor) {
			return;
		}
		var selection = Selection.createSelection(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn);
		this.cursor.setSelections('api', [selection]);
		if (reveal) {
			this.revealRange(selection, revealVerticalInCenter, revealHorizontal);
		}
	}

	public revealLines(startLineNumber: number, endLineNumber: number): void {
		this._sendRevealRange({
			startLineNumber: startLineNumber,
			startColumn: 1,
			endLineNumber: endLineNumber,
			endColumn: 1
A
Alex Dima 已提交
428
		}, editorCommon.VerticalRevealType.Simple, false);
429 430 431 432 433 434 435 436
	}

	public revealLinesInCenter(startLineNumber: number, endLineNumber: number): void {
		this._sendRevealRange({
			startLineNumber: startLineNumber,
			startColumn: 1,
			endLineNumber: endLineNumber,
			endColumn: 1
A
Alex Dima 已提交
437
		}, editorCommon.VerticalRevealType.Center, false);
438 439 440 441 442 443 444 445
	}

	public revealLinesInCenterIfOutsideViewport(startLineNumber: number, endLineNumber: number): void {
		this._sendRevealRange({
			startLineNumber: startLineNumber,
			startColumn: 1,
			endLineNumber: endLineNumber,
			endColumn: 1
A
Alex Dima 已提交
446
		}, editorCommon.VerticalRevealType.CenterIfOutsideViewport, false);
447 448
	}

A
Alex Dima 已提交
449 450
	public revealRange(range: editorCommon.IRange, revealVerticalInCenter:boolean = false, revealHorizontal:boolean = true): void {
		this._sendRevealRange(range, revealVerticalInCenter ? editorCommon.VerticalRevealType.Center : editorCommon.VerticalRevealType.Simple, revealHorizontal);
451 452
	}

A
Alex Dima 已提交
453 454
	public revealRangeInCenter(range: editorCommon.IRange): void {
		this._sendRevealRange(range, editorCommon.VerticalRevealType.Center, true);
455 456
	}

A
Alex Dima 已提交
457 458
	public revealRangeInCenterIfOutsideViewport(range: editorCommon.IRange): void {
		this._sendRevealRange(range, editorCommon.VerticalRevealType.CenterIfOutsideViewport, true);
459 460
	}

A
Alex Dima 已提交
461
	public setSelections(ranges: editorCommon.ISelection[]): void {
462 463 464 465 466 467 468 469 470 471 472 473 474 475
		if (!this.cursor) {
			return;
		}
		if (!ranges || ranges.length === 0) {
			throw new Error('Invalid arguments');
		}
		for (var i = 0, len = ranges.length; i < len; i++) {
			if (!Selection.isISelection(ranges[i])) {
				throw new Error('Invalid arguments');
			}
		}
		this.cursor.setSelections('api', ranges);
	}

476 477
	public abstract getScrollWidth(): number;
	public abstract getScrollLeft(): number;
478

479
	public abstract getScrollHeight(): number;
480 481 482
	public abstract getScrollTop(): number;

	public abstract setScrollLeft(newScrollLeft:number): void;
483 484
	public abstract setScrollTop(newScrollTop:number): void;
	public abstract setScrollPosition(position: editorCommon.INewScrollPosition): void;
485

A
Alex Dima 已提交
486 487
	public abstract saveViewState(): editorCommon.ICodeEditorViewState;
	public abstract restoreViewState(state:editorCommon.IEditorViewState): void;
488 489 490 491 492 493 494

	public onVisible(): void {
	}

	public onHide(): void {
	}

A
Alex Dima 已提交
495
	public abstract layout(dimension?:editorCommon.IDimension): void;
496 497

	public abstract focus(): void;
498 499
	public abstract beginForcedWidgetFocus(): void;
	public abstract endForcedWidgetFocus(): void;
500
	public abstract isFocused(): boolean;
501 502
	public abstract hasWidgetFocus(): boolean;

A
Alex Dima 已提交
503
	public getContribution(id: string): editorCommon.IEditorContribution {
504 505 506
		return this.contributions[id] || null;
	}

A
Alex Dima 已提交
507
	public addAction(descriptor:editorCommon.IActionDescriptor): void {
508 509 510 511 512 513 514
		if (
			(typeof descriptor.id !== 'string')
			|| (typeof descriptor.label !== 'string')
			|| (typeof descriptor.run !== 'function')
		) {
			throw new Error('Invalid action descriptor, `id`, `label` and `run` are required properties!');
		}
515 516 517 518 519
		var action = this._instantiationService.createInstance(DynamicEditorAction, descriptor, this);
		this.contributions[action.getId()] = action;
	}

	public getActions(): IAction[] {
A
Alex Dima 已提交
520 521 522 523 524 525 526 527 528
		let result: IAction[] = [];

		let keys = Object.keys(this.contributions);
		for (let i = 0, len = keys.length; i < len; i++) {
			let id = keys[i];
			let contribution = <any>this.contributions[id];
			// contribution instanceof IAction
			if (isAction(contribution)) {
				result.push(<IAction>contribution);
529 530
			}
		}
A
Alex Dima 已提交
531

532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
		return result;
	}

	public getAction(id:string): IAction {
		var contribution = <any>this.contributions[id];
		if (contribution) {
			// contribution instanceof IAction
			if (isAction(contribution)) {
				return <IAction>contribution;
			}
		}
		return null;
	}

	public trigger(source:string, handlerId:string, payload:any): void {
547
		payload = payload || {};
548 549 550
		var candidate = this.getAction(handlerId);
		if(candidate !== null) {
			if (candidate.enabled) {
551
				this._telemetryService.publicLog('editorActionInvoked', {name: candidate.label, id: candidate.id} );
552 553 554
				TPromise.as(candidate.run()).done(null, onUnexpectedError);
			}
		} else {
A
Alex Dima 已提交
555 556
			if (!this.cursor) {
				return;
557
			}
A
Alex Dima 已提交
558
			this.cursor.trigger(source, handlerId, payload);
559 560 561
		}
	}

A
Alex Dima 已提交
562 563 564 565 566
	public executeCommand(source: string, command: editorCommon.ICommand): void {
		if (!this.cursor) {
			return;
		}
		this.cursor.trigger(source, editorCommon.Handler.ExecuteCommand, command);
567 568
	}

A
Alex Dima 已提交
569
	public executeEdits(source: string, edits: editorCommon.IIdentifiedSingleEditOperation[]): boolean {
570 571 572 573 574 575 576 577 578 579 580 581 582 583
		if (!this.cursor) {
			// no view, no cursor
			return false;
		}
		if (this._configuration.editor.readOnly) {
			// read only editor => sorry!
			return false;
		}
		this.model.pushEditOperations(this.cursor.getSelections(), edits, () => {
			return this.cursor.getSelections();
		});
		return true;
	}

A
Alex Dima 已提交
584 585 586 587 588
	public executeCommands(source: string, commands: editorCommon.ICommand[]): void {
		if (!this.cursor) {
			return;
		}
		this.cursor.trigger(source, editorCommon.Handler.ExecuteCommands, commands);
589 590
	}

A
Alex Dima 已提交
591
	public changeDecorations(callback:(changeAccessor:editorCommon.IModelDecorationsChangeAccessor)=>any): any {
592 593 594 595 596 597 598 599
		if (!this.model) {
//			console.warn('Cannot change decorations on editor that is not attached to a model');
			// callback will not be called
			return null;
		}
		return this.model.changeDecorations(callback, this.id);
	}

A
Alex Dima 已提交
600
	public getLineDecorations(lineNumber: number): editorCommon.IModelDecoration[] {
601 602 603 604 605 606
		if (!this.model) {
			return null;
		}
		return this.model.getLineDecorations(lineNumber, this.id, this._configuration.editor.readOnly);
	}

A
Alex Dima 已提交
607
	public deltaDecorations(oldDecorations:string[], newDecorations:editorCommon.IModelDeltaDecoration[]): string[] {
608 609 610 611 612 613 614 615 616 617 618
		if (!this.model) {
			return [];
		}

		if (oldDecorations.length === 0 && newDecorations.length === 0) {
			return oldDecorations;
		}

		return this.model.deltaDecorations(oldDecorations, newDecorations, this.id);
	}

A
Alex Dima 已提交
619
	public setDecorations(decorationTypeKey: string, ranges:editorCommon.IRangeWithMessage[]): void {
620 621
		var opts = this._codeEditorService.resolveDecorationType(decorationTypeKey);
		var oldDecorationIds = this._decorationTypeKeysToIds[decorationTypeKey] || [];
A
Alex Dima 已提交
622 623
		this._decorationTypeKeysToIds[decorationTypeKey] = this.deltaDecorations(oldDecorationIds, ranges.map((r) : editorCommon.IModelDeltaDecoration => {
			let decOpts: editorCommon.IModelDecorationOptions;
624
			if (r.hoverMessage) {
A
Alex Dima 已提交
625 626
				// TODO@Alex: avoid objects.clone
				decOpts = objects.clone(opts);
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
				decOpts.htmlMessage = r.hoverMessage;
			} else {
				decOpts = opts;
			}
			return {
				range: r.range,
				options: decOpts
			};
		}));
	}

	public removeDecorations(decorationTypeKey: string): void {
		if (this._decorationTypeKeysToIds.hasOwnProperty(decorationTypeKey)) {
			this.deltaDecorations(this._decorationTypeKeysToIds[decorationTypeKey], []);
			delete this._decorationTypeKeysToIds[decorationTypeKey];
		}
	}

A
Alex Dima 已提交
645
	public addTypingListener(character:string, callback: () => void): ListenerUnbind {
646 647 648 649 650 651 652 653 654 655 656 657 658
		if (!this.cursor) {
			return () => {
				// no-op
			};
		}
		this.cursor.addTypingListener(character, callback);
		return () => {
			if (this.cursor) {
				this.cursor.removeTypingListener(character, callback);
			}
		};
	}

659
	public getLayoutInfo(): editorCommon.EditorLayoutInfo {
660 661 662
		return this._configuration.editor.layoutInfo;
	}

A
Alex Dima 已提交
663
	_attachModel(model:editorCommon.IModel): void {
664 665 666 667 668 669 670 671 672 673 674 675 676 677
		this.model = model ? model : null;
		this.listenersToRemove = [];
		this.viewModel = null;
		this.cursor = null;

		if (this.model) {
			this.domElement.setAttribute('data-mode-id', this.model.getMode().getId());
			this._langIdKey.set(this.model.getMode().getId());
			this.model.setStopLineTokenizationAfter(this._configuration.editor.stopLineTokenizationAfter);
			this._configuration.setIsDominatedByLongLines(this.model.isDominatedByLongLines(this._configuration.editor.longLineBoundary));

			this.model.onBeforeAttached();

			var hardWrappingLineMapperFactory = new CharacterHardWrappingLineMapperFactory(
678 679 680
				this._configuration.editor.wrappingInfo.wordWrapBreakBeforeCharacters,
				this._configuration.editor.wrappingInfo.wordWrapBreakAfterCharacters,
				this._configuration.editor.wrappingInfo.wordWrapBreakObtrusiveCharacters
681 682 683 684 685
			);

			var linesCollection = new SplitLinesCollection(
				this.model,
				hardWrappingLineMapperFactory,
686
				this.model.getOptions().tabSize,
687
				this._configuration.editor.wrappingInfo.wrappingColumn,
688
				this._configuration.editor.fontInfo.typicalFullwidthCharacterWidth / this._configuration.editor.fontInfo.typicalHalfwidthCharacterWidth,
689
				this._configuration.editor.wrappingInfo.wrappingIndent
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
			);

			this.viewModel = new ViewModel(
				linesCollection,
				this.id,
				this._configuration,
				this.model,
				() => this.getCenteredRangeInViewport()
			);

			var viewModelHelper:IViewModelHelper = {
				viewModel: this.viewModel,
				convertModelPositionToViewPosition: (lineNumber:number, column:number) => {
					return this.viewModel.convertModelPositionToViewPosition(lineNumber, column);
				},
A
Alex Dima 已提交
705
				convertModelRangeToViewRange: (modelRange:editorCommon.IEditorRange) => {
706 707 708 709 710
					return this.viewModel.convertModelRangeToViewRange(modelRange);
				},
				convertViewToModelPosition: (lineNumber:number, column:number) => {
					return this.viewModel.convertViewPositionToModelPosition(lineNumber, column);
				},
A
Alex Dima 已提交
711 712 713
				convertViewSelectionToModelSelection: (viewSelection:editorCommon.ISelection) => {
					return this.viewModel.convertViewSelectionToModelSelection(viewSelection);
				},
A
Alex Dima 已提交
714
				validateViewPosition: (viewLineNumber:number, viewColumn:number, modelPosition:editorCommon.IEditorPosition) => {
715 716
					return this.viewModel.validateViewPosition(viewLineNumber, viewColumn, modelPosition);
				},
A
Alex Dima 已提交
717
				validateViewRange: (viewStartLineNumber:number, viewStartColumn:number, viewEndLineNumber:number, viewEndColumn:number, modelRange:editorCommon.IEditorRange) => {
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
					return this.viewModel.validateViewRange(viewStartLineNumber, viewStartColumn, viewEndLineNumber, viewEndColumn, modelRange);
				}
			};

			this.cursor = new Cursor(
				this.id,
				this._configuration,
				this.model,
				viewModelHelper,
				this._enableEmptySelectionClipboard()
			);

			this.viewModel.addEventSource(this.cursor);

			this._createView();

			this.listenersToRemove.push(this._getViewInternalEventBus().addBulkListener((events) => {
				for (var i = 0, len = events.length; i < len; i++) {
					var eventType = events[i].getType();
					var e = events[i].getData();

					switch (eventType) {
A
Alex Dima 已提交
740 741
						case editorCommon.EventType.ViewFocusGained:
							this.emit(editorCommon.EventType.EditorTextFocus);
742
							// In IE, the focus is not synchronous, so we give it a little help
A
Alex Dima 已提交
743
							this.emit(editorCommon.EventType.EditorFocus, {});
744 745 746 747 748 749 750 751 752 753
							break;

						case 'scroll':
							this.emit('scroll', e);
							break;

						case 'scrollSize':
							this.emit('scrollSize', e);
							break;

A
Alex Dima 已提交
754 755
						case editorCommon.EventType.ViewFocusLost:
							this.emit(editorCommon.EventType.EditorTextBlur);
756 757
							break;

A
Alex Dima 已提交
758 759
						case editorCommon.EventType.ContextMenu:
							this.emit(editorCommon.EventType.ContextMenu, e);
760 761
							break;

A
Alex Dima 已提交
762 763
						case editorCommon.EventType.MouseDown:
							this.emit(editorCommon.EventType.MouseDown, e);
764 765
							break;

A
Alex Dima 已提交
766 767
						case editorCommon.EventType.MouseUp:
							this.emit(editorCommon.EventType.MouseUp, e);
768 769
							break;

A
Alex Dima 已提交
770 771
						case editorCommon.EventType.KeyUp:
							this.emit(editorCommon.EventType.KeyUp, e);
772 773
							break;

A
Alex Dima 已提交
774 775
						case editorCommon.EventType.MouseMove:
							this.emit(editorCommon.EventType.MouseMove, e);
776 777
							break;

A
Alex Dima 已提交
778 779
						case editorCommon.EventType.MouseLeave:
							this.emit(editorCommon.EventType.MouseLeave, e);
780 781
							break;

A
Alex Dima 已提交
782 783
						case editorCommon.EventType.KeyDown:
							this.emit(editorCommon.EventType.KeyDown, e);
784 785
							break;

A
Alex Dima 已提交
786 787
						case editorCommon.EventType.ViewLayoutChanged:
							this.emit(editorCommon.EventType.EditorLayout, e);
788 789 790 791 792 793 794 795 796 797 798 799 800 801
							break;

						default:
//							console.warn("Unhandled view event: ", e);
					}
				}
			}));

			this.listenersToRemove.push(this.model.addBulkListener((events) => {
				for (var i = 0, len = events.length; i < len; i++) {
					var eventType = events[i].getType();
					var e = events[i].getData();

					switch (eventType) {
A
Alex Dima 已提交
802 803
						case editorCommon.EventType.ModelDecorationsChanged:
							this.emit(editorCommon.EventType.ModelDecorationsChanged, e);
804 805
							break;

A
Alex Dima 已提交
806
						case editorCommon.EventType.ModelModeChanged:
807 808
							this.domElement.setAttribute('data-mode-id', this.model.getMode().getId());
							this._langIdKey.set(this.model.getMode().getId());
A
Alex Dima 已提交
809
							this.emit(editorCommon.EventType.ModelModeChanged, e);
810 811
							break;

A
Alex Dima 已提交
812 813
						case editorCommon.EventType.ModelModeSupportChanged:
							this.emit(editorCommon.EventType.ModelModeSupportChanged, e);
814 815
							break;

A
Alex Dima 已提交
816
						case editorCommon.EventType.ModelContentChanged:
817
							// TODO@Alex
A
Alex Dima 已提交
818
							this.emit(editorCommon.EventType.ModelContentChanged, e);
819 820 821
							this.emit('change', {});
							break;

822 823 824 825
						case editorCommon.EventType.ModelOptionsChanged:
							this.emit(editorCommon.EventType.ModelOptionsChanged, e);
							break;

A
Alex Dima 已提交
826
						case editorCommon.EventType.ModelDispose:
827 828 829 830 831 832 833 834 835 836
							// Someone might destroy the model from under the editor, so prevent any exceptions by setting a null model
							this.setModel(null);
							break;

						default:
//							console.warn("Unhandled model event: ", e);
					}
				}
			}));

A
Alex Dima 已提交
837
			var _hasNonEmptySelection = (e: editorCommon.ICursorSelectionChangedEvent) => {
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
				var allSelections = [e.selection].concat(e.secondarySelections);
				return allSelections.some(s => !s.isEmpty());
			};

			this.listenersToRemove.push(this.cursor.addBulkListener((events) => {
				var updateHasMultipleCursors = false,
					hasMultipleCursors = false,
					updateHasNonEmptySelection = false,
					hasNonEmptySelection = false;

				for (var i = 0, len = events.length; i < len; i++) {
					var eventType = events[i].getType();
					var e = events[i].getData();

					switch (eventType) {
A
Alex Dima 已提交
853 854
						case editorCommon.EventType.CursorPositionChanged:
							var cursorPositionChangedEvent = <editorCommon.ICursorPositionChangedEvent>e;
855 856
							updateHasMultipleCursors = true;
							hasMultipleCursors = (cursorPositionChangedEvent.secondaryPositions.length > 0);
A
Alex Dima 已提交
857
							this.emit(editorCommon.EventType.CursorPositionChanged, e);
858 859
							break;

A
Alex Dima 已提交
860 861
						case editorCommon.EventType.CursorSelectionChanged:
							var cursorSelectionChangedEvent = <editorCommon.ICursorSelectionChangedEvent>e;
862 863 864 865
							updateHasMultipleCursors = true;
							hasMultipleCursors = (cursorSelectionChangedEvent.secondarySelections.length > 0);
							updateHasNonEmptySelection = true;
							hasNonEmptySelection = _hasNonEmptySelection(cursorSelectionChangedEvent);
A
Alex Dima 已提交
866
							this.emit(editorCommon.EventType.CursorSelectionChanged, e);
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
							break;

						default:
//							console.warn("Unhandled cursor event: ", e);
					}
				}

				if (updateHasMultipleCursors) {
					if (hasMultipleCursors) {
						this._hasMultipleSelectionsKey.set(true);
					} else {
						this._hasMultipleSelectionsKey.reset();
					}
				}
				if (updateHasNonEmptySelection) {
					if (hasNonEmptySelection) {
						this._hasNonEmptySelectionKey.set(true);
					} else {
						this._hasNonEmptySelectionKey.reset();
					}
				}
			}));
		} else {
			this.hasView = false;
		}
	}

	protected abstract _enableEmptySelectionClipboard(): boolean;

	protected abstract _createView(): void;

A
Alex Dima 已提交
898
	protected abstract _getViewInternalEventBus(): IEventEmitter;
899

A
Alex Dima 已提交
900
	_postDetachModelCleanup(detachedModel:editorCommon.IModel): void {
901 902 903 904 905 906
		if (detachedModel) {
			this._decorationTypeKeysToIds = {};
			detachedModel.removeAllDecorationsWithOwnerId(this.id);
		}
	}

A
Alex Dima 已提交
907
	protected _detachModel(): editorCommon.IModel {
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
		if (this.model) {
			this.model.onBeforeDetached();
		}

		this.hasView = false;

		this.listenersToRemove.forEach((element) => {
			element();
		});
		this.listenersToRemove = [];

		if (this.cursor) {
			this.cursor.dispose();
			this.cursor = null;
		}

		if (this.viewModel) {
			this.viewModel.dispose();
			this.viewModel = null;
		}

		var result = this.model;
		this.model = null;

		this.domElement.removeAttribute('data-mode-id');

		return result;
	}
}