commonCodeEditor.ts 31.3 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 51 52

	protected forcedWidgetFocusCount:number;

	// --- Members logically associated to a model
A
Alex Dima 已提交
53 54
	protected model:editorCommon.IModel;
	protected listenersToRemove:ListenerUnbind[];
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
	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,
75
		options:editorCommon.IEditorOptions,
76 77 78 79 80 81 82
		instantiationService: IInstantiationService,
		codeEditorService: ICodeEditorService,
		keybindingService: IKeybindingService,
		telemetryService: ITelemetryService
	) {
		super();

A
Alex Dima 已提交
83 84
		this.domElement = domElement;

85 86 87
		this.id = (++EDITOR_ID);
		this._codeEditorService = codeEditorService;

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

		this._lifetimeDispose = [];

		this._keybindingService = keybindingService.createScoped(domElement);
		this._editorIdContextKey = this._keybindingService.createKey('editorId', this.getId());
A
Alex Dima 已提交
94 95 96 97 98
		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);
99 100 101 102 103

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

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

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

		this.forcedWidgetFocusCount = 0;

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

120
		this._attachModel(null);
121 122 123 124 125 126 127 128 129 130

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


		timerEvent.stop();

		this._codeEditorService.addCodeEditor(this);
	}

131
	protected abstract _createConfiguration(options:editorCommon.ICodeEditorWidgetCreationOptions): CommonEditorConfiguration;
132 133 134 135 136 137

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

	public getEditorType(): string {
A
Alex Dima 已提交
138
		return editorCommon.EditorType.ICodeEditor;
139 140 141 142 143 144 145 146
	}

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

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

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

155 156 157 158 159
		this.contributions = {};

		this._postDetachModelCleanup(this._detachModel());
		this._configuration.dispose();
		this._keybindingService.dispose();
A
Alex Dima 已提交
160
		this.emit(editorCommon.EventType.Disposed, {});
161 162 163
		super.dispose();
	}

A
Alex Dima 已提交
164
	public captureState(...flags:editorCommon.CodeEditorStateFlag[]): editorCommon.ICodeEditorState {
165 166 167
		return new EditorState(this, flags);
	}

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

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

A
Alex Dima 已提交
188
	public getConfiguration(): editorCommon.IInternalEditorOptions {
A
Alex Dima 已提交
189
		return this._configuration.editorClone;
190 191
	}

A
Alex Dima 已提交
192
	public getRawConfiguration(): editorCommon.IEditorOptions {
193 194 195 196 197 198
		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 已提交
199
			var eolPreference = editorCommon.EndOfLinePreference.TextDefined;
200
			if (options && options.lineEnding && options.lineEnding === '\n') {
A
Alex Dima 已提交
201
				eolPreference = editorCommon.EndOfLinePreference.LF;
202
			} else if (options  && options.lineEnding && options.lineEnding === '\r\n') {
A
Alex Dima 已提交
203
				eolPreference = editorCommon.EndOfLinePreference.CRLF;
204 205 206 207 208 209 210 211 212 213 214 215
			}
			return this.model.getValue(eolPreference, preserveBOM);
		}
		return '';
	}

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

A
Alex Dima 已提交
216
	public getModel(): editorCommon.IModel {
217 218 219
		return this.model;
	}

A
Alex Dima 已提交
220
	public setModel(model:editorCommon.IModel = null): void {
221 222 223 224 225
		if (this.model === model) {
			// Current model is the new model
			return;
		}

A
Alex Dima 已提交
226
		var timerEvent = timer.start(timer.Topic.EDITOR, 'CodeEditor.setModel');
227 228 229 230 231 232 233 234 235 236 237 238 239

		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 已提交
240
		var e: editorCommon.IModelChangedEvent = {
241 242 243 244 245 246
			oldModelUrl: oldModelUrl,
			newModelUrl: newModelUrl
		};

		timerEvent.stop();

A
Alex Dima 已提交
247
		this.emit(editorCommon.EventType.ModelChanged, e);
248 249 250
		this._postDetachModelCleanup(detachedModel);
	}

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

A
Alex Dima 已提交
253
	public getVisibleColumnFromPosition(rawPosition:editorCommon.IPosition): number {
254 255 256 257
		if (!this.model) {
			return rawPosition.column;
		}

258 259
		let position = this.model.validatePosition(rawPosition);
		let tabSize = this.model.getOptions().tabSize;
260

261
		return CursorMoveHelper.visibleColumnFromColumn(this.model, position.lineNumber, position.column, tabSize) + 1;
262 263
	}

A
Alex Dima 已提交
264
	public getPosition(): editorCommon.IEditorPosition {
265 266 267 268 269 270
		if (!this.cursor) {
			return null;
		}
		return this.cursor.getPosition().clone();
	}

A
Alex Dima 已提交
271
	public setPosition(position:editorCommon.IPosition, reveal:boolean = false, revealVerticalInCenter:boolean = false, revealHorizontal:boolean = false): void {
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
		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 已提交
289
	private _sendRevealRange(range: editorCommon.IRange, verticalType: editorCommon.VerticalRevealType, revealHorizontal: boolean): void {
290 291 292 293 294 295 296 297
		if (!this.model || !this.cursor) {
			return;
		}
		if (!Range.isIRange(range)) {
			throw new Error('Invalid arguments');
		}
		var validatedRange = this.model.validateRange(range);

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

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

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

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

A
Alex Dima 已提交
334
	public revealPosition(position: editorCommon.IPosition, revealVerticalInCenter:boolean=false, revealHorizontal:boolean=false): void {
335 336 337 338 339 340 341 342
		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 已提交
343
		}, revealVerticalInCenter ? editorCommon.VerticalRevealType.Center : editorCommon.VerticalRevealType.Simple, revealHorizontal);
344 345
	}

A
Alex Dima 已提交
346
	public revealPositionInCenter(position: editorCommon.IPosition): void {
347 348 349 350 351 352 353 354
		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 已提交
355
		}, editorCommon.VerticalRevealType.Center, true);
356 357
	}

A
Alex Dima 已提交
358
	public revealPositionInCenterIfOutsideViewport(position: editorCommon.IPosition): void {
359 360 361 362 363 364 365 366
		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 已提交
367
		}, editorCommon.VerticalRevealType.CenterIfOutsideViewport, true);
368 369
	}

A
Alex Dima 已提交
370
	public getSelection(): editorCommon.IEditorSelection {
371 372 373 374 375 376
		if (!this.cursor) {
			return null;
		}
		return this.cursor.getSelection().clone();
	}

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

A
Alex Dima 已提交
389 390 391 392
	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;
393 394 395 396 397 398 399 400 401
	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 已提交
402
			this._setSelectionImpl(<editorCommon.ISelection>something, reveal, revealVerticalInCenter, revealHorizontal);
403 404
		} else if (isRange) {
			// act as if it was an IRange
A
Alex Dima 已提交
405
			var selection:editorCommon.ISelection = {
406 407 408 409 410 411 412 413 414
				selectionStartLineNumber: something.startLineNumber,
				selectionStartColumn: something.startColumn,
				positionLineNumber: something.endLineNumber,
				positionColumn: something.endColumn
			};
			this._setSelectionImpl(selection, reveal, revealVerticalInCenter, revealHorizontal);
		}
	}

A
Alex Dima 已提交
415
	private _setSelectionImpl(sel:editorCommon.ISelection, reveal:boolean, revealVerticalInCenter:boolean, revealHorizontal:boolean): void {
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
		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 已提交
432
		}, editorCommon.VerticalRevealType.Simple, false);
433 434 435 436 437 438 439 440
	}

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

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

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

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

A
Alex Dima 已提交
461 462
	public revealRangeInCenterIfOutsideViewport(range: editorCommon.IRange): void {
		this._sendRevealRange(range, editorCommon.VerticalRevealType.CenterIfOutsideViewport, true);
463 464
	}

A
Alex Dima 已提交
465
	public setSelections(ranges: editorCommon.ISelection[]): void {
466 467 468 469 470 471 472 473 474 475 476 477 478 479
		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);
	}

480 481
	public abstract getScrollWidth(): number;
	public abstract getScrollLeft(): number;
482

483
	public abstract getScrollHeight(): number;
484 485 486
	public abstract getScrollTop(): number;

	public abstract setScrollLeft(newScrollLeft:number): void;
487 488
	public abstract setScrollTop(newScrollTop:number): void;
	public abstract setScrollPosition(position: editorCommon.INewScrollPosition): void;
489

A
Alex Dima 已提交
490 491
	public abstract saveViewState(): editorCommon.ICodeEditorViewState;
	public abstract restoreViewState(state:editorCommon.IEditorViewState): void;
492 493 494 495 496 497 498

	public onVisible(): void {
	}

	public onHide(): void {
	}

A
Alex Dima 已提交
499
	public abstract layout(dimension?:editorCommon.IDimension): void;
500 501 502 503 504 505 506 507 508 509 510 511 512

	public abstract focus(): void;

	public beginForcedWidgetFocus(): void {
		this.forcedWidgetFocusCount++;
	}

	public endForcedWidgetFocus(): void {
		this.forcedWidgetFocusCount--;
	}

	public abstract isFocused(): boolean;

513 514
	public abstract hasWidgetFocus(): boolean;

A
Alex Dima 已提交
515
	public getContribution(id: string): editorCommon.IEditorContribution {
516 517 518
		return this.contributions[id] || null;
	}

A
Alex Dima 已提交
519
	public addAction(descriptor:editorCommon.IActionDescriptor): void {
520 521 522 523 524 525 526
		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!');
		}
527 528 529 530 531
		var action = this._instantiationService.createInstance(DynamicEditorAction, descriptor, this);
		this.contributions[action.getId()] = action;
	}

	public getActions(): IAction[] {
A
Alex Dima 已提交
532 533 534 535 536 537 538 539 540
		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);
541 542
			}
		}
A
Alex Dima 已提交
543

544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
		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 {
559
		payload = payload || {};
560 561 562
		var candidate = this.getAction(handlerId);
		if(candidate !== null) {
			if (candidate.enabled) {
563
				this._telemetryService.publicLog('editorActionInvoked', {name: candidate.label, id: candidate.id} );
564 565 566
				TPromise.as(candidate.run()).done(null, onUnexpectedError);
			}
		} else {
A
Alex Dima 已提交
567 568
			if (!this.cursor) {
				return;
569
			}
A
Alex Dima 已提交
570
			this.cursor.trigger(source, handlerId, payload);
571 572 573
		}
	}

A
Alex Dima 已提交
574 575 576 577 578
	public executeCommand(source: string, command: editorCommon.ICommand): void {
		if (!this.cursor) {
			return;
		}
		this.cursor.trigger(source, editorCommon.Handler.ExecuteCommand, command);
579 580
	}

A
Alex Dima 已提交
581
	public executeEdits(source: string, edits: editorCommon.IIdentifiedSingleEditOperation[]): boolean {
582 583 584 585 586 587 588 589 590 591 592 593 594 595
		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 已提交
596 597 598 599 600
	public executeCommands(source: string, commands: editorCommon.ICommand[]): void {
		if (!this.cursor) {
			return;
		}
		this.cursor.trigger(source, editorCommon.Handler.ExecuteCommands, commands);
601 602
	}

A
Alex Dima 已提交
603
	public changeDecorations(callback:(changeAccessor:editorCommon.IModelDecorationsChangeAccessor)=>any): any {
604 605 606 607 608 609 610 611
		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 已提交
612
	public getLineDecorations(lineNumber: number): editorCommon.IModelDecoration[] {
613 614 615 616 617 618
		if (!this.model) {
			return null;
		}
		return this.model.getLineDecorations(lineNumber, this.id, this._configuration.editor.readOnly);
	}

A
Alex Dima 已提交
619
	public deltaDecorations(oldDecorations:string[], newDecorations:editorCommon.IModelDeltaDecoration[]): string[] {
620 621 622 623 624 625 626 627 628 629 630
		if (!this.model) {
			return [];
		}

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

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

A
Alex Dima 已提交
631
	public setDecorations(decorationTypeKey: string, ranges:editorCommon.IRangeWithMessage[]): void {
632 633
		var opts = this._codeEditorService.resolveDecorationType(decorationTypeKey);
		var oldDecorationIds = this._decorationTypeKeysToIds[decorationTypeKey] || [];
A
Alex Dima 已提交
634 635
		this._decorationTypeKeysToIds[decorationTypeKey] = this.deltaDecorations(oldDecorationIds, ranges.map((r) : editorCommon.IModelDeltaDecoration => {
			let decOpts: editorCommon.IModelDecorationOptions;
636
			if (r.hoverMessage) {
A
Alex Dima 已提交
637 638
				// TODO@Alex: avoid objects.clone
				decOpts = objects.clone(opts);
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
				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 已提交
657
	public addTypingListener(character:string, callback: () => void): ListenerUnbind {
658 659 660 661 662 663 664 665 666 667 668 669 670
		if (!this.cursor) {
			return () => {
				// no-op
			};
		}
		this.cursor.addTypingListener(character, callback);
		return () => {
			if (this.cursor) {
				this.cursor.removeTypingListener(character, callback);
			}
		};
	}

A
Alex Dima 已提交
671
	public getLayoutInfo(): editorCommon.IEditorLayoutInfo {
672 673 674
		return this._configuration.editor.layoutInfo;
	}

A
Alex Dima 已提交
675
	_attachModel(model:editorCommon.IModel): void {
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
		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(
				this._configuration.editor.wordWrapBreakBeforeCharacters,
				this._configuration.editor.wordWrapBreakAfterCharacters,
				this._configuration.editor.wordWrapBreakObtrusiveCharacters
			);

			var linesCollection = new SplitLinesCollection(
				this.model,
				hardWrappingLineMapperFactory,
698
				this.model.getOptions().tabSize,
699
				this._configuration.editor.wrappingInfo.wrappingColumn,
700
				this._configuration.editor.fontInfo.typicalFullwidthCharacterWidth / this._configuration.editor.fontInfo.typicalHalfwidthCharacterWidth,
A
Alex Dima 已提交
701
				this._configuration.editor.wrappingIndent
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
			);

			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 已提交
717
				convertModelRangeToViewRange: (modelRange:editorCommon.IEditorRange) => {
718 719 720 721 722
					return this.viewModel.convertModelRangeToViewRange(modelRange);
				},
				convertViewToModelPosition: (lineNumber:number, column:number) => {
					return this.viewModel.convertViewPositionToModelPosition(lineNumber, column);
				},
A
Alex Dima 已提交
723 724 725
				convertViewSelectionToModelSelection: (viewSelection:editorCommon.ISelection) => {
					return this.viewModel.convertViewSelectionToModelSelection(viewSelection);
				},
A
Alex Dima 已提交
726
				validateViewPosition: (viewLineNumber:number, viewColumn:number, modelPosition:editorCommon.IEditorPosition) => {
727 728
					return this.viewModel.validateViewPosition(viewLineNumber, viewColumn, modelPosition);
				},
A
Alex Dima 已提交
729
				validateViewRange: (viewStartLineNumber:number, viewStartColumn:number, viewEndLineNumber:number, viewEndColumn:number, modelRange:editorCommon.IEditorRange) => {
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
					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 已提交
752 753
						case editorCommon.EventType.ViewFocusGained:
							this.emit(editorCommon.EventType.EditorTextFocus);
754
							// In IE, the focus is not synchronous, so we give it a little help
A
Alex Dima 已提交
755
							this.emit(editorCommon.EventType.EditorFocus, {});
756 757 758 759 760 761 762 763 764 765
							break;

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

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

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

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

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

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

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

A
Alex Dima 已提交
786 787
						case editorCommon.EventType.MouseMove:
							this.emit(editorCommon.EventType.MouseMove, e);
788 789
							break;

A
Alex Dima 已提交
790 791
						case editorCommon.EventType.MouseLeave:
							this.emit(editorCommon.EventType.MouseLeave, e);
792 793
							break;

A
Alex Dima 已提交
794 795
						case editorCommon.EventType.KeyDown:
							this.emit(editorCommon.EventType.KeyDown, e);
796 797
							break;

A
Alex Dima 已提交
798 799
						case editorCommon.EventType.ViewLayoutChanged:
							this.emit(editorCommon.EventType.EditorLayout, e);
800 801 802 803 804 805 806 807 808 809 810 811 812 813
							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 已提交
814 815
						case editorCommon.EventType.ModelDecorationsChanged:
							this.emit(editorCommon.EventType.ModelDecorationsChanged, e);
816 817
							break;

A
Alex Dima 已提交
818
						case editorCommon.EventType.ModelModeChanged:
819 820
							this.domElement.setAttribute('data-mode-id', this.model.getMode().getId());
							this._langIdKey.set(this.model.getMode().getId());
A
Alex Dima 已提交
821
							this.emit(editorCommon.EventType.ModelModeChanged, e);
822 823
							break;

A
Alex Dima 已提交
824 825
						case editorCommon.EventType.ModelModeSupportChanged:
							this.emit(editorCommon.EventType.ModelModeSupportChanged, e);
826 827
							break;

A
Alex Dima 已提交
828
						case editorCommon.EventType.ModelContentChanged:
829
							// TODO@Alex
A
Alex Dima 已提交
830
							this.emit(editorCommon.EventType.ModelContentChanged, e);
831 832 833
							this.emit('change', {});
							break;

834 835 836 837
						case editorCommon.EventType.ModelOptionsChanged:
							this.emit(editorCommon.EventType.ModelOptionsChanged, e);
							break;

A
Alex Dima 已提交
838
						case editorCommon.EventType.ModelDispose:
839 840 841 842 843 844 845 846 847 848
							// 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 已提交
849
			var _hasNonEmptySelection = (e: editorCommon.ICursorSelectionChangedEvent) => {
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
				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 已提交
865 866
						case editorCommon.EventType.CursorPositionChanged:
							var cursorPositionChangedEvent = <editorCommon.ICursorPositionChangedEvent>e;
867 868
							updateHasMultipleCursors = true;
							hasMultipleCursors = (cursorPositionChangedEvent.secondaryPositions.length > 0);
A
Alex Dima 已提交
869
							this.emit(editorCommon.EventType.CursorPositionChanged, e);
870 871
							break;

A
Alex Dima 已提交
872 873
						case editorCommon.EventType.CursorSelectionChanged:
							var cursorSelectionChangedEvent = <editorCommon.ICursorSelectionChangedEvent>e;
874 875 876 877
							updateHasMultipleCursors = true;
							hasMultipleCursors = (cursorSelectionChangedEvent.secondarySelections.length > 0);
							updateHasNonEmptySelection = true;
							hasNonEmptySelection = _hasNonEmptySelection(cursorSelectionChangedEvent);
A
Alex Dima 已提交
878
							this.emit(editorCommon.EventType.CursorSelectionChanged, e);
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
							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 已提交
910
	protected abstract _getViewInternalEventBus(): IEventEmitter;
911

A
Alex Dima 已提交
912
	_postDetachModelCleanup(detachedModel:editorCommon.IModel): void {
913 914 915 916 917 918
		if (detachedModel) {
			this._decorationTypeKeysToIds = {};
			detachedModel.removeAllDecorationsWithOwnerId(this.id);
		}
	}

A
Alex Dima 已提交
919
	protected _detachModel(): editorCommon.IModel {
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
		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;
	}
}