mainThreadNotebook.ts 27.4 KB
Newer Older
R
rebornix 已提交
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

R
rebornix 已提交
6
import * as DOM from 'vs/base/browser/dom';
R
rebornix 已提交
7
import { extHostNamedCustomer } from 'vs/workbench/api/common/extHostCustomers';
R
rebornix 已提交
8
import { MainContext, MainThreadNotebookShape, NotebookExtensionDescription, IExtHostContext, ExtHostNotebookShape, ExtHostContext, INotebookDocumentsAndEditorsDelta } from '../common/extHost.protocol';
R
rebornix 已提交
9
import { Disposable, IDisposable, combinedDisposable } from 'vs/base/common/lifecycle';
R
rebornix 已提交
10
import { URI, UriComponents } from 'vs/base/common/uri';
11
import { INotebookService, IMainNotebookController } from 'vs/workbench/contrib/notebook/common/notebookService';
12
import { INotebookTextModel, INotebookMimeTypeSelector, NOTEBOOK_DISPLAY_ORDER, NotebookCellOutputsSplice, NotebookDocumentMetadata, NotebookCellMetadata, ICellEditOperation, ACCESSIBLE_NOTEBOOK_DISPLAY_ORDER, CellEditType, CellKind, INotebookKernelInfo, INotebookKernelInfoDto, IEditor, INotebookRendererInfo, IOutputRenderRequest, IOutputRenderResponse, INotebookDocumentFilter } from 'vs/workbench/contrib/notebook/common/notebookCommon';
R
rebornix 已提交
13
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
14
import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel';
15 16
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { INotebookEditor } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
17
import { CancellationToken } from 'vs/base/common/cancellation';
R
rebornix 已提交
18
import { IAccessibilityService } from 'vs/platform/accessibility/common/accessibility';
R
rebornix 已提交
19 20
import { IRelativePattern } from 'vs/base/common/glob';
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
21
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
R
rebornix 已提交
22
import { IUndoRedoService } from 'vs/platform/undoRedo/common/undoRedo';
23
import { ITextModelService } from 'vs/editor/common/services/resolverService';
R
rebornix 已提交
24
import { Emitter } from 'vs/base/common/event';
R
rebornix 已提交
25

26 27
export class MainThreadNotebookDocument extends Disposable {
	private _textModel: NotebookTextModel;
R
rebornix 已提交
28

29 30
	get textModel() {
		return this._textModel;
R
rebornix 已提交
31
	}
R
rebornix 已提交
32 33

	constructor(
R
rebornix 已提交
34
		private readonly _proxy: ExtHostNotebookShape,
R
rebornix 已提交
35
		public handle: number,
R
rebornix 已提交
36
		public viewType: string,
37
		public supportBackup: boolean,
38
		public uri: URI,
39
		@INotebookService readonly notebookService: INotebookService,
40 41
		@IUndoRedoService readonly undoRedoService: IUndoRedoService,
		@ITextModelService modelService: ITextModelService
42

R
rebornix 已提交
43
	) {
R
rebornix 已提交
44
		super();
45

46
		this._textModel = new NotebookTextModel(handle, viewType, supportBackup, uri, undoRedoService, modelService);
47
		this._register(this._textModel.onDidModelChangeProxy(e => {
R
rebornix 已提交
48
			this._proxy.$acceptModelChanged(this.uri, e);
49
			this._proxy.$acceptEditorPropertiesChanged(uri, { selections: { selections: this._textModel.selections }, metadata: null });
R
rebornix 已提交
50
		}));
R
rebornix 已提交
51 52
		this._register(this._textModel.onDidSelectionChange(e => {
			const selectionsChange = e ? { selections: e } : null;
R
rebornix 已提交
53
			this._proxy.$acceptEditorPropertiesChanged(uri, { selections: selectionsChange, metadata: null });
R
rebornix 已提交
54
		}));
R
rebornix 已提交
55
	}
R
rebornix 已提交
56

57
	async applyEdit(modelVersionId: number, edits: ICellEditOperation[], synchronous: boolean): Promise<boolean> {
58
		await this.notebookService.transformEditsOutputs(this.textModel, edits);
R
rebornix 已提交
59
		if (synchronous) {
60
			return this._textModel.$applyEdit(modelVersionId, edits, synchronous);
R
rebornix 已提交
61 62 63
		} else {
			return new Promise(resolve => {
				this._register(DOM.scheduleAtNextAnimationFrame(() => {
64
					const ret = this._textModel.$applyEdit(modelVersionId, edits, true);
R
rebornix 已提交
65 66 67 68
					resolve(ret);
				}));
			});
		}
R
rebornix 已提交
69
	}
R
rebornix 已提交
70

R
rebornix 已提交
71
	dispose() {
72
		this._textModel.dispose();
R
rebornix 已提交
73 74
		super.dispose();
	}
R
rebornix 已提交
75 76
}

R
rebornix 已提交
77
class DocumentAndEditorState {
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
	static ofSets<T>(before: Set<T>, after: Set<T>): { removed: T[], added: T[] } {
		const removed: T[] = [];
		const added: T[] = [];
		before.forEach(element => {
			if (!after.has(element)) {
				removed.push(element);
			}
		});
		after.forEach(element => {
			if (!before.has(element)) {
				added.push(element);
			}
		});
		return { removed, added };
	}

R
rebornix 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
	static ofMaps<K, V>(before: Map<K, V>, after: Map<K, V>): { removed: V[], added: V[] } {
		const removed: V[] = [];
		const added: V[] = [];
		before.forEach((value, index) => {
			if (!after.has(index)) {
				removed.push(value);
			}
		});
		after.forEach((value, index) => {
			if (!before.has(index)) {
				added.push(value);
			}
		});
		return { removed, added };
	}

	static compute(before: DocumentAndEditorState | undefined, after: DocumentAndEditorState): INotebookDocumentsAndEditorsDelta {
		if (!before) {
			const apiEditors = [];
			for (let id in after.textEditors) {
				const editor = after.textEditors.get(id)!;
				apiEditors.push({ id, documentUri: editor.uri!, selections: editor!.textModel!.selections });
			}

			return {
				addedDocuments: [],
120 121
				addedEditors: apiEditors,
				visibleEditors: [...after.visibleEditors].map(editor => editor[0])
R
rebornix 已提交
122 123
			};
		}
124
		const documentDelta = DocumentAndEditorState.ofSets(before.documents, after.documents);
R
rebornix 已提交
125 126 127 128
		const editorDelta = DocumentAndEditorState.ofMaps(before.textEditors, after.textEditors);
		const addedAPIEditors = editorDelta.added.map(add => ({
			id: add.getId(),
			documentUri: add.uri!,
129
			selections: add.textModel!.selections || []
R
rebornix 已提交
130 131 132 133 134 135 136
		}));

		const removedAPIEditors = editorDelta.removed.map(removed => removed.getId());

		// const oldActiveEditor = before.activeEditor !== after.activeEditor ? before.activeEditor : undefined;
		const newActiveEditor = before.activeEditor !== after.activeEditor ? after.activeEditor : undefined;

137 138
		const visibleEditorDelta = DocumentAndEditorState.ofMaps(before.visibleEditors, after.visibleEditors);

R
rebornix 已提交
139
		return {
140 141 142 143 144 145 146 147 148 149 150
			addedDocuments: documentDelta.added.map(e => {
				return {
					viewType: e.viewType,
					handle: e.handle,
					uri: e.uri,
					metadata: e.metadata,
					versionId: e.versionId,
					cells: e.cells.map(cell => ({
						handle: cell.handle,
						uri: cell.uri,
						source: cell.textBuffer.getLinesContent(),
151
						eol: cell.textBuffer.getEOL(),
152 153 154 155 156 157 158 159 160 161 162 163
						language: cell.language,
						cellKind: cell.cellKind,
						outputs: cell.outputs,
						metadata: cell.metadata
					})),
					// attachedEditor: editorId ? {
					// 	id: editorId,
					// 	selections: document.textModel.selections
					// } : undefined
				};
			}),
			removedDocuments: documentDelta.removed.map(e => e.uri),
R
rebornix 已提交
164 165
			addedEditors: addedAPIEditors,
			removedEditors: removedAPIEditors,
166 167 168 169
			newActiveEditor: newActiveEditor,
			visibleEditors: visibleEditorDelta.added.length === 0 && visibleEditorDelta.removed.length === 0
				? undefined
				: [...after.visibleEditors].map(editor => editor[0])
R
rebornix 已提交
170 171 172 173
		};
	}

	constructor(
174
		readonly documents: Set<NotebookTextModel>,
R
rebornix 已提交
175 176
		readonly textEditors: Map<string, IEditor>,
		readonly activeEditor: string | null | undefined,
177
		readonly visibleEditors: Map<string, IEditor>
R
rebornix 已提交
178 179 180 181 182
	) {
		//
	}
}

R
rebornix 已提交
183 184 185
@extHostNamedCustomer(MainContext.MainThreadNotebook)
export class MainThreadNotebooks extends Disposable implements MainThreadNotebookShape {
	private readonly _notebookProviders = new Map<string, MainThreadNotebookController>();
R
rebornix 已提交
186
	private readonly _notebookKernels = new Map<string, MainThreadNotebookKernel>();
R
rebornix 已提交
187
	private readonly _notebookKernelProviders = new Map<number, { extension: NotebookExtensionDescription, emitter: Emitter<void>, provider: IDisposable }>();
188
	private readonly _notebookRenderers = new Map<string, MainThreadNotebookRenderer>();
R
rebornix 已提交
189
	private readonly _proxy: ExtHostNotebookShape;
R
rebornix 已提交
190 191
	private _toDisposeOnEditorRemove = new Map<string, IDisposable>();
	private _currentState?: DocumentAndEditorState;
R
rebornix 已提交
192 193 194

	constructor(
		extHostContext: IExtHostContext,
R
rebornix 已提交
195
		@INotebookService private _notebookService: INotebookService,
196 197
		@IConfigurationService private readonly configurationService: IConfigurationService,
		@IEditorService private readonly editorService: IEditorService,
198 199
		@IAccessibilityService private readonly accessibilityService: IAccessibilityService,
		@IInstantiationService private readonly _instantiationService: IInstantiationService
200

R
rebornix 已提交
201 202 203
	) {
		super();
		this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostNotebook);
R
rebornix 已提交
204 205 206
		this.registerListeners();
	}

R
rebornix 已提交
207 208 209 210 211 212 213 214
	async $tryApplyEdits(viewType: string, resource: UriComponents, modelVersionId: number, edits: ICellEditOperation[], renderers: number[]): Promise<boolean> {
		let controller = this._notebookProviders.get(viewType);

		if (controller) {
			return controller.tryApplyEdits(resource, modelVersionId, edits, renderers);
		}

		return false;
R
rebornix 已提交
215 216
	}

R
rebornix 已提交
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
	private _isDeltaEmpty(delta: INotebookDocumentsAndEditorsDelta) {
		if (delta.addedDocuments !== undefined && delta.addedDocuments.length > 0) {
			return false;
		}

		if (delta.removedDocuments !== undefined && delta.removedDocuments.length > 0) {
			return false;
		}

		if (delta.addedEditors !== undefined && delta.addedEditors.length > 0) {
			return false;
		}

		if (delta.removedEditors !== undefined && delta.removedEditors.length > 0) {
			return false;
		}

		if (delta.visibleEditors !== undefined && delta.visibleEditors.length > 0) {
			return false;
		}

		if (delta.newActiveEditor !== undefined) {
			return false;
		}

		return true;
	}

245
	private _emitDelta(delta: INotebookDocumentsAndEditorsDelta) {
R
rebornix 已提交
246 247 248 249
		if (this._isDeltaEmpty(delta)) {
			return;
		}

250
		return this._proxy.$acceptDocumentAndEditorsDelta(delta);
251 252
	}

R
rebornix 已提交
253
	registerListeners() {
R
rebornix 已提交
254 255 256 257
		this._notebookService.listNotebookEditors().forEach((e) => {
			this._addNotebookEditor(e);
		});

R
rebornix 已提交
258
		this._register(this._notebookService.onDidChangeActiveEditor(e => {
259
			this._updateState();
R
rebornix 已提交
260
		}));
R
rebornix 已提交
261

R
rebornix 已提交
262
		this._register(this._notebookService.onDidChangeVisibleEditors(e => {
263 264 265 266 267 268 269 270 271
			if (this._notebookProviders.size > 0) {
				if (!this._currentState) {
					// no current state means we didn't even create editors in ext host yet.
					return;
				}

				// we can't simply update visibleEditors as we need to check if we should create editors first.
				this._updateState();
			}
R
rebornix 已提交
272 273
		}));

R
rebornix 已提交
274 275 276 277
		this._register(this._notebookService.onNotebookEditorAdd(editor => {
			this._addNotebookEditor(editor);
		}));

278 279 280
		this._register(this._notebookService.onNotebookEditorsRemove(editors => {
			this._removeNotebookEditor(editors);
		}));
281

R
rebornix 已提交
282 283 284 285
		this._register(this._notebookService.onNotebookDocumentAdd(() => {
			this._updateState();
		}));

286 287
		this._register(this._notebookService.onNotebookDocumentRemove(() => {
			this._updateState();
R
rebornix 已提交
288 289
		}));

R
rebornix 已提交
290 291 292 293
		this._register(this._notebookService.onDidChangeNotebookActiveKernel(e => {
			this._proxy.$acceptNotebookActiveKernelChange(e);
		}));

R
rebornix 已提交
294 295 296 297 298 299 300
		const updateOrder = () => {
			let userOrder = this.configurationService.getValue<string[]>('notebook.displayOrder');
			this._proxy.$acceptDisplayOrder({
				defaultOrder: this.accessibilityService.isScreenReaderOptimized() ? ACCESSIBLE_NOTEBOOK_DISPLAY_ORDER : NOTEBOOK_DISPLAY_ORDER,
				userOrder: userOrder
			});
		};
R
rebornix 已提交
301

R
rebornix 已提交
302
		updateOrder();
R
rebornix 已提交
303

R
rebornix 已提交
304 305 306
		this._register(this.configurationService.onDidChangeConfiguration(e => {
			if (e.affectedKeys.indexOf('notebook.displayOrder') >= 0) {
				updateOrder();
R
rebornix 已提交
307
			}
R
rebornix 已提交
308 309 310 311 312
		}));

		this._register(this.accessibilityService.onDidChangeScreenReaderOptimized(() => {
			updateOrder();
		}));
R
rebornix 已提交
313 314 315 316

		const activeEditorPane = this.editorService.activeEditorPane as any | undefined;
		const notebookEditor = activeEditorPane?.isNotebookEditor ? activeEditorPane.getControl() : undefined;
		this._updateState(notebookEditor);
R
rebornix 已提交
317 318
	}

R
rebornix 已提交
319 320 321
	private _addNotebookEditor(e: IEditor) {
		this._toDisposeOnEditorRemove.set(e.getId(), combinedDisposable(
			e.onDidChangeModel(() => this._updateState()),
R
rebornix 已提交
322 323 324
			e.onDidFocusEditorWidget(() => {
				this._updateState(e);
			}),
R
rebornix 已提交
325 326
		));

R
rebornix 已提交
327 328 329
		const activeEditorPane = this.editorService.activeEditorPane as any | undefined;
		const notebookEditor = activeEditorPane?.isNotebookEditor ? activeEditorPane.getControl() : undefined;
		this._updateState(notebookEditor);
R
rebornix 已提交
330 331
	}

332 333 334 335 336 337 338 339 340 341
	private _removeNotebookEditor(editors: IEditor[]) {
		editors.forEach(e => {
			const sub = this._toDisposeOnEditorRemove.get(e.getId());
			if (sub) {
				this._toDisposeOnEditorRemove.delete(e.getId());
				sub.dispose();
			}
		});

		this._updateState();
R
rebornix 已提交
342 343 344 345 346
	}

	private async _updateState(focusedNotebookEditor?: IEditor) {
		let activeEditor: string | null = null;

347 348 349 350 351 352 353 354 355 356
		const activeEditorPane = this.editorService.activeEditorPane as any | undefined;
		if (activeEditorPane?.isNotebookEditor) {
			const notebookEditor = (activeEditorPane.getControl() as INotebookEditor);
			activeEditor = notebookEditor && notebookEditor.hasModel() ? notebookEditor!.getId() : null;
		}

		const documentEditorsMap = new Map<string, IEditor>();

		const editors = new Map<string, IEditor>();
		this._notebookService.listNotebookEditors().forEach(editor => {
R
rebornix 已提交
357 358
			if (editor.hasModel()) {
				editors.set(editor.getId(), editor);
359 360 361 362 363 364 365 366 367 368
				documentEditorsMap.set(editor.textModel!.uri.toString(), editor);
			}
		});

		const visibleEditorsMap = new Map<string, IEditor>();
		this.editorService.visibleEditorPanes.forEach(editor => {
			if ((editor as any).isNotebookEditor) {
				const nbEditorWidget = (editor as any).getControl() as INotebookEditor;
				if (nbEditorWidget && editors.has(nbEditorWidget.getId())) {
					visibleEditorsMap.set(nbEditorWidget.getId(), nbEditorWidget);
R
rebornix 已提交
369 370
				}
			}
371 372 373 374
		});

		const documents = new Set<NotebookTextModel>();
		this._notebookService.listNotebookDocuments().forEach(document => {
R
rebornix 已提交
375
			documents.add(document);
376
		});
R
rebornix 已提交
377

378
		if (!activeEditor && focusedNotebookEditor && focusedNotebookEditor.hasModel()) {
R
rebornix 已提交
379 380 381
			activeEditor = focusedNotebookEditor.getId();
		}

R
rebornix 已提交
382
		// editors always have view model attached, which means there is already a document in exthost.
383
		const newState = new DocumentAndEditorState(documents, editors, activeEditor, visibleEditorsMap);
R
rebornix 已提交
384 385 386 387 388 389 390 391 392
		const delta = DocumentAndEditorState.compute(this._currentState, newState);
		// const isEmptyChange = (!delta.addedDocuments || delta.addedDocuments.length === 0)
		// 	&& (!delta.removedDocuments || delta.removedDocuments.length === 0)
		// 	&& (!delta.addedEditors || delta.addedEditors.length === 0)
		// 	&& (!delta.removedEditors || delta.removedEditors.length === 0)
		// 	&& (delta.newActiveEditor === undefined)

		// if (!isEmptyChange) {
		this._currentState = newState;
393
		await this._emitDelta(delta);
R
rebornix 已提交
394 395 396
		// }
	}

397 398 399 400
	async $registerNotebookRenderer(extension: NotebookExtensionDescription, type: string, selectors: INotebookMimeTypeSelector, preloads: UriComponents[]): Promise<void> {
		const renderer = new MainThreadNotebookRenderer(this._proxy, type, extension.id, URI.revive(extension.location), selectors, preloads.map(uri => URI.revive(uri)));
		this._notebookRenderers.set(type, renderer);
		this._notebookService.registerNotebookRenderer(type, renderer);
R
rebornix 已提交
401 402
	}

403 404
	async $unregisterNotebookRenderer(id: string): Promise<void> {
		this._notebookService.unregisterNotebookRenderer(id);
R
rebornix 已提交
405 406
	}

407
	async $registerNotebookProvider(extension: NotebookExtensionDescription, viewType: string, supportBackup: boolean, kernel: INotebookKernelInfoDto | undefined): Promise<void> {
408
		let controller = new MainThreadNotebookController(this._proxy, this, viewType, supportBackup, kernel, this._notebookService, this._instantiationService);
R
rebornix 已提交
409
		this._notebookProviders.set(viewType, controller);
R
rebornix 已提交
410
		this._notebookService.registerNotebookController(viewType, extension, controller);
R
rebornix 已提交
411
		return;
R
rebornix 已提交
412 413
	}

414 415 416 417 418 419 420
	async $onNotebookChange(viewType: string, uri: UriComponents): Promise<void> {
		let controller = this._notebookProviders.get(viewType);
		if (controller) {
			controller.handleNotebookChange(uri);
		}
	}

R
rebornix 已提交
421
	async $unregisterNotebookProvider(viewType: string): Promise<void> {
R
rebornix 已提交
422 423
		this._notebookProviders.delete(viewType);
		this._notebookService.unregisterNotebookProvider(viewType);
R
rebornix 已提交
424 425 426
		return;
	}

R
rebornix 已提交
427 428
	async $registerNotebookKernel(extension: NotebookExtensionDescription, id: string, label: string, selectors: (string | IRelativePattern)[], preloads: UriComponents[]): Promise<void> {
		const kernel = new MainThreadNotebookKernel(this._proxy, id, label, selectors, extension.id, URI.revive(extension.location), preloads.map(preload => URI.revive(preload)));
R
rebornix 已提交
429 430 431 432 433 434 435 436 437 438 439
		this._notebookKernels.set(id, kernel);
		this._notebookService.registerNotebookKernel(kernel);
		return;
	}

	async $unregisterNotebookKernel(id: string): Promise<void> {
		this._notebookKernels.delete(id);
		this._notebookService.unregisterNotebookKernel(id);
		return;
	}

R
rebornix 已提交
440 441 442 443 444 445
	async $registerNotebookKernelProvider(extension: NotebookExtensionDescription, handle: number, documentFilter: INotebookDocumentFilter): Promise<void> {
		const emitter = new Emitter<void>();
		const that = this;
		const provider = this._notebookService.registerNotebookKernelProvider({
			onDidChangeKernels: emitter.event,
			selector: documentFilter,
R
rebornix 已提交
446 447 448 449 450 451 452 453
			provideKernels: async (uri: URI, token: CancellationToken) => {
				const kernels = await that._proxy.$provideNotebookKernels(handle, uri, token);
				return kernels.map(kernel => {
					return {
						...kernel,
						providerHandle: handle
					};
				});
R
rebornix 已提交
454 455 456 457
			},
			resolveKernel: (editorId: string, uri: URI, kernelId: string, token: CancellationToken) => {
				return that._proxy.$resolveNotebookKernel(handle, editorId, uri, kernelId, token);
			},
458 459
			executeNotebook: (uri: URI, kernelId: string, cellHandle: number | undefined, token: CancellationToken) => {
				return that._proxy.$executeNotebookKernelFromProvider(handle, uri, kernelId, cellHandle, token);
R
rebornix 已提交
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
			}
		});
		this._notebookKernelProviders.set(handle, {
			extension,
			emitter,
			provider
		});

		return;
	}

	async $unregisterNotebookKernelProvider(handle: number): Promise<void> {
		const entry = this._notebookKernelProviders.get(handle);

		if (entry) {
			entry.emitter.dispose();
			entry.provider.dispose();
			this._notebookKernelProviders.delete(handle);
		}
	}

	$onNotebookKernelChange(handle: number): void {
		const entry = this._notebookKernelProviders.get(handle);

		entry?.emitter.fire();
	}

R
rebornix 已提交
487
	async $updateNotebookLanguages(viewType: string, resource: UriComponents, languages: string[]): Promise<void> {
R
rebornix 已提交
488 489 490
		let controller = this._notebookProviders.get(viewType);

		if (controller) {
R
rebornix 已提交
491
			controller.updateLanguages(resource, languages);
R
rebornix 已提交
492 493
		}
	}
R
rebornix 已提交
494

R
rebornix 已提交
495
	async $updateNotebookMetadata(viewType: string, resource: UriComponents, metadata: NotebookDocumentMetadata): Promise<void> {
R
rebornix 已提交
496 497 498 499 500 501 502
		let controller = this._notebookProviders.get(viewType);

		if (controller) {
			controller.updateNotebookMetadata(resource, metadata);
		}
	}

503 504 505 506 507 508 509 510
	async $updateNotebookCellMetadata(viewType: string, resource: UriComponents, handle: number, metadata: NotebookCellMetadata): Promise<void> {
		let controller = this._notebookProviders.get(viewType);

		if (controller) {
			controller.updateNotebookCellMetadata(resource, handle, metadata);
		}
	}

511
	async $spliceNotebookCellOutputs(viewType: string, resource: UriComponents, cellHandle: number, splices: NotebookCellOutputsSplice[], renderers: number[]): Promise<void> {
512
		let controller = this._notebookProviders.get(viewType);
513
		await controller?.spliceNotebookCellOutputs(resource, cellHandle, splices, renderers);
514 515
	}

516 517
	async executeNotebookByAttachedKernel(viewType: string, uri: URI, token: CancellationToken): Promise<void> {
		return this._proxy.$executeNotebookByAttachedKernel(viewType, uri, undefined, token);
R
rebornix 已提交
518
	}
519

520 521 522 523 524
	async $postMessage(editorId: string, forRendererId: string | undefined, value: any): Promise<boolean> {
		const editor = this._notebookService.getNotebookEditor(editorId) as INotebookEditor | undefined;
		if (editor?.isNotebookEditor) {
			editor.postMessage(forRendererId, value);
			return true;
525 526 527 528
		}

		return false;
	}
529 530 531 532 533 534 535 536 537 538

	$onDidEdit(resource: UriComponents, viewType: string, editId: number, label: string | undefined): void {
		let controller = this._notebookProviders.get(viewType);
		controller?.handleEdit(resource, editId, label);
	}

	$onContentChange(resource: UriComponents, viewType: string): void {
		let controller = this._notebookProviders.get(viewType);
		controller?.handleNotebookChange(resource);
	}
R
rebornix 已提交
539 540 541
}

export class MainThreadNotebookController implements IMainNotebookController {
R
rebornix 已提交
542
	private _mapping: Map<string, MainThreadNotebookDocument> = new Map();
R
rebornix 已提交
543
	static documentHandle: number = 0;
R
rebornix 已提交
544 545

	constructor(
R
rebornix 已提交
546 547
		private readonly _proxy: ExtHostNotebookShape,
		private _mainThreadNotebook: MainThreadNotebooks,
R
rebornix 已提交
548
		private _viewType: string,
549
		private _supportBackup: boolean,
550 551
		readonly kernel: INotebookKernelInfoDto | undefined,
		readonly notebookService: INotebookService,
552
		readonly _instantiationService: IInstantiationService
553

R
rebornix 已提交
554 555 556
	) {
	}

557
	async createNotebook(viewType: string, uri: URI, forceReload: boolean, editorId?: string, backupId?: string): Promise<NotebookTextModel | undefined> {
R
rebornix 已提交
558 559 560
		let mainthreadNotebook = this._mapping.get(URI.from(uri).toString());

		if (mainthreadNotebook) {
R
revert.  
rebornix 已提交
561 562 563 564 565 566 567 568
			if (forceReload) {
				const data = await this._proxy.$resolveNotebookData(viewType, uri);
				if (!data) {
					return;
				}

				mainthreadNotebook.textModel.languages = data.languages;
				mainthreadNotebook.textModel.metadata = data.metadata;
R
rebornix 已提交
569 570

				const edits: ICellEditOperation[] = [
R
revert.  
rebornix 已提交
571 572
					{ editType: CellEditType.Delete, count: mainthreadNotebook.textModel.cells.length, index: 0 },
					{ editType: CellEditType.Insert, index: 0, cells: data.cells }
R
rebornix 已提交
573 574 575 576 577 578 579 580 581
				];

				await this.notebookService.transformEditsOutputs(mainthreadNotebook.textModel, edits);
				await new Promise(resolve => {
					DOM.scheduleAtNextAnimationFrame(() => {
						const ret = mainthreadNotebook!.textModel.$applyEdit(mainthreadNotebook!.textModel.versionId, edits, true);
						resolve(ret);
					});
				});
R
revert.  
rebornix 已提交
582
			}
R
rebornix 已提交
583 584 585
			return mainthreadNotebook.textModel;
		}

586
		let document = this._instantiationService.createInstance(MainThreadNotebookDocument, this._proxy, MainThreadNotebookController.documentHandle++, viewType, this._supportBackup, uri);
R
rebornix 已提交
587 588
		this._mapping.set(document.uri.toString(), document);

R
rebornix 已提交
589
		// open notebook document
590
		const data = await this._proxy.$resolveNotebookData(viewType, uri, backupId);
R
rebornix 已提交
591 592 593 594 595 596
		if (!data) {
			return;
		}

		document.textModel.languages = data.languages;
		document.textModel.metadata = data.metadata;
597 598 599 600 601 602 603

		if (data.cells.length) {
			document.textModel.initialize(data!.cells);
		} else {
			const mainCell = document.textModel.createCellTextModel([''], document.textModel.languages.length ? document.textModel.languages[0] : '', CellKind.Code, [], undefined);
			document.textModel.insertTemplateCell(mainCell);
		}
R
rebornix 已提交
604

R
rebornix 已提交
605 606
		this._proxy.$acceptEditorPropertiesChanged(uri, { selections: null, metadata: document.textModel.metadata });

R
rebornix 已提交
607 608 609
		return document.textModel;
	}

610 611 612 613
	async resolveNotebookEditor(viewType: string, uri: URI, editorId: string) {
		await this._proxy.$resolveNotebookEditor(viewType, uri, editorId);
	}

R
rebornix 已提交
614
	async tryApplyEdits(resource: UriComponents, modelVersionId: number, edits: ICellEditOperation[], renderers: number[]): Promise<boolean> {
615
		let mainthreadNotebook = this._mapping.get(URI.from(resource).toString());
R
rebornix 已提交
616 617

		if (mainthreadNotebook) {
R
rebornix 已提交
618 619
			await this.notebookService.transformEditsOutputs(mainthreadNotebook.textModel, edits);
			return mainthreadNotebook.textModel.$applyEdit(modelVersionId, edits, true);
R
rebornix 已提交
620 621 622
		}

		return false;
623 624
	}

625
	async spliceNotebookCellOutputs(resource: UriComponents, cellHandle: number, splices: NotebookCellOutputsSplice[], renderers: number[]): Promise<void> {
626
		let mainthreadNotebook = this._mapping.get(URI.from(resource).toString());
R
rebornix 已提交
627 628 629 630
		if (mainthreadNotebook) {
			await this.notebookService.transformSpliceOutputs(mainthreadNotebook.textModel, splices);
			mainthreadNotebook.textModel.$spliceNotebookCellOutputs(cellHandle, splices);
		}
631 632
	}

633 634
	async executeNotebookByAttachedKernel(viewType: string, uri: URI, token: CancellationToken): Promise<void> {
		return this._mainThreadNotebook.executeNotebookByAttachedKernel(viewType, uri, token);
R
rebornix 已提交
635 636
	}

637 638
	onDidReceiveMessage(editorId: string, rendererType: string | undefined, message: unknown): void {
		this._proxy.$onDidReceiveMessage(editorId, rendererType, message);
639 640
	}

R
rebornix 已提交
641 642 643 644 645 646 647
	async removeNotebookDocument(notebook: INotebookTextModel): Promise<void> {
		let document = this._mapping.get(URI.from(notebook.uri).toString());

		if (!document) {
			return;
		}

648
		// TODO@rebornix, remove cell should use emitDelta as well to ensure document/editor events are sent together
R
rebornix 已提交
649 650 651 652 653 654
		await this._proxy.$acceptDocumentAndEditorsDelta({ removedDocuments: [notebook.uri] });
		document.dispose();
		this._mapping.delete(URI.from(notebook.uri).toString());
	}

	// Methods for ExtHost
R
rebornix 已提交
655

656 657 658 659 660
	handleNotebookChange(resource: UriComponents) {
		let document = this._mapping.get(URI.from(resource).toString());
		document?.textModel.handleUnknownChange();
	}

661 662
	handleEdit(resource: UriComponents, editId: number, label: string | undefined): void {
		let document = this._mapping.get(URI.from(resource).toString());
R
rebornix 已提交
663 664 665 666 667 668 669
		if (document) {
			document.textModel.$handleEdit(label, () => {
				return this._proxy.$undoNotebook(document!.textModel.viewType, document!.textModel.uri, editId, document!.textModel.isDirty);
			}, () => {
				return this._proxy.$redoNotebook(document!.textModel.viewType, document!.textModel.uri, editId, document!.textModel.isDirty);
			});
		}
670 671
	}

R
rebornix 已提交
672 673
	updateLanguages(resource: UriComponents, languages: string[]) {
		let document = this._mapping.get(URI.from(resource).toString());
674
		document?.textModel.updateLanguages(languages);
R
rebornix 已提交
675 676
	}

R
rebornix 已提交
677
	updateNotebookMetadata(resource: UriComponents, metadata: NotebookDocumentMetadata) {
R
rebornix 已提交
678 679 680 681
		let document = this._mapping.get(URI.from(resource).toString());
		document?.textModel.updateNotebookMetadata(metadata);
	}

682 683 684 685 686
	updateNotebookCellMetadata(resource: UriComponents, handle: number, metadata: NotebookCellMetadata) {
		let document = this._mapping.get(URI.from(resource).toString());
		document?.textModel.updateNotebookCellMetadata(handle, metadata);
	}

687 688
	async executeNotebookCell(uri: URI, handle: number, token: CancellationToken): Promise<void> {
		return this._proxy.$executeNotebookByAttachedKernel(this._viewType, uri, handle, token);
689 690
	}

R
rebornix 已提交
691 692
	async save(uri: URI, token: CancellationToken): Promise<boolean> {
		return this._proxy.$saveNotebook(this._viewType, uri, token);
693
	}
R
saveAs  
rebornix 已提交
694 695 696

	async saveAs(uri: URI, target: URI, token: CancellationToken): Promise<boolean> {
		return this._proxy.$saveNotebookAs(this._viewType, uri, target, token);
697 698 699 700 701 702
	}

	async backup(uri: URI, token: CancellationToken): Promise<string | undefined> {
		const backupId = await this._proxy.$backup(this._viewType, uri, token);
		return backupId;
	}
R
rebornix 已提交
703
}
R
rebornix 已提交
704 705 706 707 708

export class MainThreadNotebookKernel implements INotebookKernelInfo {
	constructor(
		private readonly _proxy: ExtHostNotebookShape,
		readonly id: string,
R
rebornix 已提交
709
		readonly label: string,
R
rebornix 已提交
710 711 712 713 714 715 716 717 718 719 720
		readonly selectors: (string | IRelativePattern)[],
		readonly extension: ExtensionIdentifier,
		readonly extensionLocation: URI,
		readonly preloads: URI[]
	) {
	}

	async executeNotebook(viewType: string, uri: URI, handle: number | undefined, token: CancellationToken): Promise<void> {
		return this._proxy.$executeNotebook2(this.id, viewType, uri, handle, token);
	}
}
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741

export class MainThreadNotebookRenderer implements INotebookRendererInfo {
	constructor(
		private readonly _proxy: ExtHostNotebookShape,
		readonly id: string,
		readonly extensionId: ExtensionIdentifier,
		readonly extensionLocation: URI,
		readonly selectors: INotebookMimeTypeSelector,
		readonly preloads: URI[]
	) {

	}

	render(uri: URI, request: IOutputRenderRequest<UriComponents>): Promise<IOutputRenderResponse<UriComponents> | undefined> {
		return this._proxy.$renderOutputs(uri, this.id, request);
	}

	render2<T>(uri: URI, request: IOutputRenderRequest<T>): Promise<IOutputRenderResponse<T> | undefined> {
		return this._proxy.$renderOutputs2(uri, this.id, request);
	}
}