extHostEditors.ts 23.6 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8
/*---------------------------------------------------------------------------------------------
 *  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';
J
Joao Moreno 已提交
9
import {IDisposable, dispose} from 'vs/base/common/lifecycle';
E
Erich Gamma 已提交
10 11
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, EndOfLine} 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
		this._proxy = threadService.getRemotable(MainThreadEditors);
		this._onDidChangeActiveTextEditor = new Emitter<vscode.TextEditor>();
		this._editors = Object.create(null);

		this._visibleEditorIds = [];
	}

	getActiveTextEditor(): vscode.TextEditor {
80
		return this._editors[this._activeEditorId];
E
Erich Gamma 已提交
81 82 83 84 85 86 87 88 89 90
	}

	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 show text document ${document.uri.toString()}, should show in editor #${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
		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[];
199
	setEndOfLine: EndOfLine;
E
Erich Gamma 已提交
200 201 202 203 204 205
}

export class TextEditorEdit {

	private _documentVersionId: number;
	private _collectedEdits: ITextEditOperation[];
206
	private _setEndOfLine: EndOfLine;
E
Erich Gamma 已提交
207 208 209 210

	constructor(document: vscode.TextDocument) {
		this._documentVersionId = document.version;
		this._collectedEdits = [];
211
		this._setEndOfLine = 0;
E
Erich Gamma 已提交
212 213 214 215 216
	}

	finalize(): IEditData {
		return {
			documentVersionId: this._documentVersionId,
217 218
			edits: this._collectedEdits,
			setEndOfLine: this._setEndOfLine
E
Erich Gamma 已提交
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
		};
	}

	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
		});
	}
267 268 269 270 271 272 273 274

	setEndOfLine(endOfLine:EndOfLine): void {
		if (endOfLine !== EndOfLine.LF && endOfLine !== EndOfLine.CRLF) {
			throw illegalArg('endOfLine');
		}

		this._setEndOfLine = endOfLine;
	}
E
Erich Gamma 已提交
275 276 277 278 279
}

function readonly(name: string, alt?: string) {
	let message = `The property '${name}' is readonly.`;
	if (alt) {
B
Benjamin Pasero 已提交
280
		message += ` Use '${alt}' instead.`;
E
Erich Gamma 已提交
281 282 283 284 285 286 287 288
	}
	return new Error(message);
}

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

J
Johannes Rieken 已提交
289
function deprecated(name: string, message: string = 'Refer to the documentation for further details.') {
E
Erich Gamma 已提交
290 291 292 293 294
	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 已提交
295
		};
E
Erich Gamma 已提交
296 297

		return descriptor;
B
Benjamin Pasero 已提交
298
	};
E
Erich Gamma 已提交
299 300
}

301
class ExtHostTextEditor implements vscode.TextEditor {
E
Erich Gamma 已提交
302 303 304 305

	private _proxy: MainThreadEditors;
	private _id: string;

306
	private _documentData: ExtHostDocumentData;
E
Erich Gamma 已提交
307 308
	private _selections: Selection[];
	private _options: TextEditorOptions;
309
	private _viewColumn: vscode.ViewColumn;
E
Erich Gamma 已提交
310

311
	constructor(proxy: MainThreadEditors, id: string, document: ExtHostDocumentData, selections: Selection[], options: EditorOptions, viewColumn: vscode.ViewColumn) {
E
Erich Gamma 已提交
312 313
		this._proxy = proxy;
		this._id = id;
314
		this._documentData = document;
E
Erich Gamma 已提交
315 316
		this._selections = selections;
		this._options = options;
317
		this._viewColumn = viewColumn;
E
Erich Gamma 已提交
318 319 320
	}

	dispose() {
321
		this._documentData = null;
E
Erich Gamma 已提交
322 323 324 325 326 327 328 329 330 331 332 333 334
	}

	@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 {
335
		return this._documentData.document;
E
Erich Gamma 已提交
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
	}

	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 已提交
356
		this._options = options;
E
Erich Gamma 已提交
357 358
	}

359 360 361 362 363 364 365 366 367 368 369 370 371 372
	// ---- 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 已提交
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
	// ---- 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 已提交
399
	setDecorations(decorationType: vscode.TextEditorDecorationType, ranges: Range[] | vscode.DecorationOptions[]): void {
E
Erich Gamma 已提交
400 401 402 403 404 405 406 407 408 409
		this._runOnProxy(
			() => this._proxy._trySetDecorations(
				this._id,
				decorationType.key,
				TypeConverters.fromRangeOrRangeWithMessage(ranges)
			),
			true
		);
	}

J
Johannes Rieken 已提交
410
	revealRange(range: Range, revealType: vscode.TextEditorRevealType): void {
E
Erich Gamma 已提交
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
		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 已提交
426
	_acceptSelections(selections: Selection[]): void {
E
Erich Gamma 已提交
427 428 429 430 431
		this._selections = selections;
	}

	// ---- editing

J
Johannes Rieken 已提交
432
	edit(callback: (edit: TextEditorEdit) => void): Thenable<boolean> {
433
		let edit = new TextEditorEdit(this._documentData.document);
E
Erich Gamma 已提交
434 435 436 437
		callback(edit);
		return this._applyEdit(edit);
	}

J
Johannes Rieken 已提交
438 439
	_applyEdit(editBuilder: TextEditorEdit): TPromise<boolean> {
		let editData = editBuilder.finalize();
E
Erich Gamma 已提交
440 441

		// prepare data for serialization
B
Benjamin Pasero 已提交
442
		let edits: ISingleEditOperation[] = editData.edits.map((edit) => {
E
Erich Gamma 已提交
443 444 445 446 447 448 449
			return {
				range: TypeConverters.fromRange(edit.range),
				text: edit.text,
				forceMoveMarkers: edit.forceMoveMarkers
			};
		});

450
		return this._proxy._tryApplyEdits(this._id, editData.documentVersionId, edits, editData.setEndOfLine);
E
Erich Gamma 已提交
451 452 453 454
	}

	// ---- util

J
Johannes Rieken 已提交
455
	private _runOnProxy(callback: () => TPromise<any>, silent: boolean): TPromise<ExtHostTextEditor> {
E
Erich Gamma 已提交
456 457 458 459 460 461 462 463 464 465 466 467
		return callback().then(() => this, err => {
			if (!silent) {
				return TPromise.wrapError(silent);
			}
			console.warn(err);
		});
	}
}

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

468
	private _proxy: ExtHostEditors;
E
Erich Gamma 已提交
469
	private _workbenchEditorService: IWorkbenchEditorService;
470
	private _telemetryService: ITelemetryService;
E
Erich Gamma 已提交
471 472
	private _editorTracker: MainThreadEditorsTracker;
	private _toDispose: IDisposable[];
J
Johannes Rieken 已提交
473 474
	private _textEditorsListenersMap: { [editorId: string]: IDisposable[]; };
	private _textEditorsMap: { [editorId: string]: MainThreadTextEditor; };
E
Erich Gamma 已提交
475 476
	private _activeTextEditor: string;
	private _visibleEditors: string[];
477
	private _editorPositionData: ITextEditorPositionData;
E
Erich Gamma 已提交
478 479 480 481

	constructor(
		@IThreadService threadService: IThreadService,
		@IWorkbenchEditorService workbenchEditorService: IWorkbenchEditorService,
482
		@ITelemetryService telemetryService: ITelemetryService,
J
Johannes Rieken 已提交
483 484 485
		@ICodeEditorService editorService: ICodeEditorService,
		@IEventService eventService: IEventService,
		@IModelService modelService: IModelService
E
Erich Gamma 已提交
486
	) {
487
		this._proxy = threadService.getRemotable(ExtHostEditors);
E
Erich Gamma 已提交
488
		this._workbenchEditorService = workbenchEditorService;
489
		this._telemetryService = telemetryService;
E
Erich Gamma 已提交
490 491 492 493 494
		this._toDispose = [];
		this._textEditorsListenersMap = Object.create(null);
		this._textEditorsMap = Object.create(null);
		this._activeTextEditor = null;
		this._visibleEditors = [];
495
		this._editorPositionData = null;
E
Erich Gamma 已提交
496 497 498 499 500 501 502 503 504 505

		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()));
506
		this._toDispose.push(eventService.addListener2(EventType.EDITOR_POSITION_CHANGED, () => this._updateActiveAndVisibleTextEditors()));
E
Erich Gamma 已提交
507 508 509 510
	}

	public dispose(): void {
		Object.keys(this._textEditorsListenersMap).forEach((editorId) => {
J
Joao Moreno 已提交
511
			dispose(this._textEditorsListenersMap[editorId]);
E
Erich Gamma 已提交
512 513
		});
		this._textEditorsListenersMap = Object.create(null);
J
Joao Moreno 已提交
514
		this._toDispose = dispose(this._toDispose);
E
Erich Gamma 已提交
515 516
	}

J
Johannes Rieken 已提交
517
	private _onTextEditorAdd(textEditor: MainThreadTextEditor): void {
E
Erich Gamma 已提交
518 519 520 521 522 523 524 525 526 527 528 529
		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(),
530 531
			selections: textEditor.getSelections(),
			editorPosition: this._findEditorPosition(textEditor)
E
Erich Gamma 已提交
532 533 534 535 536 537
		});

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

J
Johannes Rieken 已提交
538
	private _onTextEditorRemove(textEditor: MainThreadTextEditor): void {
E
Erich Gamma 已提交
539
		let id = textEditor.getId();
J
Joao Moreno 已提交
540
		dispose(this._textEditorsListenersMap[id]);
E
Erich Gamma 已提交
541 542 543 544 545 546
		delete this._textEditorsListenersMap[id];
		delete this._textEditorsMap[id];
		this._proxy._acceptTextEditorRemove(id);
	}

	private _updateActiveAndVisibleTextEditors(): void {
547 548

		// active and visible editors
E
Erich Gamma 已提交
549 550
		let visibleEditors = this._editorTracker.getVisibleTextEditorIds();
		let activeEditor = this._findActiveTextEditorId();
551 552 553 554 555
		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 已提交
556

557 558 559 560 561
		// editor columns
		let editorPositionData = this._getTextEditorPositionData();
		if (!objectEquals(this._editorPositionData, editorPositionData)) {
			this._editorPositionData = editorPositionData;
			this._proxy._acceptEditorPositionData(this._editorPositionData);
E
Erich Gamma 已提交
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
		}
	}

	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());
	}

591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
	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 已提交
618
	// --- from extension host process
E
Erich Gamma 已提交
619

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

J
Johannes Rieken 已提交
622 623 624 625
		const input = {
			resource,
			options: { preserveFocus }
		};
E
Erich Gamma 已提交
626

J
Johannes Rieken 已提交
627
		return this._workbenchEditorService.openEditor(input, position).then(editor => {
E
Erich Gamma 已提交
628

629 630 631 632
			if (!editor) {
				return;
			}

E
Erich Gamma 已提交
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
			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();
650
				}, 1000);
E
Erich Gamma 已提交
651 652 653 654 655 656 657 658 659 660 661 662 663 664

			}).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> {
665 666 667
		// check how often this is used
		this._telemetryService.publicLog('api.deprecated', { function: 'TextEditor.show' });

E
Erich Gamma 已提交
668 669 670 671 672 673
		let mainThreadEditor = this._textEditorsMap[id];
		if (mainThreadEditor) {
			let model = mainThreadEditor.getModel();
			return this._workbenchEditorService.openEditor({
				resource: model.getAssociatedResource(),
				options: { preserveFocus: false }
J
Johannes Rieken 已提交
674
			}, position).then(() => { return; });
E
Erich Gamma 已提交
675 676 677 678
		}
	}

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

E
Erich Gamma 已提交
682 683 684 685 686
		let mainThreadEditor = this._textEditorsMap[id];
		if (mainThreadEditor) {
			let editors = this._workbenchEditorService.getVisibleEditors();
			for (let editor of editors) {
				if (mainThreadEditor.matches(editor)) {
J
Johannes Rieken 已提交
687
					return this._workbenchEditorService.closeEditor(editor).then(() => { return; });
E
Erich Gamma 已提交
688 689 690 691 692 693 694 695 696 697 698 699 700
				}
			}
		}
	}

	_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 已提交
701
	_trySetDecorations(id: string, key: string, ranges: IRangeWithMessage[]): TPromise<any> {
E
Erich Gamma 已提交
702 703 704 705 706 707 708
		if (!this._textEditorsMap[id]) {
			return TPromise.wrapError('TextEditor disposed');
		}
		this._textEditorsMap[id].setDecorations(key, ranges);
		return TPromise.as(null);
	}

J
Johannes Rieken 已提交
709
	_tryRevealRange(id: string, range: IRange, revealType: TextEditorRevealType): TPromise<any> {
E
Erich Gamma 已提交
710 711 712 713 714 715
		if (!this._textEditorsMap[id]) {
			return TPromise.wrapError('TextEditor disposed');
		}
		this._textEditorsMap[id].revealRange(range, revealType);
	}

716
	_trySetOptions(id: string, options: ITextEditorConfigurationUpdate): TPromise<any> {
E
Erich Gamma 已提交
717 718 719 720 721 722 723
		if (!this._textEditorsMap[id]) {
			return TPromise.wrapError('TextEditor disposed');
		}
		this._textEditorsMap[id].setConfiguration(options);
		return TPromise.as(null);
	}

724
	_tryApplyEdits(id: string, modelVersionId: number, edits: ISingleEditOperation[], setEndOfLine:EndOfLine): TPromise<boolean> {
E
Erich Gamma 已提交
725 726 727
		if (!this._textEditorsMap[id]) {
			return TPromise.wrapError('TextEditor disposed');
		}
728
		return TPromise.as(this._textEditorsMap[id].applyEdits(modelVersionId, edits, setEndOfLine));
E
Erich Gamma 已提交
729 730
	}

J
Johannes Rieken 已提交
731
	_registerTextEditorDecorationType(key: string, options: IDecorationRenderOptions): void {
E
Erich Gamma 已提交
732 733 734
		this._editorTracker.registerTextEditorDecorationType(key, options);
	}

J
Johannes Rieken 已提交
735
	_removeTextEditorDecorationType(key: string): void {
E
Erich Gamma 已提交
736 737 738
		this._editorTracker.removeTextEditorDecorationType(key);
	}
}