mainThreadNotebook.ts 27.0 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.
 *--------------------------------------------------------------------------------------------*/

6
import * as nls from 'vs/nls';
R
rebornix 已提交
7
import { extHostNamedCustomer } from 'vs/workbench/api/common/extHostCustomers';
8
import { MainContext, MainThreadNotebookShape, NotebookExtensionDescription, IExtHostContext, ExtHostNotebookShape, ExtHostContext, INotebookDocumentsAndEditorsDelta, INotebookModelAddedData } 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, INotebookTextModelBackup, IEditor, INotebookRendererInfo, IOutputRenderRequest, IOutputRenderResponse } 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 22
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IUndoRedoService, UndoRedoElementType } from 'vs/platform/undoRedo/common/undoRedo';
R
rebornix 已提交
23

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

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

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

R
rebornix 已提交
40
	) {
R
rebornix 已提交
41
		super();
42

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

54
	async applyEdit(modelVersionId: number, edits: ICellEditOperation[], emitToExtHost: boolean): Promise<boolean> {
55 56
		await this.notebookService.transformEditsOutputs(this.textModel, edits);
		return this._textModel.$applyEdit(modelVersionId, edits);
R
rebornix 已提交
57
	}
R
rebornix 已提交
58

59 60 61 62
	async spliceNotebookCellOutputs(cellHandle: number, splices: NotebookCellOutputsSplice[]) {
		await this.notebookService.transformSpliceOutputs(this.textModel, splices);
		this._textModel.$spliceNotebookCellOutputs(cellHandle, splices);
	}
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78

	handleEdit(editId: number, label: string | undefined): void {
		this.undoRedoService.pushElement({
			type: UndoRedoElementType.Resource,
			resource: this._textModel.uri,
			label: label ?? nls.localize('defaultEditLabel', "Edit"),
			undo: async () => {
				await this._proxy.$undoNotebook(this._textModel.viewType, this._textModel.uri, editId, this._textModel.isDirty);
			},
			redo: async () => {
				await this._proxy.$redoNotebook(this._textModel.viewType, this._textModel.uri, editId, this._textModel.isDirty);
			},
		});
		this._textModel.setDirty(true);
	}

R
rebornix 已提交
79
	dispose() {
80
		this._textModel.dispose();
R
rebornix 已提交
81 82
		super.dispose();
	}
R
rebornix 已提交
83 84
}

R
rebornix 已提交
85
class DocumentAndEditorState {
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
	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 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
	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: [],
128 129
				addedEditors: apiEditors,
				visibleEditors: [...after.visibleEditors].map(editor => editor[0])
R
rebornix 已提交
130 131
			};
		}
132
		const documentDelta = DocumentAndEditorState.ofSets(before.documents, after.documents);
R
rebornix 已提交
133 134 135 136
		const editorDelta = DocumentAndEditorState.ofMaps(before.textEditors, after.textEditors);
		const addedAPIEditors = editorDelta.added.map(add => ({
			id: add.getId(),
			documentUri: add.uri!,
137
			selections: add.textModel!.selections || []
R
rebornix 已提交
138 139 140 141 142 143 144
		}));

		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;

145 146
		const visibleEditorDelta = DocumentAndEditorState.ofMaps(before.visibleEditors, after.visibleEditors);

R
rebornix 已提交
147
		return {
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
			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(),
						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 已提交
171 172
			addedEditors: addedAPIEditors,
			removedEditors: removedAPIEditors,
173 174 175 176
			newActiveEditor: newActiveEditor,
			visibleEditors: visibleEditorDelta.added.length === 0 && visibleEditorDelta.removed.length === 0
				? undefined
				: [...after.visibleEditors].map(editor => editor[0])
R
rebornix 已提交
177 178 179 180
		};
	}

	constructor(
181
		readonly documents: Set<NotebookTextModel>,
R
rebornix 已提交
182 183
		readonly textEditors: Map<string, IEditor>,
		readonly activeEditor: string | null | undefined,
184
		readonly visibleEditors: Map<string, IEditor>
R
rebornix 已提交
185 186 187 188 189
	) {
		//
	}
}

R
rebornix 已提交
190 191 192
@extHostNamedCustomer(MainContext.MainThreadNotebook)
export class MainThreadNotebooks extends Disposable implements MainThreadNotebookShape {
	private readonly _notebookProviders = new Map<string, MainThreadNotebookController>();
R
rebornix 已提交
193
	private readonly _notebookKernels = new Map<string, MainThreadNotebookKernel>();
194
	private readonly _notebookRenderers = new Map<string, MainThreadNotebookRenderer>();
R
rebornix 已提交
195
	private readonly _proxy: ExtHostNotebookShape;
R
rebornix 已提交
196 197
	private _toDisposeOnEditorRemove = new Map<string, IDisposable>();
	private _currentState?: DocumentAndEditorState;
R
rebornix 已提交
198 199 200

	constructor(
		extHostContext: IExtHostContext,
R
rebornix 已提交
201
		@INotebookService private _notebookService: INotebookService,
202 203
		@IConfigurationService private readonly configurationService: IConfigurationService,
		@IEditorService private readonly editorService: IEditorService,
204 205
		@IAccessibilityService private readonly accessibilityService: IAccessibilityService,
		@IInstantiationService private readonly _instantiationService: IInstantiationService
206

R
rebornix 已提交
207 208 209
	) {
		super();
		this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostNotebook);
R
rebornix 已提交
210 211 212
		this.registerListeners();
	}

R
rebornix 已提交
213 214 215 216 217 218 219 220
	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 已提交
221 222
	}

R
rebornix 已提交
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
	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;
	}

251
	private _emitDelta(delta: INotebookDocumentsAndEditorsDelta) {
R
rebornix 已提交
252 253 254 255
		if (this._isDeltaEmpty(delta)) {
			return;
		}

256 257 258
		this._proxy.$acceptDocumentAndEditorsDelta(delta);
	}

R
rebornix 已提交
259
	registerListeners() {
R
rebornix 已提交
260 261 262 263
		this._notebookService.listNotebookEditors().forEach((e) => {
			this._addNotebookEditor(e);
		});

R
rebornix 已提交
264
		this._register(this._notebookService.onDidChangeActiveEditor(e => {
265
			this._updateState();
R
rebornix 已提交
266
		}));
R
rebornix 已提交
267

R
rebornix 已提交
268
		this._register(this._notebookService.onDidChangeVisibleEditors(e => {
269 270 271 272 273 274 275 276 277
			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 已提交
278 279
		}));

R
rebornix 已提交
280 281 282 283
		this._register(this._notebookService.onNotebookEditorAdd(editor => {
			this._addNotebookEditor(editor);
		}));

284 285 286
		this._register(this._notebookService.onNotebookEditorsRemove(editors => {
			this._removeNotebookEditor(editors);
		}));
287

R
rebornix 已提交
288 289 290 291
		this._register(this._notebookService.onNotebookDocumentAdd(() => {
			this._updateState();
		}));

292 293
		this._register(this._notebookService.onNotebookDocumentRemove(() => {
			this._updateState();
R
rebornix 已提交
294 295
		}));

R
rebornix 已提交
296 297 298 299 300 301 302
		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 已提交
303

R
rebornix 已提交
304
		updateOrder();
R
rebornix 已提交
305

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

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

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

321
	async addNotebookDocument(data: INotebookModelAddedData) {
322
		this._updateState();
323 324
	}

R
rebornix 已提交
325 326 327
	private _addNotebookEditor(e: IEditor) {
		this._toDisposeOnEditorRemove.set(e.getId(), combinedDisposable(
			e.onDidChangeModel(() => this._updateState()),
R
rebornix 已提交
328 329 330
			e.onDidFocusEditorWidget(() => {
				this._updateState(e);
			}),
R
rebornix 已提交
331 332
		));

R
rebornix 已提交
333 334 335
		const activeEditorPane = this.editorService.activeEditorPane as any | undefined;
		const notebookEditor = activeEditorPane?.isNotebookEditor ? activeEditorPane.getControl() : undefined;
		this._updateState(notebookEditor);
R
rebornix 已提交
336 337
	}

338 339 340 341 342 343 344 345 346 347
	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 已提交
348 349 350 351 352
	}

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

353 354 355 356 357 358 359 360 361 362
		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 已提交
363 364
			if (editor.hasModel()) {
				editors.set(editor.getId(), editor);
365 366 367 368 369 370 371 372 373 374
				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 已提交
375 376
				}
			}
377 378 379 380
		});

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

384
		if (!activeEditor && focusedNotebookEditor && focusedNotebookEditor.hasModel()) {
R
rebornix 已提交
385 386 387
			activeEditor = focusedNotebookEditor.getId();
		}

R
rebornix 已提交
388
		// editors always have view model attached, which means there is already a document in exthost.
389
		const newState = new DocumentAndEditorState(documents, editors, activeEditor, visibleEditorsMap);
R
rebornix 已提交
390 391 392 393 394 395 396 397 398
		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;
399
		await this._emitDelta(delta);
R
rebornix 已提交
400 401 402
		// }
	}

403 404 405 406
	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 已提交
407 408
	}

409 410
	async $unregisterNotebookRenderer(id: string): Promise<void> {
		this._notebookService.unregisterNotebookRenderer(id);
R
rebornix 已提交
411 412
	}

413
	async $registerNotebookProvider(extension: NotebookExtensionDescription, viewType: string, supportBackup: boolean, kernel: INotebookKernelInfoDto | undefined): Promise<void> {
414
		let controller = new MainThreadNotebookController(this._proxy, this, viewType, supportBackup, kernel, this._notebookService, this._instantiationService);
R
rebornix 已提交
415
		this._notebookProviders.set(viewType, controller);
R
rebornix 已提交
416
		this._notebookService.registerNotebookController(viewType, extension, controller);
R
rebornix 已提交
417
		return;
R
rebornix 已提交
418 419
	}

420 421 422 423 424 425 426
	async $onNotebookChange(viewType: string, uri: UriComponents): Promise<void> {
		let controller = this._notebookProviders.get(viewType);
		if (controller) {
			controller.handleNotebookChange(uri);
		}
	}

R
rebornix 已提交
427
	async $unregisterNotebookProvider(viewType: string): Promise<void> {
R
rebornix 已提交
428 429
		this._notebookProviders.delete(viewType);
		this._notebookService.unregisterNotebookProvider(viewType);
R
rebornix 已提交
430 431 432
		return;
	}

R
rebornix 已提交
433 434
	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 已提交
435 436 437 438 439 440 441 442 443 444 445
		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 已提交
446
	async $updateNotebookLanguages(viewType: string, resource: UriComponents, languages: string[]): Promise<void> {
R
rebornix 已提交
447 448 449
		let controller = this._notebookProviders.get(viewType);

		if (controller) {
R
rebornix 已提交
450
			controller.updateLanguages(resource, languages);
R
rebornix 已提交
451 452
		}
	}
R
rebornix 已提交
453

R
rebornix 已提交
454
	async $updateNotebookMetadata(viewType: string, resource: UriComponents, metadata: NotebookDocumentMetadata): Promise<void> {
R
rebornix 已提交
455 456 457 458 459 460 461
		let controller = this._notebookProviders.get(viewType);

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

462 463 464 465 466 467 468 469
	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);
		}
	}

470
	async $spliceNotebookCellOutputs(viewType: string, resource: UriComponents, cellHandle: number, splices: NotebookCellOutputsSplice[], renderers: number[]): Promise<void> {
471
		let controller = this._notebookProviders.get(viewType);
472
		await controller?.spliceNotebookCellOutputs(resource, cellHandle, splices, renderers);
473 474
	}

R
rebornix 已提交
475 476
	async executeNotebook(viewType: string, uri: URI, useAttachedKernel: boolean, token: CancellationToken): Promise<void> {
		return this._proxy.$executeNotebook(viewType, uri, undefined, useAttachedKernel, token);
R
rebornix 已提交
477
	}
478 479 480 481 482

	async $postMessage(handle: number, value: any): Promise<boolean> {

		const activeEditorPane = this.editorService.activeEditorPane as any | undefined;
		if (activeEditorPane?.isNotebookEditor) {
R
rebornix 已提交
483
			const notebookEditor = (activeEditorPane.getControl() as INotebookEditor);
484 485 486 487 488 489 490 491 492

			if (notebookEditor.viewModel?.handle === handle) {
				notebookEditor.postMessage(value);
				return true;
			}
		}

		return false;
	}
493 494 495 496 497 498 499 500 501 502

	$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 已提交
503 504 505
}

export class MainThreadNotebookController implements IMainNotebookController {
R
rebornix 已提交
506
	private _mapping: Map<string, MainThreadNotebookDocument> = new Map();
R
rebornix 已提交
507
	static documentHandle: number = 0;
R
rebornix 已提交
508 509

	constructor(
R
rebornix 已提交
510 511
		private readonly _proxy: ExtHostNotebookShape,
		private _mainThreadNotebook: MainThreadNotebooks,
R
rebornix 已提交
512
		private _viewType: string,
513
		private _supportBackup: boolean,
514 515
		readonly kernel: INotebookKernelInfoDto | undefined,
		readonly notebookService: INotebookService,
516
		readonly _instantiationService: IInstantiationService
517

R
rebornix 已提交
518 519 520
	) {
	}

521
	async createNotebook(viewType: string, uri: URI, backup: INotebookTextModelBackup | undefined, forceReload: boolean, editorId?: string, backupId?: string): Promise<NotebookTextModel | undefined> {
R
rebornix 已提交
522 523 524
		let mainthreadNotebook = this._mapping.get(URI.from(uri).toString());

		if (mainthreadNotebook) {
R
revert.  
rebornix 已提交
525 526 527 528 529 530 531 532
			if (forceReload) {
				const data = await this._proxy.$resolveNotebookData(viewType, uri);
				if (!data) {
					return;
				}

				mainthreadNotebook.textModel.languages = data.languages;
				mainthreadNotebook.textModel.metadata = data.metadata;
533
				await mainthreadNotebook.applyEdit(mainthreadNotebook.textModel.versionId, [
R
revert.  
rebornix 已提交
534 535
					{ editType: CellEditType.Delete, count: mainthreadNotebook.textModel.cells.length, index: 0 },
					{ editType: CellEditType.Insert, index: 0, cells: data.cells }
536
				], true);
R
revert.  
rebornix 已提交
537
			}
R
rebornix 已提交
538 539 540
			return mainthreadNotebook.textModel;
		}

541
		let document = this._instantiationService.createInstance(MainThreadNotebookDocument, this._proxy, MainThreadNotebookController.documentHandle++, viewType, this._supportBackup, uri);
R
rebornix 已提交
542 543 544 545 546 547 548
		this._mapping.set(document.uri.toString(), document);

		if (backup) {
			// trigger events
			document.textModel.metadata = backup.metadata;
			document.textModel.languages = backup.languages;

549
			// restored from backup, update the text model without emitting any event to exthost
550
			await document.applyEdit(document.textModel.versionId, [
R
rebornix 已提交
551 552 553
				{
					editType: CellEditType.Insert,
					index: 0,
554
					cells: backup.cells || []
R
rebornix 已提交
555
				}
556
			], false);
R
rebornix 已提交
557

558
			// create document in ext host with cells data
559
			await this._mainThreadNotebook.addNotebookDocument({
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
				viewType: document.viewType,
				handle: document.handle,
				uri: document.uri,
				metadata: document.textModel.metadata,
				versionId: document.textModel.versionId,
				cells: document.textModel.cells.map(cell => ({
					handle: cell.handle,
					uri: cell.uri,
					source: cell.textBuffer.getLinesContent(),
					language: cell.language,
					cellKind: cell.cellKind,
					outputs: cell.outputs,
					metadata: cell.metadata
				})),
				attachedEditor: editorId ? {
					id: editorId,
					selections: document.textModel.selections
				} : undefined
R
rebornix 已提交
578
			});
R
rebornix 已提交
579 580 581 582 583

			return document.textModel;
		}

		// open notebook document
584
		const data = await this._proxy.$resolveNotebookData(viewType, uri, backupId);
R
rebornix 已提交
585 586 587 588 589 590
		if (!data) {
			return;
		}

		document.textModel.languages = data.languages;
		document.textModel.metadata = data.metadata;
591 592 593 594 595 596 597

		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 已提交
598

599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
		await this._mainThreadNotebook.addNotebookDocument({
			viewType: document.viewType,
			handle: document.handle,
			uri: document.uri,
			metadata: document.textModel.metadata,
			versionId: document.textModel.versionId,
			cells: document.textModel.cells.map(cell => ({
				handle: cell.handle,
				uri: cell.uri,
				source: cell.textBuffer.getLinesContent(),
				language: cell.language,
				cellKind: cell.cellKind,
				outputs: cell.outputs,
				metadata: cell.metadata
			})),
			attachedEditor: editorId ? {
				id: editorId,
				selections: document.textModel.selections
			} : undefined
R
rebornix 已提交
618 619
		});

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

R
rebornix 已提交
622 623 624
		return document.textModel;
	}

625 626 627 628
	async resolveNotebookEditor(viewType: string, uri: URI, editorId: string) {
		await this._proxy.$resolveNotebookEditor(viewType, uri, editorId);
	}

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

		if (mainthreadNotebook) {
633
			return await mainthreadNotebook.applyEdit(modelVersionId, edits, true);
R
rebornix 已提交
634 635 636
		}

		return false;
637 638
	}

639
	async spliceNotebookCellOutputs(resource: UriComponents, cellHandle: number, splices: NotebookCellOutputsSplice[], renderers: number[]): Promise<void> {
640
		let mainthreadNotebook = this._mapping.get(URI.from(resource).toString());
641
		await mainthreadNotebook?.spliceNotebookCellOutputs(cellHandle, splices);
642 643
	}

R
rebornix 已提交
644 645
	async executeNotebook(viewType: string, uri: URI, useAttachedKernel: boolean, token: CancellationToken): Promise<void> {
		return this._mainThreadNotebook.executeNotebook(viewType, uri, useAttachedKernel, token);
R
rebornix 已提交
646 647
	}

648 649
	onDidReceiveMessage(editorId: string, message: any): void {
		this._proxy.$onDidReceiveMessage(editorId, message);
650 651
	}

R
rebornix 已提交
652 653 654 655 656 657 658
	async removeNotebookDocument(notebook: INotebookTextModel): Promise<void> {
		let document = this._mapping.get(URI.from(notebook.uri).toString());

		if (!document) {
			return;
		}

659
		// TODO@rebornix, remove cell should use emitDelta as well to ensure document/editor events are sent together
R
rebornix 已提交
660 661 662 663 664 665
		await this._proxy.$acceptDocumentAndEditorsDelta({ removedDocuments: [notebook.uri] });
		document.dispose();
		this._mapping.delete(URI.from(notebook.uri).toString());
	}

	// Methods for ExtHost
R
rebornix 已提交
666

667 668 669 670 671
	handleNotebookChange(resource: UriComponents) {
		let document = this._mapping.get(URI.from(resource).toString());
		document?.textModel.handleUnknownChange();
	}

672 673 674 675 676
	handleEdit(resource: UriComponents, editId: number, label: string | undefined): void {
		let document = this._mapping.get(URI.from(resource).toString());
		document?.handleEdit(editId, label);
	}

R
rebornix 已提交
677 678
	updateLanguages(resource: UriComponents, languages: string[]) {
		let document = this._mapping.get(URI.from(resource).toString());
679
		document?.textModel.updateLanguages(languages);
R
rebornix 已提交
680 681
	}

R
rebornix 已提交
682
	updateNotebookMetadata(resource: UriComponents, metadata: NotebookDocumentMetadata) {
R
rebornix 已提交
683 684 685 686
		let document = this._mapping.get(URI.from(resource).toString());
		document?.textModel.updateNotebookMetadata(metadata);
	}

687 688 689 690 691
	updateNotebookCellMetadata(resource: UriComponents, handle: number, metadata: NotebookCellMetadata) {
		let document = this._mapping.get(URI.from(resource).toString());
		document?.textModel.updateNotebookCellMetadata(handle, metadata);
	}

R
rebornix 已提交
692 693
	async executeNotebookCell(uri: URI, handle: number, useAttachedKernel: boolean, token: CancellationToken): Promise<void> {
		return this._proxy.$executeNotebook(this._viewType, uri, handle, useAttachedKernel, token);
694 695
	}

R
rebornix 已提交
696 697
	async save(uri: URI, token: CancellationToken): Promise<boolean> {
		return this._proxy.$saveNotebook(this._viewType, uri, token);
698
	}
R
saveAs  
rebornix 已提交
699 700 701

	async saveAs(uri: URI, target: URI, token: CancellationToken): Promise<boolean> {
		return this._proxy.$saveNotebookAs(this._viewType, uri, target, token);
702 703 704 705 706 707
	}

	async backup(uri: URI, token: CancellationToken): Promise<string | undefined> {
		const backupId = await this._proxy.$backup(this._viewType, uri, token);
		return backupId;
	}
R
rebornix 已提交
708
}
R
rebornix 已提交
709 710 711 712 713

export class MainThreadNotebookKernel implements INotebookKernelInfo {
	constructor(
		private readonly _proxy: ExtHostNotebookShape,
		readonly id: string,
R
rebornix 已提交
714
		readonly label: string,
R
rebornix 已提交
715 716 717 718 719 720 721 722 723 724 725
		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);
	}
}
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746

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