extHostNotebook.ts 28.8 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 8
import { readonly } from 'vs/base/common/errors';
import { Emitter, Event } from 'vs/base/common/event';
R
rebornix 已提交
9
import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
10
import { ISplice } from 'vs/base/common/sequence';
11 12
import { URI, UriComponents } from 'vs/base/common/uri';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
R
rebornix 已提交
13
import { CellKind, CellOutputKind, ExtHostNotebookShape, IMainContext, MainContext, MainThreadNotebookShape, NotebookCellOutputsSplice, MainThreadDocumentsShape, INotebookEditorPropertiesChangeData, INotebookDocumentsAndEditorsDelta } from 'vs/workbench/api/common/extHost.protocol';
14
import { ExtHostCommands } from 'vs/workbench/api/common/extHostCommands';
15
import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors';
R
rebornix 已提交
16
import { CellEditType, CellUri, diff, ICellEditOperation, ICellInsertEdit, IErrorOutput, INotebookDisplayOrder, INotebookEditData, IOrderedMimeType, IStreamOutput, ITransformedDisplayOutputDto, mimeTypeSupportedByCore, NotebookCellsChangedEvent, NotebookCellsSplice2, sortMimeTypes, ICellDeleteEdit, notebookDocumentMetadataDefaults, NotebookCellsChangeType, NotebookDataDto } from 'vs/workbench/contrib/notebook/common/notebookCommon';
17
import { Disposable as VSCodeDisposable } from './extHostTypes';
18
import { CancellationToken } from 'vs/base/common/cancellation';
19 20
import { ExtHostDocumentData } from 'vs/workbench/api/common/extHostDocumentData';
import { NotImplementedProxy } from 'vs/base/common/types';
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41

interface IObservable<T> {
	proxy: T;
	onDidChange: Event<void>;
}

function getObservable<T extends Object>(obj: T): IObservable<T> {
	const onDidChange = new Emitter<void>();
	const proxy = new Proxy(obj, {
		set(target: T, p: PropertyKey, value: any, _receiver: any): boolean {
			target[p as keyof T] = value;
			onDidChange.fire();
			return true;
		}
	});

	return {
		proxy,
		onDidChange: onDidChange.event
	};
}
R
rebornix 已提交
42

43
export class ExtHostCell extends Disposable implements vscode.NotebookCell {
R
rebornix 已提交
44

45
	// private originalSource: string[];
R
rebornix 已提交
46
	private _outputs: any[];
47 48
	private _onDidChangeOutputs = new Emitter<ISplice<vscode.CellOutput>[]>();
	onDidChangeOutputs: Event<ISplice<vscode.CellOutput>[]> = this._onDidChangeOutputs.event;
49 50
	// private _textDocument: vscode.TextDocument | undefined;
	// private _initalVersion: number = -1;
51
	private _outputMapping = new Set<vscode.CellOutput>();
52 53 54
	private _metadata: vscode.NotebookCellMetadata;

	private _metadataChangeListener: IDisposable;
R
rebornix 已提交
55

56 57 58 59 60 61
	private _documentData: ExtHostDocumentData;

	get document(): vscode.TextDocument {
		return this._documentData.document;
	}

R
rebornix 已提交
62
	get source() {
63 64
		// todo@jrieken remove this
		return this._documentData.getText();
R
rebornix 已提交
65 66
	}

R
rebornix 已提交
67
	constructor(
68 69
		private readonly viewType: string,
		private readonly documentUri: URI,
70 71
		readonly handle: number,
		readonly uri: URI,
72
		content: string,
R
rebornix 已提交
73
		public readonly cellKind: CellKind,
R
rebornix 已提交
74
		public language: string,
R
rebornix 已提交
75
		outputs: any[],
76
		_metadata: vscode.NotebookCellMetadata | undefined,
77
		private _proxy: MainThreadNotebookShape,
R
rebornix 已提交
78
	) {
79
		super();
80 81 82 83 84 85 86
		this._documentData = new ExtHostDocumentData(
			new class extends NotImplementedProxy<MainThreadDocumentsShape>('document') { },
			uri,
			content.split(/\r|\n|\r\n/g), '\n',
			language, 0, false
		);

R
rebornix 已提交
87
		this._outputs = outputs;
88

89
		const observableMetadata = getObservable(_metadata || {});
90 91 92 93
		this._metadata = observableMetadata.proxy;
		this._metadataChangeListener = this._register(observableMetadata.onDidChange(() => {
			this.updateMetadata();
		}));
R
rebornix 已提交
94 95 96 97 98 99
	}

	get outputs() {
		return this._outputs;
	}

R
rebornix 已提交
100
	set outputs(newOutputs: vscode.CellOutput[]) {
101
		let diffs = diff<vscode.CellOutput>(this._outputs || [], newOutputs || [], (a) => {
102 103 104 105 106 107 108 109 110 111 112 113 114
			return this._outputMapping.has(a);
		});

		diffs.forEach(diff => {
			for (let i = diff.start; i < diff.start + diff.deleteCount; i++) {
				this._outputMapping.delete(this._outputs[i]);
			}

			diff.toInsert.forEach(output => {
				this._outputMapping.add(output);
			});
		});

R
rebornix 已提交
115
		this._outputs = newOutputs;
116
		this._onDidChangeOutputs.fire(diffs);
R
rebornix 已提交
117 118
	}

119 120 121 122
	get metadata() {
		return this._metadata;
	}

R
rebornix 已提交
123
	set metadata(newMetadata: vscode.NotebookCellMetadata) {
124
		// Don't apply metadata defaults here, 'undefined' means 'inherit from document metadata'
125
		this._metadataChangeListener.dispose();
126
		const observableMetadata = getObservable(newMetadata);
127 128 129 130 131 132 133
		this._metadata = observableMetadata.proxy;
		this._metadataChangeListener = this._register(observableMetadata.onDidChange(() => {
			this.updateMetadata();
		}));

		this.updateMetadata();
	}
134

135 136
	private updateMetadata(): Promise<void> {
		return this._proxy.$updateNotebookCellMetadata(this.viewType, this.documentUri, this.handle, this._metadata);
137 138
	}

139 140 141
	attachTextDocument(document: ExtHostDocumentData) {
		this._documentData = document;
		// this._initalVersion = this._documentData.version;
R
rebornix 已提交
142 143
	}

R
rebornix 已提交
144
	detachTextDocument() {
145
		// no-op? keep stale document until new comes along?
R
rebornix 已提交
146

147 148 149 150 151
		// if (this._textDocument && this._textDocument.version !== this._initalVersion) {
		// 	this.originalSource = this._textDocument.getText().split(/\r|\n|\r\n/g);
		// }
		// this._textDocument = undefined;
		// this._initalVersion = -1;
R
rebornix 已提交
152 153 154
	}
}

R
rebornix 已提交
155
export class ExtHostNotebookDocument extends Disposable implements vscode.NotebookDocument {
R
rebornix 已提交
156
	private static _handlePool: number = 0;
R
rebornix 已提交
157 158 159 160
	readonly handle = ExtHostNotebookDocument._handlePool++;

	private _cells: ExtHostCell[] = [];

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

R
rebornix 已提交
163 164 165 166
	get cells() {
		return this._cells;
	}

R
rebornix 已提交
167 168 169 170 171
	private _languages: string[] = [];

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

R
rebornix 已提交
173 174 175
	set languages(newLanguages: string[]) {
		this._languages = newLanguages;
		this._proxy.$updateNotebookLanguages(this.viewType, this.uri, this._languages);
R
rebornix 已提交
176
	}
R
rebornix 已提交
177

178 179
	private _metadata: Required<vscode.NotebookDocumentMetadata> = notebookDocumentMetadataDefaults;
	private _metadataChangeListener: IDisposable;
R
rebornix 已提交
180 181 182 183 184

	get metadata() {
		return this._metadata;
	}

185 186 187 188 189 190
	set metadata(newMetadata: Required<vscode.NotebookDocumentMetadata>) {
		this._metadataChangeListener.dispose();
		newMetadata = {
			...notebookDocumentMetadataDefaults,
			...newMetadata
		};
R
rebornix 已提交
191 192 193 194
		if (this._metadataChangeListener) {
			this._metadataChangeListener.dispose();
		}

195 196 197 198 199
		const observableMetadata = getObservable(newMetadata);
		this._metadata = observableMetadata.proxy;
		this._metadataChangeListener = this._register(observableMetadata.onDidChange(() => {
			this.updateMetadata();
		}));
R
rebornix 已提交
200 201

		this.updateMetadata();
R
rebornix 已提交
202 203
	}

R
rebornix 已提交
204
	private _displayOrder: string[] = [];
R
rebornix 已提交
205 206 207 208 209

	get displayOrder() {
		return this._displayOrder;
	}

R
rebornix 已提交
210
	set displayOrder(newOrder: string[]) {
R
rebornix 已提交
211 212 213
		this._displayOrder = newOrder;
	}

R
rebornix 已提交
214 215 216 217 218 219
	private _versionId = 0;

	get versionId() {
		return this._versionId;
	}

R
rebornix 已提交
220
	constructor(
R
rebornix 已提交
221
		private readonly _proxy: MainThreadNotebookShape,
R
rebornix 已提交
222
		private _documentsAndEditors: ExtHostDocumentsAndEditors,
R
rebornix 已提交
223
		public viewType: string,
R
rebornix 已提交
224 225
		public uri: URI,
		public renderingHandler: ExtHostNotebookOutputRenderingHandler
R
rebornix 已提交
226
	) {
R
rebornix 已提交
227
		super();
228 229 230 231 232 233 234 235 236 237

		const observableMetadata = getObservable(notebookDocumentMetadataDefaults);
		this._metadata = observableMetadata.proxy;
		this._metadataChangeListener = this._register(observableMetadata.onDidChange(() => {
			this.updateMetadata();
		}));
	}

	private updateMetadata() {
		this._proxy.$updateNotebookMetadata(this.viewType, this.uri, this._metadata);
R
rebornix 已提交
238
	}
R
rebornix 已提交
239

R
rebornix 已提交
240
	dispose() {
R
rebornix 已提交
241
		super.dispose();
R
rebornix 已提交
242 243
		this._cellDisposableMapping.forEach(cell => cell.dispose());
	}
R
rebornix 已提交
244

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

R
rebornix 已提交
247 248
	get isDirty() { return false; }

R
rebornix 已提交
249
	accpetModelChanged(event: NotebookCellsChangedEvent) {
R
rebornix 已提交
250 251 252 253
		if (event.kind === NotebookCellsChangeType.ModelChange) {
			this.$spliceNotebookCells(event.changes);
		} else if (event.kind === NotebookCellsChangeType.Move) {
			this.$moveCell(event.index, event.newIdx);
R
rebornix 已提交
254 255 256 257
		} else if (event.kind === NotebookCellsChangeType.CellClearOutput) {
			this.$clearCellOutputs(event.index);
		} else if (event.kind === NotebookCellsChangeType.CellsClearOutput) {
			this.$clearAllCellOutputs();
258 259
		} else if (event.kind === NotebookCellsChangeType.ChangeLanguage) {
			this.$changeCellLanguage(event.index, event.language);
R
rebornix 已提交
260 261
		}

R
rebornix 已提交
262 263
		this._versionId = event.versionId;
	}
264

R
rebornix 已提交
265 266 267 268
	private $spliceNotebookCells(splices: NotebookCellsSplice2[]): void {
		if (!splices.length) {
			return;
		}
269

R
rebornix 已提交
270 271 272 273
		splices.reverse().forEach(splice => {
			let cellDtos = splice[2];
			let newCells = cellDtos.map(cell => {
				const extCell = new ExtHostCell(this.viewType, this.uri, cell.handle, URI.revive(cell.uri), cell.source.join('\n'), cell.cellKind, cell.language, cell.outputs, cell.metadata, this._proxy);
274
				const documentData = this._documentsAndEditors.getDocument(URI.revive(cell.uri));
275

276 277
				if (documentData) {
					extCell.attachTextDocument(documentData);
R
rebornix 已提交
278 279 280 281
				}

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

R
rebornix 已提交
284 285 286 287 288 289 290
				let store = this._cellDisposableMapping.get(extCell.handle)!;

				store.add(extCell.onDidChangeOutputs((diffs) => {
					this.eventuallyUpdateCellOutputs(extCell, diffs);
				}));

				return extCell;
291 292
			});

R
rebornix 已提交
293 294 295 296 297
			for (let j = splice[0]; j < splice[0] + splice[1]; j++) {
				this._cellDisposableMapping.get(this.cells[j].handle)?.dispose();
				this._cellDisposableMapping.delete(this.cells[j].handle);

			}
298

R
rebornix 已提交
299 300
			this.cells.splice(splice[0], splice[1], ...newCells);
		});
R
rebornix 已提交
301
	}
R
rebornix 已提交
302

R
rebornix 已提交
303 304 305 306 307
	private $moveCell(index: number, newIdx: number) {
		const cells = this.cells.splice(index, 1);
		this.cells.splice(newIdx, 0, ...cells);
	}

R
rebornix 已提交
308 309 310 311 312 313 314 315 316
	private $clearCellOutputs(index: number) {
		const cell = this.cells[index];
		cell.outputs = [];
	}

	private $clearAllCellOutputs() {
		this.cells.forEach(cell => cell.outputs = []);
	}

317 318 319 320 321
	private $changeCellLanguage(index: number, language: string) {
		const cell = this.cells[index];
		cell.language = language;
	}

322 323 324 325 326
	eventuallyUpdateCellOutputs(cell: ExtHostCell, diffs: ISplice<vscode.CellOutput>[]) {
		let renderers = new Set<number>();
		let outputDtos: NotebookCellOutputsSplice[] = diffs.map(diff => {
			let outputs = diff.toInsert;

327
			let transformedOutputs = outputs.map(output => {
R
rebornix 已提交
328
				if (output.outputKind === CellOutputKind.Rich) {
R
rebornix 已提交
329
					const ret = this.transformMimeTypes(output);
330

331 332
					if (ret.orderedMimeTypes[ret.pickedMimeTypeIndex].isResolved) {
						renderers.add(ret.orderedMimeTypes[ret.pickedMimeTypeIndex].rendererId!);
333
					}
334 335 336
					return ret;
				} else {
					return output as IStreamOutput | IErrorOutput;
337 338 339
				}
			});

340
			return [diff.start, diff.deleteCount, transformedOutputs];
341 342 343 344 345
		});

		this._proxy.$spliceNotebookCellOutputs(this.viewType, this.uri, cell.handle, outputDtos, Array.from(renderers));
	}

R
rebornix 已提交
346
	transformMimeTypes(output: vscode.CellDisplayOutput): ITransformedDisplayOutputDto {
347
		let mimeTypes = Object.keys(output.data);
R
rebornix 已提交
348
		let coreDisplayOrder = this.renderingHandler.outputDisplayOrder;
R
rebornix 已提交
349
		const sorted = sortMimeTypes(mimeTypes, coreDisplayOrder?.userOrder || [], this._displayOrder, coreDisplayOrder?.defaultOrder || []);
350 351 352 353 354 355 356

		let orderMimeTypes: IOrderedMimeType[] = [];

		sorted.forEach(mimeType => {
			let handlers = this.renderingHandler.findBestMatchedRenderer(mimeType);

			if (handlers.length) {
R
rebornix 已提交
357
				let renderedOutput = handlers[0].render(this, output, mimeType);
358 359 360 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 387 388 389

				orderMimeTypes.push({
					mimeType: mimeType,
					isResolved: true,
					rendererId: handlers[0].handle,
					output: renderedOutput
				});

				for (let i = 1; i < handlers.length; i++) {
					orderMimeTypes.push({
						mimeType: mimeType,
						isResolved: false,
						rendererId: handlers[i].handle
					});
				}

				if (mimeTypeSupportedByCore(mimeType)) {
					orderMimeTypes.push({
						mimeType: mimeType,
						isResolved: false,
						rendererId: -1
					});
				}
			} else {
				orderMimeTypes.push({
					mimeType: mimeType,
					isResolved: false
				});
			}
		});

		return {
R
rebornix 已提交
390
			outputKind: output.outputKind,
391 392 393 394 395 396
			data: output.data,
			orderedMimeTypes: orderMimeTypes,
			pickedMimeTypeIndex: 0
		};
	}

R
rebornix 已提交
397
	getCell(cellHandle: number) {
R
rebornix 已提交
398 399
		return this.cells.find(cell => cell.handle === cellHandle);
	}
R
rebornix 已提交
400

401 402
	attachCellTextDocument(textDocument: ExtHostDocumentData) {
		let cell = this.cells.find(cell => cell.uri.toString() === textDocument.document.uri.toString());
R
rebornix 已提交
403 404 405 406 407
		if (cell) {
			cell.attachTextDocument(textDocument);
		}
	}

408 409
	detachCellTextDocument(textDocument: ExtHostDocumentData) {
		let cell = this.cells.find(cell => cell.uri.toString() === textDocument.document.uri.toString());
R
rebornix 已提交
410
		if (cell) {
R
rebornix 已提交
411
			cell.detachTextDocument();
R
rebornix 已提交
412 413
		}
	}
R
rebornix 已提交
414 415
}

R
rebornix 已提交
416
export class NotebookEditorCellEditBuilder implements vscode.NotebookEditorCellEdit {
R
rebornix 已提交
417 418 419
	private _finalized: boolean = false;
	private readonly _documentVersionId: number;
	private _collectedEdits: ICellEditOperation[] = [];
R
rebornix 已提交
420
	private _renderers = new Set<number>();
R
rebornix 已提交
421 422 423 424

	constructor(
		readonly editor: ExtHostNotebookEditor
	) {
R
rebornix 已提交
425
		this._documentVersionId = editor.document.versionId;
R
rebornix 已提交
426 427 428 429 430 431
	}

	finalize(): INotebookEditData {
		this._finalized = true;
		return {
			documentVersionId: this._documentVersionId,
R
rebornix 已提交
432 433
			edits: this._collectedEdits,
			renderers: Array.from(this._renderers)
R
rebornix 已提交
434 435 436 437 438 439 440 441 442
		};
	}

	private _throwIfFinalized() {
		if (this._finalized) {
			throw new Error('Edit is only valid while callback runs');
		}
	}

R
rebornix 已提交
443
	insert(index: number, content: string | string[], language: string, type: CellKind, outputs: vscode.CellOutput[], metadata: vscode.NotebookCellMetadata | undefined): void {
R
rebornix 已提交
444 445
		this._throwIfFinalized();

R
rebornix 已提交
446
		const sourceArr = Array.isArray(content) ? content : content.split(/\r|\n|\r\n/g);
R
rebornix 已提交
447
		let cell = {
R
rebornix 已提交
448
			source: sourceArr,
R
rebornix 已提交
449
			language,
R
rebornix 已提交
450
			cellKind: type,
R
rebornix 已提交
451 452
			outputs: (outputs as any[]), // TODO@rebornix
			metadata
R
rebornix 已提交
453 454 455 456
		};

		const transformedOutputs = outputs.map(output => {
			if (output.outputKind === CellOutputKind.Rich) {
R
rebornix 已提交
457
				const ret = this.editor.document.transformMimeTypes(output);
R
rebornix 已提交
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473

				if (ret.orderedMimeTypes[ret.pickedMimeTypeIndex].isResolved) {
					this._renderers.add(ret.orderedMimeTypes[ret.pickedMimeTypeIndex].rendererId!);
				}
				return ret;
			} else {
				return output as IStreamOutput | IErrorOutput;
			}
		});

		cell.outputs = transformedOutputs;

		this._collectedEdits.push({
			editType: CellEditType.Insert,
			index,
			cells: [cell]
R
rebornix 已提交
474 475 476 477 478 479 480 481
		});
	}

	delete(index: number): void {
		this._throwIfFinalized();

		this._collectedEdits.push({
			editType: CellEditType.Delete,
482 483
			index,
			count: 1
R
rebornix 已提交
484 485 486 487
		});
	}
}

R
rebornix 已提交
488
export class ExtHostNotebookEditor extends Disposable implements vscode.NotebookEditor {
R
rebornix 已提交
489
	private _viewColumn: vscode.ViewColumn | undefined;
R
rebornix 已提交
490 491

	selection?: ExtHostCell = undefined;
492
	onDidReceiveMessage: vscode.Event<any> = this._onDidReceiveMessage.event;
R
rebornix 已提交
493 494

	constructor(
495
		private readonly viewType: string,
R
rebornix 已提交
496 497
		readonly id: string,
		public uri: URI,
498 499
		private _proxy: MainThreadNotebookShape,
		private _onDidReceiveMessage: Emitter<any>,
R
rebornix 已提交
500
		public document: ExtHostNotebookDocument,
R
rebornix 已提交
501
		private _documentsAndEditors: ExtHostDocumentsAndEditors
R
rebornix 已提交
502
	) {
R
rebornix 已提交
503 504
		super();
		this._register(this._documentsAndEditors.onDidAddDocuments(documents => {
505 506
			for (const documentData of documents) {
				let data = CellUri.parse(documentData.document.uri);
J
Johannes Rieken 已提交
507 508
				if (data) {
					if (this.document.uri.toString() === data.notebook.toString()) {
509
						document.attachCellTextDocument(documentData);
R
rebornix 已提交
510 511 512
					}
				}
			}
R
rebornix 已提交
513
		}));
R
rebornix 已提交
514

R
rebornix 已提交
515
		this._register(this._documentsAndEditors.onDidRemoveDocuments(documents => {
516 517
			for (const documentData of documents) {
				let data = CellUri.parse(documentData.document.uri);
J
Johannes Rieken 已提交
518 519
				if (data) {
					if (this.document.uri.toString() === data.notebook.toString()) {
520
						document.detachCellTextDocument(documentData);
R
rebornix 已提交
521 522 523
					}
				}
			}
R
rebornix 已提交
524 525 526
		}));
	}

R
rebornix 已提交
527 528
	edit(callback: (editBuilder: NotebookEditorCellEditBuilder) => void): Thenable<boolean> {
		const edit = new NotebookEditorCellEditBuilder(this);
R
rebornix 已提交
529 530 531 532
		callback(edit);
		return this._applyEdit(edit);
	}

R
rebornix 已提交
533
	private _applyEdit(editBuilder: NotebookEditorCellEditBuilder): Promise<boolean> {
R
rebornix 已提交
534 535 536 537 538 539 540
		const editData = editBuilder.finalize();

		// return when there is nothing to do
		if (editData.edits.length === 0) {
			return Promise.resolve(true);
		}

R
rebornix 已提交
541 542 543 544 545 546 547 548 549 550 551 552 553 554
		let compressedEdits: ICellEditOperation[] = [];
		let compressedEditsIndex = -1;

		for (let i = 0; i < editData.edits.length; i++) {
			if (compressedEditsIndex < 0) {
				compressedEdits.push(editData.edits[i]);
				compressedEditsIndex++;
				continue;
			}

			let prevIndex = compressedEditsIndex;
			let prev = compressedEdits[prevIndex];

			if (prev.editType === CellEditType.Insert && editData.edits[i].editType === CellEditType.Insert) {
555
				if (prev.index === editData.edits[i].index) {
R
rebornix 已提交
556 557 558 559 560
					prev.cells.push(...(editData.edits[i] as ICellInsertEdit).cells);
					continue;
				}
			}

561 562 563 564 565 566 567
			if (prev.editType === CellEditType.Delete && editData.edits[i].editType === CellEditType.Delete) {
				if (prev.index === editData.edits[i].index) {
					prev.count += (editData.edits[i] as ICellDeleteEdit).count;
					continue;
				}
			}

R
rebornix 已提交
568 569 570
			compressedEdits.push(editData.edits[i]);
			compressedEditsIndex++;
		}
R
rebornix 已提交
571

R
rebornix 已提交
572
		return this._proxy.$tryApplyEdits(this.viewType, this.uri, editData.documentVersionId, compressedEdits, editData.renderers);
R
rebornix 已提交
573 574 575 576 577 578 579 580
	}

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

	set viewColumn(value) {
		throw readonly('viewColumn');
R
rebornix 已提交
581
	}
582 583 584 585 586

	async postMessage(message: any): Promise<boolean> {
		return this._proxy.$postMessage(this.document.handle, message);
	}

R
rebornix 已提交
587 588
}

R
rebornix 已提交
589
export class ExtHostNotebookOutputRenderer {
R
rebornix 已提交
590 591 592
	private static _handlePool: number = 0;
	readonly handle = ExtHostNotebookOutputRenderer._handlePool++;

R
rebornix 已提交
593
	constructor(
R
rebornix 已提交
594 595 596
		public type: string,
		public filter: vscode.NotebookOutputSelector,
		public renderer: vscode.NotebookOutputRenderer
R
rebornix 已提交
597 598 599 600
	) {

	}

R
rebornix 已提交
601 602 603
	matches(mimeType: string): boolean {
		if (this.filter.subTypes) {
			if (this.filter.subTypes.indexOf(mimeType) >= 0) {
R
rebornix 已提交
604 605 606 607 608 609
				return true;
			}
		}
		return false;
	}

R
rebornix 已提交
610
	render(document: ExtHostNotebookDocument, output: vscode.CellDisplayOutput, mimeType: string): string {
R
rebornix 已提交
611
		let html = this.renderer.render(document, output, mimeType);
R
rebornix 已提交
612

613
		return html;
R
rebornix 已提交
614 615 616 617
	}
}

export interface ExtHostNotebookOutputRenderingHandler {
R
rebornix 已提交
618
	outputDisplayOrder: INotebookDisplayOrder | undefined;
R
rebornix 已提交
619
	findBestMatchedRenderer(mimeType: string): ExtHostNotebookOutputRenderer[];
R
rebornix 已提交
620 621 622
}

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

R
rebornix 已提交
625
	private readonly _proxy: MainThreadNotebookShape;
R
rebornix 已提交
626
	private readonly _notebookContentProviders = new Map<string, { readonly provider: vscode.NotebookContentProvider, readonly extension: IExtensionDescription; }>();
R
rebornix 已提交
627
	private readonly _documents = new Map<string, ExtHostNotebookDocument>();
R
rebornix 已提交
628
	private readonly _editors = new Map<string, { editor: ExtHostNotebookEditor, onDidReceiveMessage: Emitter<any>; }>();
R
rebornix 已提交
629
	private readonly _notebookOutputRenderers = new Map<number, ExtHostNotebookOutputRenderer>();
630

R
rebornix 已提交
631 632
	private readonly _onDidChangeNotebookDocument = new Emitter<{ document: ExtHostNotebookDocument, changes: NotebookCellsChangedEvent[]; }>();
	readonly onDidChangeNotebookDocument: Event<{ document: ExtHostNotebookDocument, changes: NotebookCellsChangedEvent[]; }> = this._onDidChangeNotebookDocument.event;
633

R
rebornix 已提交
634
	private _outputDisplayOrder: INotebookDisplayOrder | undefined;
R
rebornix 已提交
635

R
rebornix 已提交
636
	get outputDisplayOrder(): INotebookDisplayOrder | undefined {
R
rebornix 已提交
637
		return this._outputDisplayOrder;
R
rebornix 已提交
638 639
	}

R
rebornix 已提交
640 641 642 643 644 645
	private _activeNotebookDocument: ExtHostNotebookDocument | undefined;

	get activeNotebookDocument() {
		return this._activeNotebookDocument;
	}

R
rebornix 已提交
646 647 648 649 650 651
	private _activeNotebookEditor: ExtHostNotebookEditor | undefined;

	get activeNotebookEditor() {
		return this._activeNotebookEditor;
	}

R
rebornix 已提交
652 653
	private _onDidOpenNotebookDocument = new Emitter<vscode.NotebookDocument>();
	onDidOpenNotebookDocument: Event<vscode.NotebookDocument> = this._onDidOpenNotebookDocument.event;
R
rebornix 已提交
654 655
	private _onDidCloseNotebookDocument = new Emitter<vscode.NotebookDocument>();
	onDidCloseNotebookDocument: Event<vscode.NotebookDocument> = this._onDidCloseNotebookDocument.event;
R
rebornix 已提交
656

657
	constructor(mainContext: IMainContext, commands: ExtHostCommands, private _documentsAndEditors: ExtHostDocumentsAndEditors) {
R
rebornix 已提交
658
		this._proxy = mainContext.getProxy(MainContext.MainThreadNotebook);
659 660 661 662 663 664 665 666

		commands.registerArgumentProcessor({
			processArgument: arg => {
				if (arg && arg.$mid === 12) {
					const documentHandle = arg.notebookEditor?.notebookHandle;
					const cellHandle = arg.cell.handle;

					for (let value of this._editors) {
667 668
						if (value[1].editor.document.handle === documentHandle) {
							const cell = value[1].editor.document.getCell(cellHandle);
669 670 671 672 673 674
							if (cell) {
								return cell;
							}
						}
					}
				}
B
Benjamin Pasero 已提交
675
				return arg;
676 677
			}
		});
R
rebornix 已提交
678 679
	}

R
rebornix 已提交
680
	registerNotebookOutputRenderer(
R
rebornix 已提交
681
		type: string,
R
rebornix 已提交
682
		extension: IExtensionDescription,
R
rebornix 已提交
683
		filter: vscode.NotebookOutputSelector,
R
rebornix 已提交
684
		renderer: vscode.NotebookOutputRenderer
R
rebornix 已提交
685
	): vscode.Disposable {
R
rebornix 已提交
686
		let extHostRenderer = new ExtHostNotebookOutputRenderer(type, filter, renderer);
R
rebornix 已提交
687
		this._notebookOutputRenderers.set(extHostRenderer.handle, extHostRenderer);
R
rebornix 已提交
688
		this._proxy.$registerNotebookRenderer({ id: extension.identifier, location: extension.extensionLocation }, type, filter, extHostRenderer.handle, renderer.preloads || []);
R
rebornix 已提交
689
		return new VSCodeDisposable(() => {
R
rebornix 已提交
690 691 692
			this._notebookOutputRenderers.delete(extHostRenderer.handle);
			this._proxy.$unregisterNotebookRenderer(extHostRenderer.handle);
		});
R
rebornix 已提交
693 694
	}

R
rebornix 已提交
695 696
	findBestMatchedRenderer(mimeType: string): ExtHostNotebookOutputRenderer[] {
		let matches: ExtHostNotebookOutputRenderer[] = [];
R
rebornix 已提交
697
		for (let renderer of this._notebookOutputRenderers) {
R
rebornix 已提交
698
			if (renderer[1].matches(mimeType)) {
R
rebornix 已提交
699
				matches.push(renderer[1]);
R
rebornix 已提交
700 701 702
			}
		}

R
rebornix 已提交
703
		return matches;
R
rebornix 已提交
704 705
	}

R
rebornix 已提交
706 707 708 709 710 711
	registerNotebookContentProvider(
		extension: IExtensionDescription,
		viewType: string,
		provider: vscode.NotebookContentProvider,
	): vscode.Disposable {

R
rebornix 已提交
712
		if (this._notebookContentProviders.has(viewType)) {
R
rebornix 已提交
713 714 715 716
			throw new Error(`Notebook provider for '${viewType}' already registered`);
		}

		this._notebookContentProviders.set(viewType, { extension, provider });
R
rebornix 已提交
717
		this._proxy.$registerNotebookProvider({ id: extension.identifier, location: extension.extensionLocation }, viewType);
R
rebornix 已提交
718 719 720 721 722 723
		return new VSCodeDisposable(() => {
			this._notebookContentProviders.delete(viewType);
			this._proxy.$unregisterNotebookProvider(viewType);
		});
	}

R
rebornix 已提交
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
	async $resolveNotebookData(viewType: string, uri: UriComponents): Promise<NotebookDataDto | undefined> {
		let provider = this._notebookContentProviders.get(viewType);
		let document = this._documents.get(URI.revive(uri).toString());

		if (provider && document) {
			const rawCells = await provider.provider.openNotebook(URI.revive(uri));
			const renderers = new Set<number>();
			const dto = {
				metadata: {
					...notebookDocumentMetadataDefaults,
					...rawCells.metadata
				},
				languages: rawCells.languages,
				cells: rawCells.cells.map(cell => {
					let transformedOutputs = cell.outputs.map(output => {
						if (output.outputKind === CellOutputKind.Rich) {
							// TODO display string[]
							const ret = this._transformMimeTypes(document!, (rawCells.metadata.displayOrder as string[]) || [], output);

							if (ret.orderedMimeTypes[ret.pickedMimeTypeIndex].isResolved) {
								renderers.add(ret.orderedMimeTypes[ret.pickedMimeTypeIndex].rendererId!);
							}
							return ret;
						} else {
							return output as IStreamOutput | IErrorOutput;
						}
					});

					return {
						language: cell.language,
						cellKind: cell.cellKind,
						metadata: cell.metadata,
						source: cell.source,
						outputs: transformedOutputs
					};
				})
			};

			return dto;
		}

		return;
	}

	private _transformMimeTypes(document: ExtHostNotebookDocument, displayOrder: string[], output: vscode.CellDisplayOutput): ITransformedDisplayOutputDto {
		let mimeTypes = Object.keys(output.data);
		let coreDisplayOrder = this.outputDisplayOrder;
		const sorted = sortMimeTypes(mimeTypes, coreDisplayOrder?.userOrder || [], displayOrder, coreDisplayOrder?.defaultOrder || []);

		let orderMimeTypes: IOrderedMimeType[] = [];

		sorted.forEach(mimeType => {
			let handlers = this.findBestMatchedRenderer(mimeType);

			if (handlers.length) {
				let renderedOutput = handlers[0].render(document, output, mimeType);

				orderMimeTypes.push({
					mimeType: mimeType,
					isResolved: true,
					rendererId: handlers[0].handle,
					output: renderedOutput
				});

				for (let i = 1; i < handlers.length; i++) {
					orderMimeTypes.push({
						mimeType: mimeType,
						isResolved: false,
						rendererId: handlers[i].handle
					});
				}

				if (mimeTypeSupportedByCore(mimeType)) {
					orderMimeTypes.push({
						mimeType: mimeType,
						isResolved: false,
						rendererId: -1
					});
				}
			} else {
				orderMimeTypes.push({
					mimeType: mimeType,
					isResolved: false
				});
			}
		});

		return {
			outputKind: output.outputKind,
			data: output.data,
			orderedMimeTypes: orderMimeTypes,
			pickedMimeTypeIndex: 0
		};
	}

819
	async $executeNotebook(viewType: string, uri: UriComponents, cellHandle: number | undefined, token: CancellationToken): Promise<void> {
R
rebornix 已提交
820
		let document = this._documents.get(URI.revive(uri).toString());
R
rebornix 已提交
821

R
rebornix 已提交
822
		if (!document) {
R
rebornix 已提交
823
			return;
R
rebornix 已提交
824
		}
R
rebornix 已提交
825

R
rebornix 已提交
826 827
		if (this._notebookContentProviders.has(viewType)) {
			let cell = cellHandle !== undefined ? document.getCell(cellHandle) : undefined;
R
rebornix 已提交
828

R
rebornix 已提交
829 830
			return this._notebookContentProviders.get(viewType)!.provider.executeCell(document, cell, token);
		}
R
rebornix 已提交
831 832
	}

R
rebornix 已提交
833
	async $saveNotebook(viewType: string, uri: UriComponents, token: CancellationToken): Promise<boolean> {
R
rebornix 已提交
834
		let document = this._documents.get(URI.revive(uri).toString());
R
rebornix 已提交
835 836 837 838 839 840
		if (!document) {
			return false;
		}

		if (this._notebookContentProviders.has(viewType)) {
			try {
R
rebornix 已提交
841
				await this._notebookContentProviders.get(viewType)!.provider.saveNotebook(document, token);
R
rebornix 已提交
842 843 844 845 846 847 848
			} catch (e) {
				return false;
			}

			return true;
		}

R
rebornix 已提交
849
		let provider = this._notebookContentProviders.get(viewType);
R
rebornix 已提交
850 851

		if (provider && document) {
R
rebornix 已提交
852 853
			await provider.provider.saveNotebook(document, token);
			return true;
R
rebornix 已提交
854 855 856 857 858
		}

		return false;
	}

R
rebornix 已提交
859
	$acceptDisplayOrder(displayOrder: INotebookDisplayOrder): void {
R
rebornix 已提交
860
		this._outputDisplayOrder = displayOrder;
R
rebornix 已提交
861
	}
862 863 864 865 866 867 868 869

	$onDidReceiveMessage(uri: UriComponents, message: any): void {
		let editor = this._editors.get(URI.revive(uri).toString());

		if (editor) {
			editor.onDidReceiveMessage.fire(message);
		}
	}
R
rebornix 已提交
870 871 872 873 874 875

	$acceptModelChanged(uriComponents: UriComponents, event: NotebookCellsChangedEvent): void {
		let editor = this._editors.get(URI.revive(uriComponents).toString());

		if (editor) {
			editor.editor.document.accpetModelChanged(event);
876 877
			this._onDidChangeNotebookDocument.fire({
				document: editor.editor.document,
R
rebornix 已提交
878
				changes: [event]
879
			});
R
rebornix 已提交
880 881 882
		}

	}
R
rebornix 已提交
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901

	$acceptEditorPropertiesChanged(uriComponents: UriComponents, data: INotebookEditorPropertiesChangeData): void {
		let editor = this._editors.get(URI.revive(uriComponents).toString());

		if (!editor) {
			return;
		}

		if (data.selections) {
			const cells = editor.editor.document.cells;

			if (data.selections.selections.length) {
				const firstCell = data.selections.selections[0];
				editor.editor.selection = cells.find(cell => cell.handle === firstCell);
			} else {
				editor.editor.selection = undefined;
			}
		}
	}
R
rebornix 已提交
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933

	async $acceptDocumentAndEditorsDelta(delta: INotebookDocumentsAndEditorsDelta) {
		if (delta.removedDocuments) {
			delta.removedDocuments.forEach((uri) => {
				let document = this._documents.get(URI.revive(uri).toString());

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

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

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

		if (delta.addedDocuments) {
			delta.addedDocuments.forEach(modelData => {
				const revivedUri = URI.revive(modelData.uri);
				const viewType = modelData.viewType;
				if (!this._documents.has(revivedUri.toString())) {
					let document = new ExtHostNotebookDocument(this._proxy, this._documentsAndEditors, viewType, revivedUri, this);
					this._documents.set(revivedUri.toString(), document);
				}

				const onDidReceiveMessage = new Emitter<any>();
R
rebornix 已提交
934
				const document = this._documents.get(revivedUri.toString())!;
R
rebornix 已提交
935 936 937 938 939 940 941

				let editor = new ExtHostNotebookEditor(
					viewType,
					`${ExtHostNotebookController._handlePool++}`,
					revivedUri,
					this._proxy,
					onDidReceiveMessage,
R
rebornix 已提交
942
					document,
R
rebornix 已提交
943 944 945
					this._documentsAndEditors
				);

R
rebornix 已提交
946 947
				this._onDidOpenNotebookDocument.fire(document);

R
rebornix 已提交
948 949 950 951 952 953 954 955 956 957
				// TODO, does it already exist?
				this._editors.set(revivedUri.toString(), { editor, onDidReceiveMessage });
			});
		}

		if (delta.newActiveEditor) {
			this._activeNotebookDocument = this._documents.get(URI.revive(delta.newActiveEditor).toString());
			this._activeNotebookEditor = this._editors.get(URI.revive(delta.newActiveEditor).toString())?.editor;
		}
	}
R
rebornix 已提交
958
}