extHostEditors.ts 23.2 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8 9 10 11
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

import URI from 'vs/base/common/uri';
import Event, {Emitter} from 'vs/base/common/event';
import {IDisposable, disposeAll} from 'vs/base/common/lifecycle';
import {TPromise} from 'vs/base/common/winjs.base';
import {Remotable, IThreadService} from 'vs/platform/thread/common/thread';
J
Johannes Rieken 已提交
12
import {ExtHostModelService, ExtHostDocumentData} from 'vs/workbench/api/node/extHostDocuments';
13
import {Selection, Range, Position, EditorOptions} from './extHostTypes';
14
import {ISingleEditOperation, ISelection, IRange, IEditor, EditorType, ICommonCodeEditor, ICommonDiffEditor, IDecorationRenderOptions, IRangeWithMessage} from 'vs/editor/common/editorCommon';
E
Erich Gamma 已提交
15 16
import {ICodeEditorService} from 'vs/editor/common/services/codeEditorService';
import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService';
J
Johannes Rieken 已提交
17
import {Position as EditorPosition} from 'vs/platform/editor/common/editor';
E
Erich Gamma 已提交
18
import {IModelService} from 'vs/editor/common/services/modelService';
19
import {MainThreadEditorsTracker, TextEditorRevealType, MainThreadTextEditor, ITextEditorConfigurationUpdate, IResolvedTextEditorConfiguration} from 'vs/workbench/api/node/mainThreadEditors';
20
import * as TypeConverters from './extHostTypeConverters';
21
import {TextDocument, TextEditorSelectionChangeEvent, TextEditorOptionsChangeEvent, TextEditorOptions, TextEditorViewColumnChangeEvent, ViewColumn} from 'vscode';
22
import {EventType} from 'vs/workbench/common/events';
23
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
E
Erich Gamma 已提交
24 25
import {IEventService} from 'vs/platform/event/common/event';
import {equals as arrayEquals} from 'vs/base/common/arrays';
26
import {equals as objectEquals} from 'vs/base/common/objects';
E
Erich Gamma 已提交
27 28 29 30

export interface ITextEditorAddData {
	id: string;
	document: URI;
31
	options: IResolvedTextEditorConfiguration;
E
Erich Gamma 已提交
32
	selections: ISelection[];
33 34 35 36 37
	editorPosition: EditorPosition;
}

export interface ITextEditorPositionData {
	[id: string]: EditorPosition;
E
Erich Gamma 已提交
38 39
}

A
Alex Dima 已提交
40
@Remotable.ExtHostContext('ExtHostEditors')
41
export class ExtHostEditors {
E
Erich Gamma 已提交
42 43 44 45 46 47 48

	public onDidChangeTextEditorSelection: Event<TextEditorSelectionChangeEvent>;
	private _onDidChangeTextEditorSelection: Emitter<TextEditorSelectionChangeEvent>;

	public onDidChangeTextEditorOptions: Event<TextEditorOptionsChangeEvent>;
	private _onDidChangeTextEditorOptions: Emitter<TextEditorOptionsChangeEvent>;

49 50 51
	public onDidChangeTextEditorViewColumn: Event<TextEditorViewColumnChangeEvent>;
	private _onDidChangeTextEditorViewColumn: Emitter<TextEditorViewColumnChangeEvent>;

52
	private _editors: { [id: string]: ExtHostTextEditor };
E
Erich Gamma 已提交
53 54
	private _proxy: MainThreadEditors;
	private _onDidChangeActiveTextEditor: Emitter<vscode.TextEditor>;
55
	private _modelService: ExtHostModelService;
E
Erich Gamma 已提交
56 57 58 59 60 61 62 63 64 65 66 67
	private _activeEditorId: string;
	private _visibleEditorIds: string[];

	constructor(
		@IThreadService threadService: IThreadService
	) {
		this._onDidChangeTextEditorSelection = new Emitter<TextEditorSelectionChangeEvent>();
		this.onDidChangeTextEditorSelection = this._onDidChangeTextEditorSelection.event;

		this._onDidChangeTextEditorOptions = new Emitter<TextEditorOptionsChangeEvent>();
		this.onDidChangeTextEditorOptions = this._onDidChangeTextEditorOptions.event;

68 69 70
		this._onDidChangeTextEditorViewColumn = new Emitter<TextEditorViewColumnChangeEvent>();
		this.onDidChangeTextEditorViewColumn = this._onDidChangeTextEditorViewColumn.event;

71
		this._modelService = threadService.getRemotable(ExtHostModelService);
E
Erich Gamma 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
		this._proxy = threadService.getRemotable(MainThreadEditors);
		this._onDidChangeActiveTextEditor = new Emitter<vscode.TextEditor>();
		this._editors = Object.create(null);

		this._visibleEditorIds = [];
	}

	getActiveTextEditor(): vscode.TextEditor {
		return this._activeEditorId && this._editors[this._activeEditorId];
	}

	getVisibleTextEditors(): vscode.TextEditor[] {
		return this._visibleEditorIds.map(id => this._editors[id]);
	}

	get onDidChangeActiveTextEditor(): Event<vscode.TextEditor> {
		return this._onDidChangeActiveTextEditor && this._onDidChangeActiveTextEditor.event;
	}

91 92
	showTextDocument(document: TextDocument, column: ViewColumn, preserveFocus: boolean): TPromise<vscode.TextEditor> {
		return this._proxy._tryShowTextDocument(<URI> document.uri, TypeConverters.fromViewColumn(column), preserveFocus).then(id => {
E
Erich Gamma 已提交
93 94 95 96
			let editor = this._editors[id];
			if (editor) {
				return editor;
			} else {
97
				throw new Error('Failed to create editor with id: ' + id);
E
Erich Gamma 已提交
98 99 100 101 102 103 104 105 106 107
			}
		});
	}

	createTextEditorDecorationType(options: vscode.DecorationRenderOptions): vscode.TextEditorDecorationType {
		return new TextEditorDecorationType(this._proxy, options);
	}

	// --- called from main thread

J
Johannes Rieken 已提交
108
	_acceptTextEditorAdd(data: ITextEditorAddData): void {
109
		let document = this._modelService.getDocumentData(data.document);
110
		let newEditor = new ExtHostTextEditor(this._proxy, data.id, document, data.selections.map(TypeConverters.toSelection), data.options, TypeConverters.toViewColumn(data.editorPosition));
E
Erich Gamma 已提交
111 112 113
		this._editors[data.id] = newEditor;
	}

114
	_acceptOptionsChanged(id: string, opts: IResolvedTextEditorConfiguration): void {
E
Erich Gamma 已提交
115 116 117 118 119 120 121 122
		let editor = this._editors[id];
		editor._acceptOptions(opts);
		this._onDidChangeTextEditorOptions.fire({
			textEditor: editor,
			options: opts
		});
	}

J
Johannes Rieken 已提交
123
	_acceptSelectionsChanged(id: string, _selections: ISelection[]): void {
E
Erich Gamma 已提交
124 125 126 127 128 129 130 131 132
		let selections = _selections.map(TypeConverters.toSelection);
		let editor = this._editors[id];
		editor._acceptSelections(selections);
		this._onDidChangeTextEditorSelection.fire({
			textEditor: editor,
			selections: selections
		});
	}

J
Johannes Rieken 已提交
133
	_acceptActiveEditorAndVisibleEditors(id: string, visibleIds: string[]): void {
E
Erich Gamma 已提交
134 135 136 137 138 139 140 141 142 143
		this._visibleEditorIds = visibleIds;

		if (this._activeEditorId === id) {
			// nothing to do
			return;
		}
		this._activeEditorId = id;
		this._onDidChangeActiveTextEditor.fire(this.getActiveTextEditor());
	}

144 145
	_acceptEditorPositionData(data: ITextEditorPositionData): void {
		for (let id in data) {
146 147 148 149 150
			let textEditor = this._editors[id];
			let viewColumn = TypeConverters.toViewColumn(data[id]);
			if (textEditor.viewColumn !== viewColumn) {
				textEditor._acceptViewColumn(viewColumn);
				this._onDidChangeTextEditorViewColumn.fire({ textEditor, viewColumn });
151 152 153 154
			}
		}
	}

J
Johannes Rieken 已提交
155
	_acceptTextEditorRemove(id: string): void {
E
Erich Gamma 已提交
156
		// make sure the removed editor is not visible
B
Benjamin Pasero 已提交
157
		let newVisibleEditors = this._visibleEditorIds.filter(visibleEditorId => visibleEditorId !== id);
E
Erich Gamma 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173

		if (this._activeEditorId === id) {
			// removing the current active editor
			this._acceptActiveEditorAndVisibleEditors(undefined, newVisibleEditors);
		} else {
			this._acceptActiveEditorAndVisibleEditors(this._activeEditorId, newVisibleEditors);
		}

		let editor = this._editors[id];
		editor.dispose();
		delete this._editors[id];
	}
}

class TextEditorDecorationType implements vscode.TextEditorDecorationType {

J
Johannes Rieken 已提交
174
	private static LAST_ID: number = 0;
E
Erich Gamma 已提交
175 176 177 178

	private _proxy: MainThreadEditors;
	public key: string;

J
Johannes Rieken 已提交
179
	constructor(proxy: MainThreadEditors, options: vscode.DecorationRenderOptions) {
E
Erich Gamma 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
		this.key = 'TextEditorDecorationType' + (++TextEditorDecorationType.LAST_ID);
		this._proxy = proxy;
		this._proxy._registerTextEditorDecorationType(this.key, <any>options);
	}

	public dispose(): void {
		this._proxy._removeTextEditorDecorationType(this.key);
	}
}

export interface ITextEditOperation {
	range: Range;
	text: string;
	forceMoveMarkers: boolean;
}

export interface IEditData {
	documentVersionId: number;
	edits: ITextEditOperation[];
}

export class TextEditorEdit {

	private _documentVersionId: number;
	private _collectedEdits: ITextEditOperation[];

	constructor(document: vscode.TextDocument) {
		this._documentVersionId = document.version;
		this._collectedEdits = [];
	}

	finalize(): IEditData {
		return {
			documentVersionId: this._documentVersionId,
			edits: this._collectedEdits
		};
	}

	replace(location: Position | Range | Selection, value: string): void {
		let range: Range = null;

		if (location instanceof Position) {
			range = new Range(location, location);
		} else if (location instanceof Range) {
			range = location;
		} else if (location instanceof Selection) {
			range = new Range(location.start, location.end);
		} else {
			throw new Error('Unrecognized location');
		}

		this._collectedEdits.push({
			range: range,
			text: value,
			forceMoveMarkers: false
		});
	}

	insert(location: Position, value: string): void {
		this._collectedEdits.push({
			range: new Range(location, location),
			text: value,
			forceMoveMarkers: true
		});
	}

	delete(location: Range | Selection): void {
		let range: Range = null;

		if (location instanceof Range) {
			range = location;
		} else if (location instanceof Selection) {
			range = new Range(location.start, location.end);
		} else {
			throw new Error('Unrecognized location');
		}

		this._collectedEdits.push({
			range: range,
			text: null,
			forceMoveMarkers: true
		});
	}
}

function readonly(name: string, alt?: string) {
	let message = `The property '${name}' is readonly.`;
	if (alt) {
B
Benjamin Pasero 已提交
268
		message += ` Use '${alt}' instead.`;
E
Erich Gamma 已提交
269 270 271 272 273 274 275 276
	}
	return new Error(message);
}

function illegalArg(name: string) {
	return new Error(`illgeal argument '${name}'`);
}

J
Johannes Rieken 已提交
277
function deprecated(name: string, message: string = 'Refer to the documentation for further details.') {
E
Erich Gamma 已提交
278 279 280 281 282
	return (target: Object, key: string, descriptor: TypedPropertyDescriptor<any>) => {
		const originalMethod = descriptor.value;
		descriptor.value = function(...args: any[]) {
			console.warn(`[Deprecation Warning] method '${name}' is deprecated and should no longer be used. ${message}`);
			return originalMethod.apply(this, args);
B
Benjamin Pasero 已提交
283
		};
E
Erich Gamma 已提交
284 285

		return descriptor;
B
Benjamin Pasero 已提交
286
	};
E
Erich Gamma 已提交
287 288
}

289
class ExtHostTextEditor implements vscode.TextEditor {
E
Erich Gamma 已提交
290 291 292 293

	private _proxy: MainThreadEditors;
	private _id: string;

294
	private _documentData: ExtHostDocumentData;
E
Erich Gamma 已提交
295 296
	private _selections: Selection[];
	private _options: TextEditorOptions;
297
	private _viewColumn: vscode.ViewColumn;
E
Erich Gamma 已提交
298

299
	constructor(proxy: MainThreadEditors, id: string, document: ExtHostDocumentData, selections: Selection[], options: EditorOptions, viewColumn: vscode.ViewColumn) {
E
Erich Gamma 已提交
300 301
		this._proxy = proxy;
		this._id = id;
302
		this._documentData = document;
E
Erich Gamma 已提交
303 304
		this._selections = selections;
		this._options = options;
305
		this._viewColumn = viewColumn;
E
Erich Gamma 已提交
306 307 308
	}

	dispose() {
309
		this._documentData = null;
E
Erich Gamma 已提交
310 311 312 313 314 315 316 317 318 319 320 321 322
	}

	@deprecated('TextEditor.show') show(column: vscode.ViewColumn) {
		this._proxy._tryShowEditor(this._id, TypeConverters.fromViewColumn(column));
	}

	@deprecated('TextEditor.hide') hide() {
		this._proxy._tryHideEditor(this._id);
	}

	// ---- the document

	get document(): vscode.TextDocument {
323
		return this._documentData.document;
E
Erich Gamma 已提交
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
	}

	set document(value) {
		throw readonly('document');
	}

	// ---- options

	get options(): TextEditorOptions {
		return this._options;
	}

	set options(value: TextEditorOptions) {
		this._options = value;
		this._runOnProxy(() => {
			return this._proxy._trySetOptions(this._id, this._options);
		}, true);
	}

	_acceptOptions(options: EditorOptions): void {
B
Benjamin Pasero 已提交
344
		this._options = options;
E
Erich Gamma 已提交
345 346
	}

347 348 349 350 351 352 353 354 355 356 357 358 359 360
	// ---- view column

	get viewColumn(): vscode.ViewColumn {
		return this._viewColumn;
	}

	set viewColumn(value) {
		throw readonly('viewColumn');
	}

	_acceptViewColumn(value: vscode.ViewColumn) {
		this._viewColumn = value;
	}

E
Erich Gamma 已提交
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
	// ---- selections

	get selection(): Selection {
		return this._selections && this._selections[0];
	}

	set selection(value: Selection) {
		if (!(value instanceof Selection)) {
			throw illegalArg('selection');
		}
		this._selections = [value];
		this._trySetSelection(true);
	}

	get selections(): Selection[] {
		return this._selections;
	}

	set selections(value: Selection[]) {
		if (!Array.isArray(value) || value.some(a => !(a instanceof Selection))) {
			throw illegalArg('selections');
		}
		this._selections = value;
		this._trySetSelection(true);
	}

J
Johannes Rieken 已提交
387
	setDecorations(decorationType: vscode.TextEditorDecorationType, ranges: Range[] | vscode.DecorationOptions[]): void {
E
Erich Gamma 已提交
388 389 390 391 392 393 394 395 396 397
		this._runOnProxy(
			() => this._proxy._trySetDecorations(
				this._id,
				decorationType.key,
				TypeConverters.fromRangeOrRangeWithMessage(ranges)
			),
			true
		);
	}

J
Johannes Rieken 已提交
398
	revealRange(range: Range, revealType: vscode.TextEditorRevealType): void {
E
Erich Gamma 已提交
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
		this._runOnProxy(
			() => this._proxy._tryRevealRange(
				this._id,
				TypeConverters.fromRange(range),
				(<TextEditorRevealType><any>revealType) || TextEditorRevealType.Default
			),
			true
		);
	}

	private _trySetSelection(silent: boolean): TPromise<vscode.TextEditor> {
		let selection = this._selections.map(TypeConverters.fromSelection);
		return this._runOnProxy(() => this._proxy._trySetSelections(this._id, selection), silent);
	}

J
Johannes Rieken 已提交
414
	_acceptSelections(selections: Selection[]): void {
E
Erich Gamma 已提交
415 416 417 418 419
		this._selections = selections;
	}

	// ---- editing

J
Johannes Rieken 已提交
420
	edit(callback: (edit: TextEditorEdit) => void): Thenable<boolean> {
421
		let edit = new TextEditorEdit(this._documentData.document);
E
Erich Gamma 已提交
422 423 424 425
		callback(edit);
		return this._applyEdit(edit);
	}

J
Johannes Rieken 已提交
426 427
	_applyEdit(editBuilder: TextEditorEdit): TPromise<boolean> {
		let editData = editBuilder.finalize();
E
Erich Gamma 已提交
428 429

		// prepare data for serialization
B
Benjamin Pasero 已提交
430
		let edits: ISingleEditOperation[] = editData.edits.map((edit) => {
E
Erich Gamma 已提交
431 432 433 434 435 436 437 438 439 440 441 442
			return {
				range: TypeConverters.fromRange(edit.range),
				text: edit.text,
				forceMoveMarkers: edit.forceMoveMarkers
			};
		});

		return this._proxy._tryApplyEdits(this._id, editData.documentVersionId, edits);
	}

	// ---- util

J
Johannes Rieken 已提交
443
	private _runOnProxy(callback: () => TPromise<any>, silent: boolean): TPromise<ExtHostTextEditor> {
E
Erich Gamma 已提交
444 445 446 447 448 449 450 451 452 453 454 455
		return callback().then(() => this, err => {
			if (!silent) {
				return TPromise.wrapError(silent);
			}
			console.warn(err);
		});
	}
}

@Remotable.MainContext('MainThreadEditors')
export class MainThreadEditors {

456
	private _proxy: ExtHostEditors;
E
Erich Gamma 已提交
457
	private _workbenchEditorService: IWorkbenchEditorService;
458
	private _telemetryService: ITelemetryService;
E
Erich Gamma 已提交
459 460
	private _editorTracker: MainThreadEditorsTracker;
	private _toDispose: IDisposable[];
J
Johannes Rieken 已提交
461 462
	private _textEditorsListenersMap: { [editorId: string]: IDisposable[]; };
	private _textEditorsMap: { [editorId: string]: MainThreadTextEditor; };
E
Erich Gamma 已提交
463 464
	private _activeTextEditor: string;
	private _visibleEditors: string[];
465
	private _editorPositionData: ITextEditorPositionData;
E
Erich Gamma 已提交
466 467 468 469

	constructor(
		@IThreadService threadService: IThreadService,
		@IWorkbenchEditorService workbenchEditorService: IWorkbenchEditorService,
470
		@ITelemetryService telemetryService: ITelemetryService,
J
Johannes Rieken 已提交
471 472 473
		@ICodeEditorService editorService: ICodeEditorService,
		@IEventService eventService: IEventService,
		@IModelService modelService: IModelService
E
Erich Gamma 已提交
474
	) {
475
		this._proxy = threadService.getRemotable(ExtHostEditors);
E
Erich Gamma 已提交
476
		this._workbenchEditorService = workbenchEditorService;
477
		this._telemetryService = telemetryService;
E
Erich Gamma 已提交
478 479 480 481 482
		this._toDispose = [];
		this._textEditorsListenersMap = Object.create(null);
		this._textEditorsMap = Object.create(null);
		this._activeTextEditor = null;
		this._visibleEditors = [];
483
		this._editorPositionData = null;
E
Erich Gamma 已提交
484 485 486 487 488 489 490 491 492 493

		this._editorTracker = new MainThreadEditorsTracker(editorService, modelService);
		this._toDispose.push(this._editorTracker);

		this._toDispose.push(this._editorTracker.onTextEditorAdd((textEditor) => this._onTextEditorAdd(textEditor)));
		this._toDispose.push(this._editorTracker.onTextEditorRemove((textEditor) => this._onTextEditorRemove(textEditor)));

		this._toDispose.push(this._editorTracker.onDidUpdateTextEditors(() => this._updateActiveAndVisibleTextEditors()));
		this._toDispose.push(this._editorTracker.onChangedFocusedTextEditor((focusedTextEditorId) => this._updateActiveAndVisibleTextEditors()));
		this._toDispose.push(eventService.addListener2(EventType.EDITOR_INPUT_CHANGED, () => this._updateActiveAndVisibleTextEditors()));
494
		this._toDispose.push(eventService.addListener2(EventType.EDITOR_POSITION_CHANGED, () => this._updateActiveAndVisibleTextEditors()));
E
Erich Gamma 已提交
495 496 497 498 499 500 501 502 503 504
	}

	public dispose(): void {
		Object.keys(this._textEditorsListenersMap).forEach((editorId) => {
			disposeAll(this._textEditorsListenersMap[editorId]);
		});
		this._textEditorsListenersMap = Object.create(null);
		this._toDispose = disposeAll(this._toDispose);
	}

J
Johannes Rieken 已提交
505
	private _onTextEditorAdd(textEditor: MainThreadTextEditor): void {
E
Erich Gamma 已提交
506 507 508 509 510 511 512 513 514 515 516 517
		let id = textEditor.getId();
		let toDispose: IDisposable[] = [];
		toDispose.push(textEditor.onConfigurationChanged((opts) => {
			this._proxy._acceptOptionsChanged(id, opts);
		}));
		toDispose.push(textEditor.onSelectionChanged((selection) => {
			this._proxy._acceptSelectionsChanged(id, selection);
		}));
		this._proxy._acceptTextEditorAdd({
			id: id,
			document: textEditor.getModel().getAssociatedResource(),
			options: textEditor.getConfiguration(),
518 519
			selections: textEditor.getSelections(),
			editorPosition: this._findEditorPosition(textEditor)
E
Erich Gamma 已提交
520 521 522 523 524 525
		});

		this._textEditorsListenersMap[id] = toDispose;
		this._textEditorsMap[id] = textEditor;
	}

J
Johannes Rieken 已提交
526
	private _onTextEditorRemove(textEditor: MainThreadTextEditor): void {
E
Erich Gamma 已提交
527 528 529 530 531 532 533 534
		let id = textEditor.getId();
		disposeAll(this._textEditorsListenersMap[id]);
		delete this._textEditorsListenersMap[id];
		delete this._textEditorsMap[id];
		this._proxy._acceptTextEditorRemove(id);
	}

	private _updateActiveAndVisibleTextEditors(): void {
535 536

		// active and visible editors
E
Erich Gamma 已提交
537 538
		let visibleEditors = this._editorTracker.getVisibleTextEditorIds();
		let activeEditor = this._findActiveTextEditorId();
539 540 541 542 543
		if (activeEditor !== this._activeTextEditor || !arrayEquals(this._visibleEditors, visibleEditors, (a, b) => a === b)) {
			this._activeTextEditor = activeEditor;
			this._visibleEditors = visibleEditors;
			this._proxy._acceptActiveEditorAndVisibleEditors(this._activeTextEditor, this._visibleEditors);
		}
E
Erich Gamma 已提交
544

545 546 547 548 549
		// editor columns
		let editorPositionData = this._getTextEditorPositionData();
		if (!objectEquals(this._editorPositionData, editorPositionData)) {
			this._editorPositionData = editorPositionData;
			this._proxy._acceptEditorPositionData(this._editorPositionData);
E
Erich Gamma 已提交
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
		}
	}

	private _findActiveTextEditorId(): string {
		let focusedTextEditorId = this._editorTracker.getFocusedTextEditorId();
		if (focusedTextEditorId) {
			return focusedTextEditorId;
		}

		let activeEditor = this._workbenchEditorService.getActiveEditor();
		if (!activeEditor) {
			return null;
		}

		let editor = <IEditor>activeEditor.getControl();
		// Substitute for (editor instanceof ICodeEditor)
		if (!editor || typeof editor.getEditorType !== 'function') {
			// Not a text editor...
			return null;
		}

		if (editor.getEditorType() === EditorType.ICodeEditor) {
			return this._editorTracker.findTextEditorIdFor(<ICommonCodeEditor>editor);
		}

		// Must be a diff editor => use the modified side
		return this._editorTracker.findTextEditorIdFor((<ICommonDiffEditor>editor).getModifiedEditor());
	}

579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
	private _findEditorPosition(editor: MainThreadTextEditor): EditorPosition {
		for (let workbenchEditor of this._workbenchEditorService.getVisibleEditors()) {
			if (editor.matches(workbenchEditor)) {
				return workbenchEditor.position;
			}
		}
	}

	private _getTextEditorPositionData(): ITextEditorPositionData {
		let result: ITextEditorPositionData = Object.create(null);
		for (let workbenchEditor of this._workbenchEditorService.getVisibleEditors()) {
			let editor = <IEditor>workbenchEditor.getControl();
			// Substitute for (editor instanceof ICodeEditor)
			if (!editor || typeof editor.getEditorType !== 'function') {
				// Not a text editor...
				continue;
			}
			if (editor.getEditorType() === EditorType.ICodeEditor) {
				let id = this._editorTracker.findTextEditorIdFor(<ICommonCodeEditor>editor);
				if (id) {
					result[id] = workbenchEditor.position;
				}
			}
		}
		return result;
	}

A
Alex Dima 已提交
606
	// --- from extension host process
E
Erich Gamma 已提交
607

608
	_tryShowTextDocument(resource: URI, position: EditorPosition, preserveFocus: boolean): TPromise<string> {
E
Erich Gamma 已提交
609

J
Johannes Rieken 已提交
610 611 612 613
		const input = {
			resource,
			options: { preserveFocus }
		};
E
Erich Gamma 已提交
614

J
Johannes Rieken 已提交
615
		return this._workbenchEditorService.openEditor(input, position).then(editor => {
E
Erich Gamma 已提交
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633

			return new TPromise<void>(c => {
				// not very nice but the way it is: changes to the editor state aren't
				// send to the ext host as they happen but stuff is delayed a little. in
				// order to provide the real editor on #openTextEditor we need to sync on
				// that update
				let subscription: IDisposable;
				let handle: number;
				function contd() {
					subscription.dispose();
					clearTimeout(handle);
					c(undefined);
				}
				subscription = this._editorTracker.onDidUpdateTextEditors(() => {
					contd();
				});
				handle = setTimeout(() => {
					contd();
634
				}, 1000);
E
Erich Gamma 已提交
635 636 637 638 639 640 641 642 643 644 645 646 647 648

			}).then(() => {
				// find the editor we have just opened and return the
				// id we have assigned to it.
				for (let id in this._textEditorsMap) {
					if (this._textEditorsMap[id].matches(editor)) {
						return id;
					}
				}
			});
		});
	}

	_tryShowEditor(id: string, position: EditorPosition): TPromise<void> {
649 650 651
		// check how often this is used
		this._telemetryService.publicLog('api.deprecated', { function: 'TextEditor.show' });

E
Erich Gamma 已提交
652 653 654 655 656 657
		let mainThreadEditor = this._textEditorsMap[id];
		if (mainThreadEditor) {
			let model = mainThreadEditor.getModel();
			return this._workbenchEditorService.openEditor({
				resource: model.getAssociatedResource(),
				options: { preserveFocus: false }
J
Johannes Rieken 已提交
658
			}, position).then(() => { return; });
E
Erich Gamma 已提交
659 660 661 662
		}
	}

	_tryHideEditor(id: string): TPromise<void> {
663 664 665
		// check how often this is used
		this._telemetryService.publicLog('api.deprecated', { function: 'TextEditor.hide' });

E
Erich Gamma 已提交
666 667 668 669 670
		let mainThreadEditor = this._textEditorsMap[id];
		if (mainThreadEditor) {
			let editors = this._workbenchEditorService.getVisibleEditors();
			for (let editor of editors) {
				if (mainThreadEditor.matches(editor)) {
J
Johannes Rieken 已提交
671
					return this._workbenchEditorService.closeEditor(editor).then(() => { return; });
E
Erich Gamma 已提交
672 673 674 675 676 677 678 679 680 681 682 683 684
				}
			}
		}
	}

	_trySetSelections(id: string, selections: ISelection[]): TPromise<any> {
		if (!this._textEditorsMap[id]) {
			return TPromise.wrapError('TextEditor disposed');
		}
		this._textEditorsMap[id].setSelections(selections);
		return TPromise.as(null);
	}

J
Johannes Rieken 已提交
685
	_trySetDecorations(id: string, key: string, ranges: IRangeWithMessage[]): TPromise<any> {
E
Erich Gamma 已提交
686 687 688 689 690 691 692
		if (!this._textEditorsMap[id]) {
			return TPromise.wrapError('TextEditor disposed');
		}
		this._textEditorsMap[id].setDecorations(key, ranges);
		return TPromise.as(null);
	}

J
Johannes Rieken 已提交
693
	_tryRevealRange(id: string, range: IRange, revealType: TextEditorRevealType): TPromise<any> {
E
Erich Gamma 已提交
694 695 696 697 698 699
		if (!this._textEditorsMap[id]) {
			return TPromise.wrapError('TextEditor disposed');
		}
		this._textEditorsMap[id].revealRange(range, revealType);
	}

700
	_trySetOptions(id: string, options: ITextEditorConfigurationUpdate): TPromise<any> {
E
Erich Gamma 已提交
701 702 703 704 705 706 707
		if (!this._textEditorsMap[id]) {
			return TPromise.wrapError('TextEditor disposed');
		}
		this._textEditorsMap[id].setConfiguration(options);
		return TPromise.as(null);
	}

J
Johannes Rieken 已提交
708
	_tryApplyEdits(id: string, modelVersionId: number, edits: ISingleEditOperation[]): TPromise<boolean> {
E
Erich Gamma 已提交
709 710 711 712 713 714
		if (!this._textEditorsMap[id]) {
			return TPromise.wrapError('TextEditor disposed');
		}
		return TPromise.as(this._textEditorsMap[id].applyEdits(modelVersionId, edits));
	}

J
Johannes Rieken 已提交
715
	_registerTextEditorDecorationType(key: string, options: IDecorationRenderOptions): void {
E
Erich Gamma 已提交
716 717 718
		this._editorTracker.registerTextEditorDecorationType(key, options);
	}

J
Johannes Rieken 已提交
719
	_removeTextEditorDecorationType(key: string): void {
E
Erich Gamma 已提交
720 721 722
		this._editorTracker.removeTextEditorDecorationType(key);
	}
}