extHostEditors.ts 12.9 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7
/*---------------------------------------------------------------------------------------------
 *  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';
J
Johannes Rieken 已提交
8
import {readonly, illegalArgument} from 'vs/base/common/errors';
J
Johannes Rieken 已提交
9
import {IdGenerator} from 'vs/base/common/idGenerator';
E
Erich Gamma 已提交
10 11
import Event, {Emitter} from 'vs/base/common/event';
import {TPromise} from 'vs/base/common/winjs.base';
12
import {IThreadService} from 'vs/workbench/services/thread/common/threadService';
13 14 15 16
import {ExtHostDocuments, ExtHostDocumentData} from 'vs/workbench/api/node/extHostDocuments';
import {Selection, Range, Position, EditorOptions, EndOfLine, TextEditorRevealType} from './extHostTypes';
import {ISingleEditOperation, ISelection} from 'vs/editor/common/editorCommon';
import {IResolvedTextEditorConfiguration} from 'vs/workbench/api/node/mainThreadEditorsTracker';
17
import * as TypeConverters from './extHostTypeConverters';
18
import {TextDocument, TextEditorSelectionChangeEvent, TextEditorOptionsChangeEvent, TextEditorOptions, TextEditorViewColumnChangeEvent, ViewColumn} from 'vscode';
A
Alex Dima 已提交
19
import {MainContext, MainThreadEditorsShape, ExtHostEditorsShape, ITextEditorAddData, ITextEditorPositionData} from './extHost.protocol';
E
Erich Gamma 已提交
20

A
Alex Dima 已提交
21
export class ExtHostEditors extends ExtHostEditorsShape {
E
Erich Gamma 已提交
22 23 24 25 26 27 28

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

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

29 30 31
	public onDidChangeTextEditorViewColumn: Event<TextEditorViewColumnChangeEvent>;
	private _onDidChangeTextEditorViewColumn: Emitter<TextEditorViewColumnChangeEvent>;

32
	private _editors: { [id: string]: ExtHostTextEditor };
33
	private _proxy: MainThreadEditorsShape;
E
Erich Gamma 已提交
34
	private _onDidChangeActiveTextEditor: Emitter<vscode.TextEditor>;
35
	private _extHostDocuments: ExtHostDocuments;
E
Erich Gamma 已提交
36 37 38 39
	private _activeEditorId: string;
	private _visibleEditorIds: string[];

	constructor(
40
		threadService: IThreadService,
41
		extHostDocuments: ExtHostDocuments
E
Erich Gamma 已提交
42
	) {
A
Alex Dima 已提交
43
		super();
E
Erich Gamma 已提交
44 45 46 47 48 49
		this._onDidChangeTextEditorSelection = new Emitter<TextEditorSelectionChangeEvent>();
		this.onDidChangeTextEditorSelection = this._onDidChangeTextEditorSelection.event;

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

50 51 52
		this._onDidChangeTextEditorViewColumn = new Emitter<TextEditorViewColumnChangeEvent>();
		this.onDidChangeTextEditorViewColumn = this._onDidChangeTextEditorViewColumn.event;

53
		this._extHostDocuments = extHostDocuments;
54
		this._proxy = threadService.get(MainContext.MainThreadEditors);
E
Erich Gamma 已提交
55 56 57 58 59 60 61
		this._onDidChangeActiveTextEditor = new Emitter<vscode.TextEditor>();
		this._editors = Object.create(null);

		this._visibleEditorIds = [];
	}

	getActiveTextEditor(): vscode.TextEditor {
62
		return this._editors[this._activeEditorId];
E
Erich Gamma 已提交
63 64 65 66 67 68 69 70 71 72
	}

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

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

73 74
	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 已提交
75 76 77 78
			let editor = this._editors[id];
			if (editor) {
				return editor;
			} else {
79
				throw new Error(`Failed to show text document ${document.uri.toString()}, should show in editor #${id}`);
E
Erich Gamma 已提交
80 81 82 83 84 85 86 87 88 89
			}
		});
	}

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

	// --- called from main thread

J
Johannes Rieken 已提交
90
	_acceptTextEditorAdd(data: ITextEditorAddData): void {
91
		let document = this._extHostDocuments.getDocumentData(data.document);
92
		let newEditor = new ExtHostTextEditor(this._proxy, data.id, document, data.selections.map(TypeConverters.toSelection), data.options, TypeConverters.toViewColumn(data.editorPosition));
E
Erich Gamma 已提交
93 94 95
		this._editors[data.id] = newEditor;
	}

96
	_acceptOptionsChanged(id: string, opts: IResolvedTextEditorConfiguration): void {
E
Erich Gamma 已提交
97 98 99 100 101 102 103 104
		let editor = this._editors[id];
		editor._acceptOptions(opts);
		this._onDidChangeTextEditorOptions.fire({
			textEditor: editor,
			options: opts
		});
	}

J
Johannes Rieken 已提交
105
	_acceptSelectionsChanged(id: string, _selections: ISelection[]): void {
E
Erich Gamma 已提交
106 107 108 109 110 111 112 113 114
		let selections = _selections.map(TypeConverters.toSelection);
		let editor = this._editors[id];
		editor._acceptSelections(selections);
		this._onDidChangeTextEditorSelection.fire({
			textEditor: editor,
			selections: selections
		});
	}

J
Johannes Rieken 已提交
115
	_acceptActiveEditorAndVisibleEditors(id: string, visibleIds: string[]): void {
E
Erich Gamma 已提交
116 117 118 119 120 121 122 123 124 125
		this._visibleEditorIds = visibleIds;

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

126 127
	_acceptEditorPositionData(data: ITextEditorPositionData): void {
		for (let id in data) {
128 129 130 131 132
			let textEditor = this._editors[id];
			let viewColumn = TypeConverters.toViewColumn(data[id]);
			if (textEditor.viewColumn !== viewColumn) {
				textEditor._acceptViewColumn(viewColumn);
				this._onDidChangeTextEditorViewColumn.fire({ textEditor, viewColumn });
133 134 135 136
			}
		}
	}

J
Johannes Rieken 已提交
137
	_acceptTextEditorRemove(id: string): void {
E
Erich Gamma 已提交
138
		// make sure the removed editor is not visible
B
Benjamin Pasero 已提交
139
		let newVisibleEditors = this._visibleEditorIds.filter(visibleEditorId => visibleEditorId !== id);
E
Erich Gamma 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155

		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 已提交
156
	private static _Keys = new IdGenerator('TextEditorDecorationType');
E
Erich Gamma 已提交
157

158
	private _proxy: MainThreadEditorsShape;
E
Erich Gamma 已提交
159 160
	public key: string;

161
	constructor(proxy: MainThreadEditorsShape, options: vscode.DecorationRenderOptions) {
J
Johannes Rieken 已提交
162
		this.key = TextEditorDecorationType._Keys.nextId();
E
Erich Gamma 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
		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[];
181
	setEndOfLine: EndOfLine;
E
Erich Gamma 已提交
182 183 184 185 186 187
}

export class TextEditorEdit {

	private _documentVersionId: number;
	private _collectedEdits: ITextEditOperation[];
188
	private _setEndOfLine: EndOfLine;
E
Erich Gamma 已提交
189 190 191 192

	constructor(document: vscode.TextDocument) {
		this._documentVersionId = document.version;
		this._collectedEdits = [];
193
		this._setEndOfLine = 0;
E
Erich Gamma 已提交
194 195 196 197 198
	}

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

	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
		});
	}
249 250 251

	setEndOfLine(endOfLine:EndOfLine): void {
		if (endOfLine !== EndOfLine.LF && endOfLine !== EndOfLine.CRLF) {
J
Johannes Rieken 已提交
252
			throw illegalArgument('endOfLine');
253 254 255 256
		}

		this._setEndOfLine = endOfLine;
	}
E
Erich Gamma 已提交
257 258 259
}


J
Johannes Rieken 已提交
260
function deprecated(name: string, message: string = 'Refer to the documentation for further details.') {
E
Erich Gamma 已提交
261 262 263 264 265
	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 已提交
266
		};
E
Erich Gamma 已提交
267 268

		return descriptor;
B
Benjamin Pasero 已提交
269
	};
E
Erich Gamma 已提交
270 271
}

272
class ExtHostTextEditor implements vscode.TextEditor {
E
Erich Gamma 已提交
273

274
	private _proxy: MainThreadEditorsShape;
E
Erich Gamma 已提交
275 276
	private _id: string;

277
	private _documentData: ExtHostDocumentData;
E
Erich Gamma 已提交
278 279
	private _selections: Selection[];
	private _options: TextEditorOptions;
280
	private _viewColumn: vscode.ViewColumn;
E
Erich Gamma 已提交
281

282
	constructor(proxy: MainThreadEditorsShape, id: string, document: ExtHostDocumentData, selections: Selection[], options: EditorOptions, viewColumn: vscode.ViewColumn) {
E
Erich Gamma 已提交
283 284
		this._proxy = proxy;
		this._id = id;
285
		this._documentData = document;
E
Erich Gamma 已提交
286 287
		this._selections = selections;
		this._options = options;
288
		this._viewColumn = viewColumn;
E
Erich Gamma 已提交
289 290 291
	}

	dispose() {
292
		this._documentData = null;
E
Erich Gamma 已提交
293 294 295 296 297 298 299 300 301 302 303 304 305
	}

	@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 {
306
		return this._documentData.document;
E
Erich Gamma 已提交
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
	}

	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 已提交
327
		this._options = options;
E
Erich Gamma 已提交
328 329
	}

330 331 332 333 334 335 336 337 338 339 340 341 342 343
	// ---- 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 已提交
344 345 346 347 348 349 350 351
	// ---- selections

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

	set selection(value: Selection) {
		if (!(value instanceof Selection)) {
J
Johannes Rieken 已提交
352
			throw illegalArgument('selection');
E
Erich Gamma 已提交
353 354 355 356 357 358 359 360 361 362 363
		}
		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))) {
J
Johannes Rieken 已提交
364
			throw illegalArgument('selections');
E
Erich Gamma 已提交
365 366 367 368 369
		}
		this._selections = value;
		this._trySetSelection(true);
	}

J
Johannes Rieken 已提交
370
	setDecorations(decorationType: vscode.TextEditorDecorationType, ranges: Range[] | vscode.DecorationOptions[]): void {
E
Erich Gamma 已提交
371 372 373 374 375 376 377 378 379 380
		this._runOnProxy(
			() => this._proxy._trySetDecorations(
				this._id,
				decorationType.key,
				TypeConverters.fromRangeOrRangeWithMessage(ranges)
			),
			true
		);
	}

J
Johannes Rieken 已提交
381
	revealRange(range: Range, revealType: vscode.TextEditorRevealType): void {
E
Erich Gamma 已提交
382 383 384 385
		this._runOnProxy(
			() => this._proxy._tryRevealRange(
				this._id,
				TypeConverters.fromRange(range),
386
				revealType || TextEditorRevealType.Default
E
Erich Gamma 已提交
387 388 389 390 391 392 393 394 395 396
			),
			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 已提交
397
	_acceptSelections(selections: Selection[]): void {
E
Erich Gamma 已提交
398 399 400 401 402
		this._selections = selections;
	}

	// ---- editing

J
Johannes Rieken 已提交
403
	edit(callback: (edit: TextEditorEdit) => void): Thenable<boolean> {
404
		let edit = new TextEditorEdit(this._documentData.document);
E
Erich Gamma 已提交
405 406 407 408
		callback(edit);
		return this._applyEdit(edit);
	}

J
Johannes Rieken 已提交
409 410
	_applyEdit(editBuilder: TextEditorEdit): TPromise<boolean> {
		let editData = editBuilder.finalize();
E
Erich Gamma 已提交
411 412

		// prepare data for serialization
B
Benjamin Pasero 已提交
413
		let edits: ISingleEditOperation[] = editData.edits.map((edit) => {
E
Erich Gamma 已提交
414 415 416 417 418 419 420
			return {
				range: TypeConverters.fromRange(edit.range),
				text: edit.text,
				forceMoveMarkers: edit.forceMoveMarkers
			};
		});

421
		return this._proxy._tryApplyEdits(this._id, editData.documentVersionId, edits, editData.setEndOfLine);
E
Erich Gamma 已提交
422 423 424 425
	}

	// ---- util

J
Johannes Rieken 已提交
426
	private _runOnProxy(callback: () => TPromise<any>, silent: boolean): TPromise<ExtHostTextEditor> {
E
Erich Gamma 已提交
427 428 429 430 431 432 433 434
		return callback().then(() => this, err => {
			if (!silent) {
				return TPromise.wrapError(silent);
			}
			console.warn(err);
		});
	}
}