extHostNotebook.ts 15.2 KB
Newer Older
R
rebornix 已提交
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.
 *--------------------------------------------------------------------------------------------*/

import * as vscode from 'vscode';
R
rebornix 已提交
7
import { ExtHostNotebookShape, IMainContext, MainThreadNotebookShape, MainContext, MainThreadDocumentsShape } from 'vs/workbench/api/common/extHost.protocol';
R
rebornix 已提交
8 9 10 11
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { Disposable as VSCodeDisposable } from './extHostTypes';
import { URI } from 'vs/base/common/uri';
import { DisposableStore } from 'vs/base/common/lifecycle';
R
rebornix 已提交
12 13
import { readonly } from 'vs/base/common/errors';
import { Emitter, Event } from 'vs/base/common/event';
R
rebornix 已提交
14
import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors';
R
rebornix 已提交
15
import { ICell } from 'vs/editor/common/modes';
R
rebornix 已提交
16
// import { ExtHostDocumentData } from 'vs/workbench/api/common/extHostDocumentData';
R
rebornix 已提交
17 18
import * as extHostTypeConverter from 'vs/workbench/api/common/extHostTypeConverters';
import { IMarkdownString } from 'vs/base/common/htmlContent';
R
rebornix 已提交
19 20

export class ExtHostCell implements vscode.NotebookCell {
R
rebornix 已提交
21 22 23

	private static _handlePool: number = 0;
	readonly handle = ExtHostCell._handlePool++;
R
rebornix 已提交
24 25 26 27
	public source: string[];
	private _outputs: any[];
	private _onDidChangeOutputs = new Emitter<void>();
	onDidChangeOutputs: Event<void> = this._onDidChangeOutputs.event;
R
rebornix 已提交
28 29
	private _textDocument: vscode.TextDocument | undefined;
	private _initalVersion: number = -1;
R
rebornix 已提交
30 31

	constructor(
R
rebornix 已提交
32 33 34 35
		private _content: string,
		public cell_type: 'markdown' | 'code',
		public language: string,
		outputs: any[]
R
rebornix 已提交
36
	) {
R
rebornix 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50
		this.source = this._content.split(/\r|\n|\r\n/g);
		this._outputs = outputs;
	}

	get outputs() {
		return this._outputs;
	}

	set outputs(newOutputs: any[]) {
		this._outputs = newOutputs;
		this._onDidChangeOutputs.fire();
	}

	getContent(): string {
R
rebornix 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
		if (this._textDocument && this._initalVersion !== this._textDocument?.version) {
			return this._textDocument.getText();
		} else {
			return this.source.join('\n');
		}
	}

	attachTextDocument(document: vscode.TextDocument) {
		this._textDocument = document;
		this._initalVersion = this._textDocument.version;
	}

	detachTextDocument(document: vscode.TextDocument) {
		if (this._textDocument && this._textDocument.version !== this._initalVersion) {
			this.source = this._textDocument.getText().split(/\r|\n|\r\n/g);
		}

		this._textDocument = undefined;
		this._initalVersion = -1;
R
rebornix 已提交
70 71 72
	}
}

R
rebornix 已提交
73
export class ExtHostNotebookDocument implements vscode.NotebookDocument {
R
rebornix 已提交
74
	private static _handlePool: number = 0;
R
rebornix 已提交
75 76 77 78
	readonly handle = ExtHostNotebookDocument._handlePool++;

	private _cells: ExtHostCell[] = [];

R
rebornix 已提交
79 80
	private _cellDisposableMapping = new Map<number, DisposableStore>();

R
rebornix 已提交
81 82 83 84 85 86 87
	get cells() {
		return this._cells;
	}

	set cells(newCells: ExtHostCell[]) {
		this._cells = newCells;
		this._cells.forEach(cell => {
R
rebornix 已提交
88 89 90 91 92 93
			if (!this._cellDisposableMapping.has(cell.handle)) {
				this._cellDisposableMapping.set(cell.handle, new DisposableStore());
			}

			let store = this._cellDisposableMapping.get(cell.handle)!;
			store.add(cell.onDidChangeOutputs(() => {
R
rebornix 已提交
94
				this._proxy.$updateNotebookCell(this.viewType, this.uri, {
R
rebornix 已提交
95 96
					handle: cell.handle,
					source: cell.source,
R
rebornix 已提交
97
					language: cell.language,
R
rebornix 已提交
98
					cell_type: cell.cell_type,
R
rebornix 已提交
99 100
					outputs: cell.outputs,
					isDirty: false
R
rebornix 已提交
101
				});
R
rebornix 已提交
102
			}));
R
rebornix 已提交
103
		});
R
rebornix 已提交
104 105 106 107 108 109 110
	}

	private _languages: string[] = [];

	get languages() {
		return this._languages = [];
	}
R
rebornix 已提交
111

R
rebornix 已提交
112 113 114
	set languages(newLanguages: string[]) {
		this._languages = newLanguages;
		this._proxy.$updateNotebookLanguages(this.viewType, this.uri, this._languages);
R
rebornix 已提交
115
	}
R
rebornix 已提交
116 117

	constructor(
R
rebornix 已提交
118
		private readonly _proxy: MainThreadNotebookShape,
R
rebornix 已提交
119
		public viewType: string,
R
rebornix 已提交
120 121
		public uri: URI,
		public renderingHandler: ExtHostNotebookOutputRenderingHandler
R
rebornix 已提交
122
	) {
R
rebornix 已提交
123

R
rebornix 已提交
124 125
	}

R
rebornix 已提交
126
	get fileName() { return this.uri.fsPath; }
R
rebornix 已提交
127

R
rebornix 已提交
128 129
	get isDirty() { return false; }

R
rebornix 已提交
130
	async $updateCells(): Promise<void> {
R
rebornix 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
		return await this._proxy.$updateNotebookCells(this.viewType, this.uri, this.cells.map(cell => {
			let outputs = cell.outputs;
			if (outputs && outputs.length) {
				outputs = outputs.map(output => {
					let handler = this.renderingHandler.findBestMatchedRenderer(output);

					if (handler) {
						return handler.render(this, cell, output);
					} else {
						return output;
					}
				})
			}

			return {
				handle: cell.handle,
				source: cell.source,
				language: cell.language,
				cell_type: cell.cell_type,
				outputs: outputs,
				isDirty: false
			}
		}
	));
R
rebornix 已提交
155
	}
R
rebornix 已提交
156

R
rebornix 已提交
157 158
	insertRawCell(index: number, cell: ExtHostCell) {
		this.cells.splice(index, 0, cell);
R
rebornix 已提交
159 160 161 162 163 164 165 166

		if (!this._cellDisposableMapping.has(cell.handle)) {
			this._cellDisposableMapping.set(cell.handle, new DisposableStore());
		}

		let store = this._cellDisposableMapping.get(cell.handle)!;

		store.add(cell.onDidChangeOutputs(() => {
R
rebornix 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179
			let outputs = cell.outputs;
			if (outputs && outputs.length) {
				outputs = outputs.map(output => {
					let handler = this.renderingHandler.findBestMatchedRenderer(output);

					if (handler) {
						return handler.render(this, cell, output);
					} else {
						return output;
					}
				})
			}

R
rebornix 已提交
180 181 182 183 184
			this._proxy.$updateNotebookCell(this.viewType, this.uri, {
				handle: cell.handle,
				source: cell.source,
				language: cell.language,
				cell_type: cell.cell_type,
R
rebornix 已提交
185
				outputs: outputs,
R
rebornix 已提交
186 187
				isDirty: false
			});
R
rebornix 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201
		}));
	}

	deleteCell(index: number): boolean {
		if (index >= this.cells.length) {
			return false;
		}

		let cell = this.cells[index];
		this._cellDisposableMapping.get(cell.handle)?.dispose();
		this._cellDisposableMapping.delete(cell.handle);

		this.cells.splice(index, 1);
		return true;
R
rebornix 已提交
202 203
	}

R
rebornix 已提交
204 205 206
	getActiveCell(cellHandle: number) {
		return this.cells.find(cell => cell.handle === cellHandle);
	}
R
rebornix 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222

	attachCellTextDocument(cellHandle: number, textDocument: vscode.TextDocument) {
		let cell = this.cells.find(cell => cell.handle === cellHandle);

		if (cell) {
			cell.attachTextDocument(textDocument);
		}
	}

	detachCellTextDocument(cellHandle: number, textDocument: vscode.TextDocument) {
		let cell = this.cells.find(cell => cell.handle === cellHandle);

		if (cell) {
			cell.detachTextDocument(textDocument);
		}
	}
R
rebornix 已提交
223 224 225 226 227 228
}

export class ExtHostNotebookEditor implements vscode.NotebookEditor {
	private _viewColumn: vscode.ViewColumn | undefined;

	constructor(
R
rebornix 已提交
229
		private viewType: string,
R
rebornix 已提交
230 231 232 233
		private readonly _proxy: MainThreadNotebookShape,
		readonly id: string,
		public uri: URI,
		public document: ExtHostNotebookDocument,
R
rebornix 已提交
234 235
		private readonly documentsProxy: MainThreadDocumentsShape,
		private _documentsAndEditors: ExtHostDocumentsAndEditors
R
rebornix 已提交
236
	) {
R
rebornix 已提交
237
		let regex = new RegExp(`notebook\\+${viewType}-(\\d+)-(\\d+)`);
R
rebornix 已提交
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 268 269 270 271 272 273 274
		this._documentsAndEditors.onDidAddDocuments(documents => {
			for (const data of documents) {
				let textDocument = data.document;
				let authority = textDocument.uri.authority;

				if (authority !== '') {
					let matches = regex.exec(authority);
					if (matches) {
						const notebookHandle = matches[1];
						const cellHandle = matches[2];

						if (Number(notebookHandle) === this.document.handle) {
							document.attachCellTextDocument(Number(cellHandle), textDocument);
						}
					}
				}
			}
		});

		this._documentsAndEditors.onDidRemoveDocuments(documents => {
			for (const data of documents) {
				let textDocument = data.document;
				let authority = textDocument.uri.authority;

				if (authority !== '') {
					let matches = regex.exec(authority);
					if (matches) {
						const notebookHandle = matches[1];
						const cellHandle = matches[2];

						if (Number(notebookHandle) === this.document.handle) {
							document.detachCellTextDocument(Number(cellHandle), textDocument);
						}
					}
				}
			}
		});
R
rebornix 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287
	}

	createCell(content: string, language: string, type: 'markdown' | 'code', outputs: vscode.CellOutput[]): vscode.NotebookCell {
		let cell = new ExtHostCell(content, type, language, outputs);
		return cell;
	}

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

	set viewColumn(value) {
		throw readonly('viewColumn');
R
rebornix 已提交
288 289 290
	}
}

R
rebornix 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
export class ExtHostNotebookOutputRenderer {
	constructor(
		private filter: vscode.NotebookOutputFilter,
		private renderer: vscode.NotebookOutputRenderer
	) {

	}

	matches(output: vscode.CellOutput): boolean {
		if (output.output_type === this.filter.type) {
			if (output.output_type === 'stream' || output.output_type === 'error') {
				return true;
			}

			if (this.filter.subTypes) {
				for (let i = 0; i < this.filter.subTypes.length; i++) {
					if (output.data[this.filter.subTypes[i]] !== undefined) {
						return true;
					}
				}

				return false;
			} else {
				return true;
			}
		}

		return false;
	}

	render(document: ExtHostNotebookDocument, cell: ExtHostCell, output: vscode.CellOutput): vscode.CellDisplayOutput {
		let html = this.renderer.render(document ,cell, output);

		return {
			output_type: 'display_data',
			data: {
				'text/html': [
					html
				]
			}
		};
	}
}

export interface ExtHostNotebookOutputRenderingHandler {
	findBestMatchedRenderer(output: vscode.CellOutput): ExtHostNotebookOutputRenderer | undefined;
}

export class ExtHostNotebookController implements ExtHostNotebookShape, ExtHostNotebookOutputRenderingHandler {
R
rebornix 已提交
340 341
	private static _handlePool: number = 0;

R
rebornix 已提交
342
	private readonly _proxy: MainThreadNotebookShape;
R
rebornix 已提交
343
	private readonly _documentsProxy: MainThreadDocumentsShape;
R
rebornix 已提交
344
	private readonly _notebookProviders = new Map<string, { readonly provider: vscode.NotebookProvider, readonly extension: IExtensionDescription }>();
R
rebornix 已提交
345
	private readonly _documents = new Map<string, ExtHostNotebookDocument>();
R
rebornix 已提交
346
	private readonly _editors = new Map<string, ExtHostNotebookEditor>();
R
rebornix 已提交
347
	private readonly _notebookOutputRenderers: ExtHostNotebookOutputRenderer[] = [];
R
rebornix 已提交
348

R
rebornix 已提交
349

R
rebornix 已提交
350
	constructor(mainContext: IMainContext, private _documentsAndEditors: ExtHostDocumentsAndEditors) {
R
rebornix 已提交
351
		this._proxy = mainContext.getProxy(MainContext.MainThreadNotebook);
R
rebornix 已提交
352 353
		this._documentsProxy = mainContext.getProxy(MainContext.MainThreadDocuments);

R
rebornix 已提交
354 355
	}

R
rebornix 已提交
356 357 358 359 360 361
	private _activeNotebookDocument: ExtHostNotebookDocument | undefined;

	get activeNotebookDocument() {
		return this._activeNotebookDocument;
	}

R
rebornix 已提交
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
	public registerNotebookOutputRenderer(
		extension: IExtensionDescription,
		filter: vscode.NotebookOutputFilter,
		renderer: vscode.NotebookOutputRenderer
	) {
		this._notebookOutputRenderers.push(new ExtHostNotebookOutputRenderer(filter, renderer));
	}

	findBestMatchedRenderer(output: vscode.CellOutput): ExtHostNotebookOutputRenderer | undefined {
		for (let i = 0; i < this._notebookOutputRenderers.length; i++) {
			if (this._notebookOutputRenderers[i].matches(output)) {
				return this._notebookOutputRenderers[i];
			}
		}

		return;
	}

R
rebornix 已提交
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
	public registerNotebookProvider(
		extension: IExtensionDescription,
		viewType: string,
		provider: vscode.NotebookProvider,
	): vscode.Disposable {

		if (this._notebookProviders.has(viewType)) {
			throw new Error(`Notebook provider for '${viewType}' already registered`);
		}

		this._notebookProviders.set(viewType, { extension, provider });
		this._proxy.$registerNotebookProvider({ id: extension.identifier, location: extension.extensionLocation }, viewType);
		return new VSCodeDisposable(() => {
			this._notebookProviders.delete(viewType);
			this._proxy.$unregisterNotebookProvider(viewType);
		});
	}

R
rebornix 已提交
398
	async $resolveNotebook(viewType: string, uri: URI): Promise<number | undefined> {
R
rebornix 已提交
399 400 401
		let provider = this._notebookProviders.get(viewType);

		if (provider) {
R
rebornix 已提交
402
			if (!this._documents.has(URI.revive(uri).toString())) {
R
rebornix 已提交
403
				let document = new ExtHostNotebookDocument(this._proxy, viewType, uri, this);
R
rebornix 已提交
404 405
				await this._proxy.$createNotebookDocument(
					document.handle,
R
rebornix 已提交
406
					viewType,
R
rebornix 已提交
407 408 409 410
					uri
				);

				this._documents.set(URI.revive(uri).toString(), document);
R
rebornix 已提交
411
			}
R
rebornix 已提交
412

R
rebornix 已提交
413 414 415 416 417 418 419 420 421
			let editor = new ExtHostNotebookEditor(
				viewType,
				this._proxy,
				`${ExtHostNotebookController._handlePool++}`,
				uri,
				this._documents.get(URI.revive(uri).toString())!,
				this._documentsProxy,
				this._documentsAndEditors
			);
R
rebornix 已提交
422 423

			this._editors.set(URI.revive(uri).toString(), editor);
R
rebornix 已提交
424 425 426
			await provider.provider.resolveNotebook(editor);
			await editor.document.$updateCells();
			return editor.document.handle;
R
rebornix 已提交
427 428 429 430 431 432 433 434 435
		}

		return Promise.resolve(undefined);
	}

	async $executeNotebook(viewType: string, uri: URI): Promise<void> {
		let provider = this._notebookProviders.get(viewType);

		if (provider) {
436 437 438
			let document = this._documents.get(URI.revive(uri).toString());

			return provider.provider.executeCell(document!, undefined);
R
rebornix 已提交
439 440
		}
	}
R
rebornix 已提交
441 442 443 444 445 446 447 448 449 450 451 452 453 454

	async $executeNotebookCell(viewType: string, uri: URI, cellHandle: number): Promise<void> {
		let provider = this._notebookProviders.get(viewType);

		if (provider) {
			let document = this._documents.get(URI.revive(uri).toString());
			let cell = document?.getActiveCell(cellHandle);

			if (cell) {
				return provider.provider.executeCell(document!, cell!);
			}
		}
	}

R
rebornix 已提交
455 456 457 458 459 460 461 462 463 464 465
	async $latexRenderer(viewType: string, value: string): Promise<IMarkdownString | undefined> {
		let provider = this._notebookProviders.get(viewType);

		if (provider && provider.provider.latexRenderer) {
			let res = await provider.provider.latexRenderer(value);
			return extHostTypeConverter.MarkdownString.from(res);
		}

		return;
	}

R
rebornix 已提交
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
	async $createRawCell(viewType: string, uri: URI, index: number, language: string, type: 'markdown' | 'code'): Promise<ICell | undefined> {
		let provider = this._notebookProviders.get(viewType);

		if (provider) {
			let editor = this._editors.get(URI.revive(uri).toString());
			let document = this._documents.get(URI.revive(uri).toString());

			let rawCell = editor?.createCell('', language, type, []) as ExtHostCell;
			document?.insertRawCell(index, rawCell!);
			return {
				handle: rawCell.handle,
				source: rawCell.source,
				language: rawCell.language,
				cell_type: rawCell.cell_type,
				outputs: rawCell.outputs,
				isDirty: false
			};
		}

		return;
	}

R
rebornix 已提交
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
	async $deleteCell(viewType: string, uri: URI, index: number): Promise<boolean> {
		let provider = this._notebookProviders.get(viewType);

		if (provider) {
			let document = this._documents.get(URI.revive(uri).toString());

			if (document) {
				return document.deleteCell(index);
			}

			return false;
		}

		return false;
	}

R
rebornix 已提交
504 505 506 507 508 509 510 511 512 513 514
	async $saveNotebook(viewType: string, uri: URI): Promise<boolean> {
		let provider = this._notebookProviders.get(viewType);
		let document = this._documents.get(URI.revive(uri).toString());

		if (provider && document) {
			return await provider.provider.save(document);
		}

		return false;
	}

R
rebornix 已提交
515 516 517 518 519 520 521 522 523 524
	async $updateActiveEditor(viewType: string, uri: URI): Promise<void> {
		let document = this._documents.get(URI.revive(uri).toString());

		if (document) {
			this._activeNotebookDocument = document;
		} else {
			this._activeNotebookDocument = undefined;
		}
	}

525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
	async $destoryNotebookDocument(viewType: string, uri: URI): Promise<boolean> {
		let provider = this._notebookProviders.get(viewType);

		if (provider) {
			let document = this._documents.get(URI.revive(uri).toString());

			if (document) {
				this._documents.delete(URI.revive(uri).toString());
			}

			let editor = this._editors.get(URI.revive(uri).toString());

			if (editor) {
				this._editors.delete(URI.revive(uri).toString());
			}

			return true;
		}

		return false;
	}

R
rebornix 已提交
547
}