codeEditorWidget.ts 15.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 'vs/css!./media/default-theme';
E
Erich Gamma 已提交
8 9
import 'vs/css!./media/editor';
import 'vs/css!./media/tokens';
10 11
import {onUnexpectedError} from 'vs/base/common/errors';
import {IEventEmitter} from 'vs/base/common/eventEmitter';
A
Alex Dima 已提交
12 13
import * as browser from 'vs/base/browser/browser';
import * as dom from 'vs/base/browser/dom';
E
Erich Gamma 已提交
14
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
15
import {IKeybindingService} from 'vs/platform/keybinding/common/keybindingService';
A
Alex Dima 已提交
16
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
17 18
import {CommonCodeEditor} from 'vs/editor/common/commonCodeEditor';
import {CommonEditorConfiguration, IIndentationGuesser} from 'vs/editor/common/config/commonEditorConfig';
A
Alex Dima 已提交
19 20 21 22 23 24 25 26 27 28
import {Range} from 'vs/editor/common/core/range';
import {Selection} from 'vs/editor/common/core/selection';
import * as editorCommon from 'vs/editor/common/editorCommon';
import {CommonEditorRegistry} from 'vs/editor/common/editorCommonExtensions';
import {ICodeEditorService} from 'vs/editor/common/services/codeEditorService';
import {Configuration} from 'vs/editor/browser/config/configuration';
import * as editorBrowser from 'vs/editor/browser/editorBrowser';
import {EditorBrowserRegistry} from 'vs/editor/browser/editorBrowserExtensions';
import {Colorizer} from 'vs/editor/browser/standalone/colorizer';
import {View} from 'vs/editor/browser/view/viewImpl';
E
Erich Gamma 已提交
29

A
Alex Dima 已提交
30
export class CodeEditorWidget extends CommonCodeEditor implements editorBrowser.ICodeEditor {
E
Erich Gamma 已提交
31

32
	protected domElement:HTMLElement;
A
Alex Dima 已提交
33
	private focusTracker:dom.IFocusTracker;
E
Erich Gamma 已提交
34

35 36
	_configuration:Configuration;

A
Alex Dima 已提交
37 38
	private contentWidgets:{ [key:string]:editorBrowser.IContentWidgetData; };
	private overlayWidgets:{ [key:string]:editorBrowser.IOverlayWidgetData; };
E
Erich Gamma 已提交
39

A
Alex Dima 已提交
40
	_view:editorBrowser.IView;
E
Erich Gamma 已提交
41 42 43

	constructor(
		domElement:HTMLElement,
44
		options:editorCommon.IEditorOptions,
E
Erich Gamma 已提交
45 46 47 48 49
		@IInstantiationService instantiationService: IInstantiationService,
		@ICodeEditorService codeEditorService: ICodeEditorService,
		@IKeybindingService keybindingService: IKeybindingService,
		@ITelemetryService telemetryService: ITelemetryService
	) {
50
		super(domElement, options, instantiationService, codeEditorService, keybindingService, telemetryService);
E
Erich Gamma 已提交
51 52

		// track focus of the domElement and all its anchestors
A
Alex Dima 已提交
53
		this.focusTracker = dom.trackFocus(this.domElement);
E
Erich Gamma 已提交
54 55 56
		this.focusTracker.addFocusListener(() => {
			if (this.forcedWidgetFocusCount === 0) {
				this._editorFocusContextKey.set(true);
A
Alex Dima 已提交
57
				this.emit(editorCommon.EventType.EditorFocus, {});
E
Erich Gamma 已提交
58 59 60 61 62
			}
		});
		this.focusTracker.addBlurListener(() => {
			if (this.forcedWidgetFocusCount === 0) {
				this._editorFocusContextKey.reset();
A
Alex Dima 已提交
63
				this.emit(editorCommon.EventType.EditorBlur, {});
E
Erich Gamma 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76
			}
		});

		this.contentWidgets = {};
		this.overlayWidgets = {};

		var contributionDescriptors = [].concat(EditorBrowserRegistry.getEditorContributions()).concat(CommonEditorRegistry.getEditorContributions());
		for (var i = 0, len = contributionDescriptors.length; i < len; i++) {
			try {
				var contribution = contributionDescriptors[i].createInstance(this._instantiationService, this);
				this.contributions[contribution.getId()] = contribution;
			} catch (err) {
				console.error('Could not instantiate contribution ' + contribution.getId());
77
				onUnexpectedError(err);
E
Erich Gamma 已提交
78 79 80 81
			}
		}
	}

A
Alex Dima 已提交
82
	protected _createConfiguration(options:editorCommon.ICodeEditorWidgetCreationOptions, indentationGuesser:IIndentationGuesser): CommonEditorConfiguration {
83
		return new Configuration(options, this.domElement, indentationGuesser);
E
Erich Gamma 已提交
84 85 86 87 88 89 90 91 92 93
	}

	public dispose(): void {
		this.contentWidgets = {};
		this.overlayWidgets = {};

		this.focusTracker.dispose();
		super.dispose();
	}

A
Alex Dima 已提交
94
	public colorizeModelLine(lineNumber:number, model:editorCommon.IModel = this.model): string {
E
Erich Gamma 已提交
95 96 97 98 99
		if (!model) {
			return '';
		}
		var content = model.getLineContent(lineNumber);
		var tokens = model.getLineTokens(lineNumber, false);
A
Alex Dima 已提交
100
		var inflatedTokens = editorCommon.LineTokensBinaryEncoding.inflateArr(tokens.getBinaryEncodedTokensMap(), tokens.getBinaryEncodedTokens());
E
Erich Gamma 已提交
101
		var indent = this._configuration.getIndentationOptions();
A
Alex Dima 已提交
102
		return Colorizer.colorizeLine(content, inflatedTokens, indent.tabSize);
E
Erich Gamma 已提交
103
	}
A
Alex Dima 已提交
104
	public getView(): editorBrowser.IView {
E
Erich Gamma 已提交
105 106 107 108 109 110 111 112 113 114
		return this._view;
	}

	public getDomNode(): HTMLElement {
		if (!this.hasView) {
			return null;
		}
		return this._view.domNode;
	}

A
Alex Dima 已提交
115
	public getCenteredRangeInViewport(): editorCommon.IEditorRange {
E
Erich Gamma 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
		if (!this.hasView) {
			return null;
		}
		return this._view.getCenteredRangeInViewport();
	}

	public setScrollTop(newScrollTop:number): void {
		if (!this.hasView) {
			return;
		}
		if (typeof newScrollTop !== 'number') {
			throw new Error('Invalid arguments');
		}
		this._view.getCodeEditorHelper().setScrollTop(newScrollTop);
	}

	public getScrollTop(): number {
		if (!this.hasView) {
			return -1;
		}
		return this._view.getCodeEditorHelper().getScrollTop();
	}

	public delegateVerticalScrollbarMouseDown(browserEvent:MouseEvent): void {
		if (!this.hasView) {
			return;
		}
		this._view.getCodeEditorHelper().delegateVerticalScrollbarMouseDown(browserEvent);
	}

	public setScrollLeft(newScrollLeft:number): void {
		if (!this.hasView) {
			return;
		}
		if (typeof newScrollLeft !== 'number') {
			throw new Error('Invalid arguments');
		}
		this._view.getCodeEditorHelper().setScrollLeft(newScrollLeft);
	}

	public getScrollLeft(): number {
		if (!this.hasView) {
			return -1;
		}
		return this._view.getCodeEditorHelper().getScrollLeft();
	}

	public getScrollWidth(): number {
		if (!this.hasView) {
			return -1;
		}
		return this._view.getCodeEditorHelper().getScrollWidth();
	}

	public getScrollHeight(): number {
		if (!this.hasView) {
			return -1;
		}
		return this._view.getCodeEditorHelper().getScrollHeight();
	}

A
Alex Dima 已提交
177
	public saveViewState(): editorCommon.ICodeEditorViewState {
E
Erich Gamma 已提交
178 179 180
		if (!this.cursor || !this.hasView) {
			return null;
		}
181 182 183 184 185 186 187 188
		let contributionsState: {[key:string]:any} = {};
		for (let id in this.contributions) {
			let contribution = this.contributions[id];
			if (typeof contribution.saveViewState === 'function') {
				contributionsState[id] = contribution.saveViewState();
			}
		}

E
Erich Gamma 已提交
189 190 191 192
		var cursorState = this.cursor.saveState();
		var viewState = this._view.saveState();
		return {
			cursorState: cursorState,
193 194
			viewState: viewState,
			contributionsState: contributionsState
E
Erich Gamma 已提交
195 196 197
		};
	}

A
Alex Dima 已提交
198
	public restoreViewState(state:editorCommon.IEditorViewState): void {
E
Erich Gamma 已提交
199 200 201 202 203
		if (!this.cursor || !this.hasView) {
			return;
		}
		var s = <any>state;
		if (s && s.cursorState && s.viewState) {
A
Alex Dima 已提交
204
			var codeEditorState = <editorCommon.ICodeEditorViewState>s;
E
Erich Gamma 已提交
205 206
			var cursorState = <any>codeEditorState.cursorState;
			if (Array.isArray(cursorState)) {
A
Alex Dima 已提交
207
				this.cursor.restoreState(<editorCommon.ICursorState[]>cursorState);
E
Erich Gamma 已提交
208 209
			} else {
				// Backwards compatibility
A
Alex Dima 已提交
210
				this.cursor.restoreState([<editorCommon.ICursorState>cursorState]);
E
Erich Gamma 已提交
211 212
			}
			this._view.restoreState(codeEditorState.viewState);
213 214 215 216 217 218 219 220

			let contributionsState = s.contributionsState || {};
			for (let id in this.contributions) {
				let contribution = this.contributions[id];
				if (typeof contribution.restoreViewState === 'function') {
					contribution.restoreViewState(contributionsState[id]);
				}
			}
E
Erich Gamma 已提交
221 222 223
		}
	}

A
Alex Dima 已提交
224
	public layout(dimension?:editorCommon.IDimension): void {
E
Erich Gamma 已提交
225
		this._configuration.observeReferenceElement(dimension);
226
		this.render();
E
Erich Gamma 已提交
227 228 229 230 231 232 233 234 235 236 237 238 239
	}

	public focus(): void {
		if (!this.hasView) {
			return;
		}
		this._view.focus();
	}

	public isFocused(): boolean {
		return this.hasView && this._view.isFocused();
	}

A
Alex Dima 已提交
240 241
	public addContentWidget(widget: editorBrowser.IContentWidget): void {
		var widgetData: editorBrowser.IContentWidgetData = {
E
Erich Gamma 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
			widget: widget,
			position: widget.getPosition()
		};

		if (this.contentWidgets.hasOwnProperty(widget.getId())) {
			console.warn('Overwriting a content widget with the same id.');
		}

		this.contentWidgets[widget.getId()] = widgetData;

		if (this.hasView) {
			this._view.addContentWidget(widgetData);
		}
	}

A
Alex Dima 已提交
257
	public layoutContentWidget(widget: editorBrowser.IContentWidget): void {
E
Erich Gamma 已提交
258 259 260 261 262 263 264 265 266 267
		var widgetId = widget.getId();
		if (this.contentWidgets.hasOwnProperty(widgetId)) {
			var widgetData = this.contentWidgets[widgetId];
			widgetData.position = widget.getPosition();
			if (this.hasView) {
				this._view.layoutContentWidget(widgetData);
			}
		}
	}

A
Alex Dima 已提交
268
	public removeContentWidget(widget: editorBrowser.IContentWidget): void {
E
Erich Gamma 已提交
269 270 271 272 273 274 275 276 277 278
		var widgetId = widget.getId();
		if (this.contentWidgets.hasOwnProperty(widgetId)) {
			var widgetData = this.contentWidgets[widgetId];
			delete this.contentWidgets[widgetId];
			if (this.hasView) {
				this._view.removeContentWidget(widgetData);
			}
		}
	}

A
Alex Dima 已提交
279 280
	public addOverlayWidget(widget: editorBrowser.IOverlayWidget): void {
		var widgetData: editorBrowser.IOverlayWidgetData = {
E
Erich Gamma 已提交
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
			widget: widget,
			position: widget.getPosition()
		};

		if (this.overlayWidgets.hasOwnProperty(widget.getId())) {
			console.warn('Overwriting an overlay widget with the same id.');
		}

		this.overlayWidgets[widget.getId()] = widgetData;

		if (this.hasView) {
			this._view.addOverlayWidget(widgetData);
		}
	}

A
Alex Dima 已提交
296
	public layoutOverlayWidget(widget: editorBrowser.IOverlayWidget): void {
E
Erich Gamma 已提交
297 298 299 300 301 302 303 304 305 306
		var widgetId = widget.getId();
		if (this.overlayWidgets.hasOwnProperty(widgetId)) {
			var widgetData = this.overlayWidgets[widgetId];
			widgetData.position = widget.getPosition();
			if (this.hasView) {
				this._view.layoutOverlayWidget(widgetData);
			}
		}
	}

A
Alex Dima 已提交
307
	public removeOverlayWidget(widget: editorBrowser.IOverlayWidget): void {
E
Erich Gamma 已提交
308 309 310 311 312 313 314 315 316 317
		var widgetId = widget.getId();
		if (this.overlayWidgets.hasOwnProperty(widgetId)) {
			var widgetData = this.overlayWidgets[widgetId];
			delete this.overlayWidgets[widgetId];
			if (this.hasView) {
				this._view.removeOverlayWidget(widgetData);
			}
		}
	}

A
Alex Dima 已提交
318
	public changeViewZones(callback:(accessor:editorBrowser.IViewZoneChangeAccessor)=>void): void {
E
Erich Gamma 已提交
319 320 321 322 323 324
		if (!this.hasView) {
//			console.warn('Cannot change view zones on editor that is not attached to a model, since there is no view.');
			return;
		}
		var hasChanges = this._view.change(callback);
		if (hasChanges) {
A
Alex Dima 已提交
325
			this.emit(editorCommon.EventType.ViewZonesChanged);
E
Erich Gamma 已提交
326 327 328
		}
	}

A
Alex Dima 已提交
329
	public getWhitespaces(): editorCommon.IEditorWhitespace[] {
E
Erich Gamma 已提交
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
		if (!this.hasView) {
			return [];
		}
		return this._view.getWhitespaces();
	}

	public getTopForLineNumber(lineNumber: number): number {
		if (!this.hasView) {
			return -1;
		}
		return this._view.getCodeEditorHelper().getVerticalOffsetForPosition(lineNumber, 1);
	}

	public getTopForPosition(lineNumber: number, column: number): number {
		if (!this.hasView) {
			return -1;
		}
		return this._view.getCodeEditorHelper().getVerticalOffsetForPosition(lineNumber, column);
	}

A
Alex Dima 已提交
350
	public getScrolledVisiblePosition(rawPosition:editorCommon.IPosition): { top:number; left:number; height:number; } {
E
Erich Gamma 已提交
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
		if (!this.hasView) {
			return null;
		}

		var position = this.model.validatePosition(rawPosition);
		var helper = this._view.getCodeEditorHelper();
		var layoutInfo = this._configuration.editor.layoutInfo;

		var top = helper.getVerticalOffsetForPosition(position.lineNumber, position.column) - helper.getScrollTop();
		var left = helper.getOffsetForColumn(position.lineNumber, position.column) + layoutInfo.glyphMarginWidth + layoutInfo.lineNumbersWidth + layoutInfo.decorationsWidth - helper.getScrollLeft();

		return {
			top: top,
			left: left,
			height: this._configuration.editor.lineHeight
		};
	}

	public getOffsetForColumn(lineNumber:number, column:number): number {
		if (!this.hasView) {
			return -1;
		}
		return this._view.getCodeEditorHelper().getOffsetForColumn(lineNumber, column);
	}

376 377 378 379 380 381 382
	public render(): void {
		if (!this.hasView) {
			return;
		}
		this._view.render(true);
	}

A
Alex Dima 已提交
383
	public setHiddenAreas(ranges:editorCommon.IRange[]): void {
M
Martin Aeschlimann 已提交
384 385 386 387 388
		if (this.viewModel) {
			this.viewModel.setHiddenAreas(ranges);
		}
	}

A
Alex Dima 已提交
389 390 391 392 393 394 395
	public setAriaActiveDescendant(id:string): void {
		if (!this.hasView) {
			return;
		}
		this._view.setAriaActiveDescendant(id);
	}

A
Alex Dima 已提交
396
	_attachModel(model:editorCommon.IModel): void {
E
Erich Gamma 已提交
397 398
		this._view = null;

399
		super._attachModel(model);
E
Erich Gamma 已提交
400

401
		if (this._view) {
E
Erich Gamma 已提交
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
			this.domElement.appendChild(this._view.domNode);

			this._view.renderOnce(() => {

				var widgetId:string;
				for (widgetId in this.contentWidgets) {
					if (this.contentWidgets.hasOwnProperty(widgetId)) {
						this._view.addContentWidget(this.contentWidgets[widgetId]);
					}
				}

				for (widgetId in this.overlayWidgets) {
					if (this.overlayWidgets.hasOwnProperty(widgetId)) {
						this._view.addOverlayWidget(this.overlayWidgets[widgetId]);
					}
				}

419
				this._view.render(false);
E
Erich Gamma 已提交
420 421 422 423 424
				this.hasView = true;
			});
		}
	}

425
	protected _enableEmptySelectionClipboard(): boolean {
A
Alex Dima 已提交
426
		return browser.enableEmptySelectionClipboard;
E
Erich Gamma 已提交
427 428
	}

429 430 431 432 433 434 435 436
	protected _createView(): void {
		this._view = new View(
			this.id,
			this._configuration,
			this.viewModel,
			this._keybindingService
		);
	}
E
Erich Gamma 已提交
437

438 439 440
	protected _getViewInternalEventBus(): IEventEmitter {
		return this._view.getInternalEventBus();
	}
E
Erich Gamma 已提交
441

A
Alex Dima 已提交
442
	protected _detachModel(): editorCommon.IModel {
E
Erich Gamma 已提交
443 444 445 446 447 448 449 450
		var removeDomNode:HTMLElement = null;

		if (this._view) {
			this._view.dispose();
			removeDomNode = this._view.domNode;
			this._view = null;
		}

451
		let result = super._detachModel();
E
Erich Gamma 已提交
452 453 454 455 456 457 458 459 460

		if (removeDomNode) {
			this.domElement.removeChild(removeDomNode);
		}

		return result;
	}
}

A
Alex Dima 已提交
461
class OverlayWidget2 implements editorBrowser.IOverlayWidget {
E
Erich Gamma 已提交
462 463

	private _id: string;
A
Alex Dima 已提交
464
	private _position: editorBrowser.IOverlayWidgetPosition;
E
Erich Gamma 已提交
465 466
	private _domNode: HTMLElement;

A
Alex Dima 已提交
467
	constructor(id:string, position:editorBrowser.IOverlayWidgetPosition) {
E
Erich Gamma 已提交
468 469 470 471 472 473 474 475 476 477 478 479 480 481
		this._id = id;
		this._position = position;
		this._domNode = document.createElement('div');
		this._domNode.className = this._id.replace(/\./g, '-').replace(/[^a-z0-9\-]/,'');
	}

	public getId(): string {
		return this._id;
	}

	public getDomNode(): HTMLElement {
		return this._domNode;
	}

A
Alex Dima 已提交
482
	public getPosition(): editorBrowser.IOverlayWidgetPosition {
E
Erich Gamma 已提交
483 484 485 486 487 488 489 490
		return this._position;
	}
}

export enum EditCursorState {
	EndOfLastEditOperation = 0
}

A
Alex Dima 已提交
491
export class CommandRunner implements editorCommon.ICommand {
E
Erich Gamma 已提交
492

A
Alex Dima 已提交
493
	private _ops: editorCommon.ISingleEditOperation[];
E
Erich Gamma 已提交
494 495
	private _editCursorState: EditCursorState;

A
Alex Dima 已提交
496
	constructor(ops: editorCommon.ISingleEditOperation[], editCursorState: EditCursorState) {
E
Erich Gamma 已提交
497 498 499 500
		this._ops = ops;
		this._editCursorState = editCursorState;
	}

A
Alex Dima 已提交
501
	public getEditOperations(model: editorCommon.ITokenizedModel, builder: editorCommon.IEditOperationBuilder): void {
E
Erich Gamma 已提交
502 503 504 505 506 507 508 509 510 511
		if (this._ops.length === 0) {
			return;
		}

		// Sort them in ascending order by range starts
		this._ops.sort((o1, o2) => {
			return Range.compareRangesUsingStarts(o1.range, o2.range);
		});

		// Merge operations that touch each other
A
Alex Dima 已提交
512
		var resultOps:editorCommon.ISingleEditOperation[] = [];
E
Erich Gamma 已提交
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
		var previousOp = this._ops[0];
		for (var i = 1; i < this._ops.length; i++) {
			if (previousOp.range.endLineNumber === this._ops[i].range.startLineNumber && previousOp.range.endColumn === this._ops[i].range.startColumn) {
				// These operations are one after another and can be merged
				previousOp.range = Range.plusRange(previousOp.range, this._ops[i].range);
				previousOp.text = previousOp.text + this._ops[i].text;
			} else {
				resultOps.push(previousOp);
				previousOp = this._ops[i];
			}
		}
		resultOps.push(previousOp);

		for (var i = 0; i < resultOps.length; i++) {
			builder.addEditOperation(Range.lift(resultOps[i].range), resultOps[i].text);
		}
	}

A
Alex Dima 已提交
531
	public computeCursorState(model: editorCommon.ITokenizedModel, helper: editorCommon.ICursorStateComputerData): editorCommon.IEditorSelection {
E
Erich Gamma 已提交
532 533 534 535 536 537 538 539 540 541
		var inverseEditOperations = helper.getInverseEditOperations();
		var srcRange = inverseEditOperations[inverseEditOperations.length - 1].range;
		return Selection.createSelection(
			srcRange.endLineNumber,
			srcRange.endColumn,
			srcRange.endLineNumber,
			srcRange.endColumn
		);
	}
}