notebookServiceImpl.ts 32.7 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 { flatten } from 'vs/base/common/arrays';
R
rebornix 已提交
7
import { CancellationToken } from 'vs/base/common/cancellation';
8 9 10
import { Emitter, Event } from 'vs/base/common/event';
import { Iterable } from 'vs/base/common/iterator';
import { Disposable, DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
J
Johannes Rieken 已提交
11
import { ResourceMap } from 'vs/base/common/map';
12
import { URI } from 'vs/base/common/uri';
R
rebornix 已提交
13
import { RedoCommand, UndoCommand } from 'vs/editor/browser/editorExtensions';
14
import { CopyAction, CutAction, PasteAction } from 'vs/editor/contrib/clipboard/clipboard';
15 16
import * as nls from 'vs/nls';
import { IAccessibilityService } from 'vs/platform/accessibility/common/accessibility';
17
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
18 19 20 21 22 23 24 25
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { NotebookExtensionDescription } from 'vs/workbench/api/common/extHost.protocol';
import { Memento } from 'vs/workbench/common/memento';
import { INotebookEditorContribution, notebookProviderExtensionPoint, notebookRendererExtensionPoint } from 'vs/workbench/contrib/notebook/browser/extensionPoint';
import { getActiveNotebookEditor, INotebookEditor, NotebookEditorOptions } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { NotebookKernelProviderAssociationRegistry, NotebookViewTypesExtensionRegistry, updateNotebookKernelProvideAssociationSchema } from 'vs/workbench/contrib/notebook/browser/notebookKernelAssociation';
26
import { CellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookViewModel';
27 28
import { NotebookCellTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookCellTextModel';
import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel';
R
rebornix 已提交
29
import { ACCESSIBLE_NOTEBOOK_DISPLAY_ORDER, BUILTIN_RENDERER_ID, CellEditType, CellOutputKind, CellUri, DisplayOrderKey, ICellEditOperation, IDisplayOutput, INotebookKernelInfo2, INotebookKernelProvider, INotebookRendererInfo, INotebookTextModel, IOrderedMimeType, ITransformedDisplayOutputDto, mimeTypeSupportedByCore, NotebookCellOutputsSplice, notebookDocumentFilterMatch, NotebookEditorPriority, NOTEBOOK_DISPLAY_ORDER, sortMimeTypes } from 'vs/workbench/contrib/notebook/common/notebookCommon';
30 31 32 33 34 35
import { NotebookOutputRendererInfo } from 'vs/workbench/contrib/notebook/common/notebookOutputRenderer';
import { NotebookEditorDescriptor, NotebookProviderInfo } from 'vs/workbench/contrib/notebook/common/notebookProvider';
import { IMainNotebookController, INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
import { ICustomEditorInfo, ICustomEditorViewTypesHandler, IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IExtensionPointUser } from 'vs/workbench/services/extensions/common/extensionsRegistry';
36

R
rebornix 已提交
37 38 39 40 41 42 43 44 45 46 47 48
export class NotebookKernelProviderInfoStore extends Disposable {
	private readonly _notebookKernelProviders: INotebookKernelProvider[] = [];

	constructor() {
		super();
	}

	add(provider: INotebookKernelProvider) {
		this._notebookKernelProviders.push(provider);
		this._updateProviderExtensionsInfo();

		return toDisposable(() => {
R
Rob Lourens 已提交
49
			const idx = this._notebookKernelProviders.indexOf(provider);
R
rebornix 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
			if (idx >= 0) {
				this._notebookKernelProviders.splice(idx, 1);
			}

			this._updateProviderExtensionsInfo();
		});
	}

	get(viewType: string, resource: URI) {
		return this._notebookKernelProviders.filter(provider => notebookDocumentFilterMatch(provider.selector, viewType, resource));
	}

	private _updateProviderExtensionsInfo() {
		NotebookKernelProviderAssociationRegistry.extensionIds.length = 0;
		NotebookKernelProviderAssociationRegistry.extensionDescriptions.length = 0;

		this._notebookKernelProviders.forEach(provider => {
			NotebookKernelProviderAssociationRegistry.extensionIds.push(provider.providerExtensionId);
			NotebookKernelProviderAssociationRegistry.extensionDescriptions.push(provider.providerDescription || '');
		});

		updateNotebookKernelProvideAssociationSchema();
	}
}

75
export class NotebookProviderInfoStore extends Disposable {
76 77 78 79
	private static readonly CUSTOM_EDITORS_STORAGE_ID = 'notebookEditors';
	private static readonly CUSTOM_EDITORS_ENTRY_ID = 'editors';

	private readonly _memento: Memento;
80 81 82 83 84 85 86
	private _handled: boolean = false;
	constructor(
		storageService: IStorageService,
		extensionService: IExtensionService

	) {
		super();
87 88 89 90 91 92
		this._memento = new Memento(NotebookProviderInfoStore.CUSTOM_EDITORS_STORAGE_ID, storageService);

		const mementoObject = this._memento.getMemento(StorageScope.GLOBAL);
		for (const info of (mementoObject[NotebookProviderInfoStore.CUSTOM_EDITORS_ENTRY_ID] || []) as NotebookEditorDescriptor[]) {
			this.add(new NotebookProviderInfo(info));
		}
93

R
rebornix 已提交
94 95
		this._updateProviderExtensionsInfo();

96 97 98 99 100 101 102
		this._register(extensionService.onDidRegisterExtensions(() => {
			if (!this._handled) {
				// there is no extension point registered for notebook content provider
				// clear the memento and cache
				this.clear();
				mementoObject[NotebookProviderInfoStore.CUSTOM_EDITORS_ENTRY_ID] = [];
				this._memento.saveMemento();
R
rebornix 已提交
103 104

				this._updateProviderExtensionsInfo();
105 106
			}
		}));
107 108
	}

109 110
	setupHandler(extensions: readonly IExtensionPointUser<INotebookEditorContribution[]>[]) {
		this._handled = true;
111 112 113 114 115 116 117 118
		this.clear();

		for (const extension of extensions) {
			for (const notebookContribution of extension.value) {
				this.add(new NotebookProviderInfo({
					id: notebookContribution.viewType,
					displayName: notebookContribution.displayName,
					selector: notebookContribution.selector || [],
R
rebornix 已提交
119
					priority: this._convertPriority(notebookContribution.priority),
R
rebornix 已提交
120 121
					providerExtensionId: extension.description.identifier.value,
					providerDescription: extension.description.description,
122 123 124 125 126 127 128
					providerDisplayName: extension.description.isBuiltin ? nls.localize('builtinProviderDisplayName', "Built-in") : extension.description.displayName || extension.description.identifier.value,
					providerExtensionLocation: extension.description.extensionLocation
				}));
			}
		}

		const mementoObject = this._memento.getMemento(StorageScope.GLOBAL);
R
rebornix 已提交
129
		mementoObject[NotebookProviderInfoStore.CUSTOM_EDITORS_ENTRY_ID] = Array.from(this._contributedEditors.values());
130
		this._memento.saveMemento();
R
rebornix 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146

		this._updateProviderExtensionsInfo();
	}

	private _updateProviderExtensionsInfo() {
		NotebookViewTypesExtensionRegistry.viewTypes.length = 0;
		NotebookViewTypesExtensionRegistry.viewTypeDescriptions.length = 0;

		for (const contribute of this._contributedEditors) {
			if (contribute[1].providerExtensionId) {
				NotebookViewTypesExtensionRegistry.viewTypes.push(contribute[1].id);
				NotebookViewTypesExtensionRegistry.viewTypeDescriptions.push(`${contribute[1].displayName}`);
			}
		}

		updateNotebookKernelProvideAssociationSchema();
147 148
	}

R
rebornix 已提交
149
	private _convertPriority(priority?: string) {
150 151 152 153 154 155 156 157 158 159 160 161
		if (!priority) {
			return NotebookEditorPriority.default;
		}

		if (priority === NotebookEditorPriority.default) {
			return NotebookEditorPriority.default;
		}

		return NotebookEditorPriority.option;

	}

R
rebornix 已提交
162
	private readonly _contributedEditors = new Map<string, NotebookProviderInfo>();
R
rebornix 已提交
163

R
rebornix 已提交
164
	clear() {
R
rebornix 已提交
165
		this._contributedEditors.clear();
R
rebornix 已提交
166 167
	}

R
rebornix 已提交
168
	get(viewType: string): NotebookProviderInfo | undefined {
R
rebornix 已提交
169
		return this._contributedEditors.get(viewType);
R
rebornix 已提交
170 171
	}

R
rebornix 已提交
172
	add(info: NotebookProviderInfo): void {
R
rebornix 已提交
173
		if (this._contributedEditors.has(info.id)) {
R
rebornix 已提交
174 175
			return;
		}
R
rebornix 已提交
176
		this._contributedEditors.set(info.id, info);
R
rebornix 已提交
177 178
	}

R
rebornix 已提交
179
	getContributedNotebook(resource: URI): readonly NotebookProviderInfo[] {
R
rebornix 已提交
180
		return [...Iterable.filter(this._contributedEditors.values(), customEditor => resource.scheme === 'untitled' || customEditor.matches(resource))];
R
rebornix 已提交
181
	}
182 183

	public [Symbol.iterator](): Iterator<NotebookProviderInfo> {
R
rebornix 已提交
184
		return this._contributedEditors.values();
185
	}
R
rebornix 已提交
186 187
}

R
rebornix 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
export class NotebookOutputRendererInfoStore {
	private readonly contributedRenderers = new Map<string, NotebookOutputRendererInfo>();

	clear() {
		this.contributedRenderers.clear();
	}

	get(viewType: string): NotebookOutputRendererInfo | undefined {
		return this.contributedRenderers.get(viewType);
	}

	add(info: NotebookOutputRendererInfo): void {
		if (this.contributedRenderers.has(info.id)) {
			return;
		}
		this.contributedRenderers.set(info.id, info);
	}

	getContributedRenderer(mimeType: string): readonly NotebookOutputRendererInfo[] {
		return Array.from(this.contributedRenderers.values()).filter(customEditor =>
			customEditor.matches(mimeType));
	}
}

R
rebornix 已提交
212 213 214 215
class ModelData implements IDisposable {
	private readonly _modelEventListeners = new DisposableStore();

	constructor(
216 217
		public model: NotebookTextModel,
		onWillDispose: (model: INotebookTextModel) => void
R
rebornix 已提交
218 219 220 221
	) {
		this._modelEventListeners.add(model.onWillDispose(() => onWillDispose(model)));
	}

R
rebornix 已提交
222
	dispose(): void {
R
rebornix 已提交
223 224 225
		this._modelEventListeners.dispose();
	}
}
226
export class NotebookService extends Disposable implements INotebookService, ICustomEditorViewTypesHandler {
227
	declare readonly _serviceBrand: undefined;
R
rebornix 已提交
228
	private readonly _notebookProviders = new Map<string, { controller: IMainNotebookController, extensionData: NotebookExtensionDescription }>();
229
	notebookProviderInfoStore: NotebookProviderInfoStore;
R
rebornix 已提交
230
	notebookRenderersInfoStore: NotebookOutputRendererInfoStore = new NotebookOutputRendererInfoStore();
R
rebornix 已提交
231
	notebookKernelProviderInfoStore: NotebookKernelProviderInfoStore = new NotebookKernelProviderInfoStore();
J
Johannes Rieken 已提交
232
	private readonly _models = new ResourceMap<ModelData>();
R
rebornix 已提交
233 234
	private _onDidChangeActiveEditor = new Emitter<string | null>();
	onDidChangeActiveEditor: Event<string | null> = this._onDidChangeActiveEditor.event;
R
rebornix 已提交
235
	private _activeEditorDisposables = new DisposableStore();
R
rebornix 已提交
236 237
	private _onDidChangeVisibleEditors = new Emitter<string[]>();
	onDidChangeVisibleEditors: Event<string[]> = this._onDidChangeVisibleEditors.event;
R
rebornix 已提交
238 239
	private readonly _onNotebookEditorAdd: Emitter<INotebookEditor> = this._register(new Emitter<INotebookEditor>());
	public readonly onNotebookEditorAdd: Event<INotebookEditor> = this._onNotebookEditorAdd.event;
240 241
	private readonly _onNotebookEditorsRemove: Emitter<INotebookEditor[]> = this._register(new Emitter<INotebookEditor[]>());
	public readonly onNotebookEditorsRemove: Event<INotebookEditor[]> = this._onNotebookEditorsRemove.event;
242 243 244 245 246 247

	private readonly _onDidAddNotebookDocument = this._register(new Emitter<NotebookTextModel>());
	private readonly _onDidRemoveNotebookDocument = this._register(new Emitter<URI>());
	readonly onDidAddNotebookDocument = this._onDidAddNotebookDocument.event;
	readonly onDidRemoveNotebookDocument = this._onDidRemoveNotebookDocument.event;

248 249
	private readonly _onNotebookDocumentSaved: Emitter<URI> = this._register(new Emitter<URI>());
	public readonly onNotebookDocumentSaved: Event<URI> = this._onNotebookDocumentSaved.event;
250
	private readonly _notebookEditors = new Map<string, INotebookEditor>();
R
rebornix 已提交
251

252 253
	private readonly _onDidChangeViewTypes = new Emitter<void>();
	onDidChangeViewTypes: Event<void> = this._onDidChangeViewTypes.event;
R
rebornix 已提交
254

R
rebornix 已提交
255 256
	private readonly _onDidChangeKernels = new Emitter<URI | undefined>();
	onDidChangeKernels: Event<URI | undefined> = this._onDidChangeKernels.event;
R
rebornix 已提交
257 258
	private readonly _onDidChangeNotebookActiveKernel = new Emitter<{ uri: URI, providerHandle: number | undefined, kernelId: string | undefined }>();
	onDidChangeNotebookActiveKernel: Event<{ uri: URI, providerHandle: number | undefined, kernelId: string | undefined }> = this._onDidChangeNotebookActiveKernel.event;
R
rebornix 已提交
259
	private cutItems: NotebookCellTextModel[] | undefined;
R
rebornix 已提交
260
	private _lastClipboardIsCopy: boolean = true;
261

262
	private _displayOrder: { userOrder: string[], defaultOrder: string[] } = Object.create(null);
263

264
	constructor(
R
rebornix 已提交
265 266 267 268
		@IExtensionService private readonly _extensionService: IExtensionService,
		@IEditorService private readonly _editorService: IEditorService,
		@IConfigurationService private readonly _configurationService: IConfigurationService,
		@IAccessibilityService private readonly _accessibilityService: IAccessibilityService,
269 270
		@IStorageService private readonly _storageService: IStorageService,
		@IInstantiationService private readonly _instantiationService: IInstantiationService
271
	) {
R
rebornix 已提交
272 273
		super();

274
		this.notebookProviderInfoStore = new NotebookProviderInfoStore(this._storageService, this._extensionService);
275
		this._register(this.notebookProviderInfoStore);
276

R
rebornix 已提交
277
		notebookProviderExtensionPoint.setHandler((extensions) => {
278
			this.notebookProviderInfoStore.setupHandler(extensions);
R
rebornix 已提交
279 280
		});

R
rebornix 已提交
281 282 283 284 285
		notebookRendererExtensionPoint.setHandler((renderers) => {
			this.notebookRenderersInfoStore.clear();

			for (const extension of renderers) {
				for (const notebookContribution of extension.value) {
286 287 288 289 290
					if (!notebookContribution.entrypoint) { // avoid crashing
						console.error(`Cannot register renderer for ${extension.description.identifier.value} since it did not have an entrypoint. This is now required: https://github.com/microsoft/vscode/issues/102644`);
						continue;
					}

291 292 293 294 295 296
					const id = notebookContribution.id ?? notebookContribution.viewType;
					if (!id) {
						console.error(`Notebook renderer from ${extension.description.identifier.value} is missing an 'id'`);
						continue;
					}

R
rebornix 已提交
297
					this.notebookRenderersInfoStore.add(new NotebookOutputRendererInfo({
298
						id,
299 300
						extension: extension.description,
						entrypoint: notebookContribution.entrypoint,
R
rebornix 已提交
301
						displayName: notebookContribution.displayName,
302
						mimeTypes: notebookContribution.mimeTypes || [],
R
rebornix 已提交
303 304 305 306
					}));
				}
			}
		});
307

R
rebornix 已提交
308
		this._editorService.registerCustomEditorViewTypesHandler('Notebook', this);
309 310

		const updateOrder = () => {
311
			const userOrder = this._configurationService.getValue<string[]>(DisplayOrderKey);
312
			this._displayOrder = {
R
rebornix 已提交
313
				defaultOrder: this._accessibilityService.isScreenReaderOptimized() ? ACCESSIBLE_NOTEBOOK_DISPLAY_ORDER : NOTEBOOK_DISPLAY_ORDER,
314 315 316 317 318 319
				userOrder: userOrder
			};
		};

		updateOrder();

R
rebornix 已提交
320
		this._register(this._configurationService.onDidChangeConfiguration(e => {
321
			if (e.affectedKeys.indexOf(DisplayOrderKey) >= 0) {
322 323 324 325
				updateOrder();
			}
		}));

R
rebornix 已提交
326
		this._register(this._accessibilityService.onDidChangeScreenReaderOptimized(() => {
327 328
			updateOrder();
		}));
R
rebornix 已提交
329

330
		const getContext = () => {
R
rebornix 已提交
331
			const editor = getActiveNotebookEditor(this._editorService);
332 333 334 335 336 337 338 339 340 341 342
			const activeCell = editor?.getActiveCell();

			return {
				editor,
				activeCell
			};
		};

		const PRIORITY = 50;
		this._register(UndoCommand.addImplementation(PRIORITY, () => {
			const { editor } = getContext();
R
rebornix 已提交
343
			if (editor?.viewModel) {
R
rebornix 已提交
344 345 346 347 348
				editor?.viewModel.undo().then(cellResources => {
					if (cellResources?.length) {
						editor?.setOptions(new NotebookEditorOptions({ cellOptions: { resource: cellResources[0] } }));
					}
				});
R
rebornix 已提交
349 350 351 352 353 354 355
				return true;
			}

			return false;
		}));

		this._register(RedoCommand.addImplementation(PRIORITY, () => {
356
			const { editor } = getContext();
R
rebornix 已提交
357
			if (editor?.viewModel) {
R
rebornix 已提交
358 359 360 361 362
				editor?.viewModel.redo().then(cellResources => {
					if (cellResources?.length) {
						editor?.setOptions(new NotebookEditorOptions({ cellOptions: { resource: cellResources[0] } }));
					}
				});
R
rebornix 已提交
363 364 365 366 367
				return true;
			}

			return false;
		}));
368 369 370

		if (CopyAction) {
			this._register(CopyAction.addImplementation(PRIORITY, accessor => {
R
rebornix 已提交
371 372 373 374 375
				const activeElement = <HTMLElement>document.activeElement;
				if (activeElement && ['input', 'textarea'].indexOf(activeElement.tagName.toLowerCase()) >= 0) {
					return false;
				}

376 377 378 379 380
				const { editor, activeCell } = getContext();
				if (!editor || !activeCell) {
					return false;
				}

R
rebornix 已提交
381 382 383 384 385
				if (editor.hasOutputTextSelection()) {
					document.execCommand('copy');
					return true;
				}

386 387 388 389 390 391 392 393 394 395 396
				const clipboardService = accessor.get<IClipboardService>(IClipboardService);
				const notebookService = accessor.get<INotebookService>(INotebookService);
				clipboardService.writeText(activeCell.getText());
				notebookService.setToCopy([activeCell.model], true);

				return true;
			}));
		}

		if (PasteAction) {
			PasteAction.addImplementation(PRIORITY, () => {
R
rebornix 已提交
397 398 399 400 401
				const activeElement = <HTMLElement>document.activeElement;
				if (activeElement && ['input', 'textarea'].indexOf(activeElement.tagName.toLowerCase()) >= 0) {
					return false;
				}

402 403 404 405 406 407 408
				const pasteCells = this.getToCopy();

				if (!pasteCells) {
					return false;
				}

				const { editor, activeCell } = getContext();
R
rebornix 已提交
409
				if (!editor) {
410 411 412 413 414 415 416 417 418
					return false;
				}

				const viewModel = editor.viewModel;

				if (!viewModel) {
					return false;
				}

R
rebornix 已提交
419 420 421 422
				if (!viewModel.metadata.editable) {
					return false;
				}

R
rebornix 已提交
423 424 425 426 427 428 429 430 431 432 433 434 435
				if (activeCell) {
					const currCellIndex = viewModel.getCellIndex(activeCell);

					let topPastedCell: CellViewModel | undefined = undefined;
					pasteCells.items.reverse().map(cell => {
						const data = CellUri.parse(cell.uri);

						if (pasteCells.isCopy || data?.notebook.toString() !== viewModel.uri.toString()) {
							return viewModel.notebookDocument.createCellTextModel(
								cell.getValue(),
								cell.language,
								cell.cellKind,
								[],
R
rebornix 已提交
436 437 438 439 440 441 442 443 444
								{
									editable: cell.metadata?.editable,
									runnable: cell.metadata?.runnable,
									breakpointMargin: cell.metadata?.breakpointMargin,
									hasExecutionOrder: cell.metadata?.hasExecutionOrder,
									inputCollapsed: cell.metadata?.inputCollapsed,
									outputCollapsed: cell.metadata?.outputCollapsed,
									custom: cell.metadata?.custom
								}
R
rebornix 已提交
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
							);
						} else {
							return cell;
						}
					}).forEach(pasteCell => {
						const newIdx = typeof currCellIndex === 'number' ? currCellIndex + 1 : 0;
						topPastedCell = viewModel.insertCell(newIdx, pasteCell, true);
					});

					if (topPastedCell) {
						editor.focusNotebookCell(topPastedCell, 'container');
					}
				} else {
					if (viewModel.length !== 0) {
						return false;
460 461
					}

R
rebornix 已提交
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
					let topPastedCell: CellViewModel | undefined = undefined;
					pasteCells.items.reverse().map(cell => {
						const data = CellUri.parse(cell.uri);

						if (pasteCells.isCopy || data?.notebook.toString() !== viewModel.uri.toString()) {
							return viewModel.notebookDocument.createCellTextModel(
								cell.getValue(),
								cell.language,
								cell.cellKind,
								[],
								cell.metadata
							);
						} else {
							return cell;
						}
					}).forEach(pasteCell => {
						topPastedCell = viewModel.insertCell(0, pasteCell, true);
					});

					if (topPastedCell) {
						editor.focusNotebookCell(topPastedCell, 'container');
					}
484 485
				}

R
rebornix 已提交
486

487 488 489 490 491 492
				return true;
			});
		}

		if (CutAction) {
			CutAction.addImplementation(PRIORITY, accessor => {
R
rebornix 已提交
493 494 495 496 497
				const activeElement = <HTMLElement>document.activeElement;
				if (activeElement && ['input', 'textarea'].indexOf(activeElement.tagName.toLowerCase()) >= 0) {
					return false;
				}

498 499 500 501 502 503 504 505 506 507 508
				const { editor, activeCell } = getContext();
				if (!editor || !activeCell) {
					return false;
				}

				const viewModel = editor.viewModel;

				if (!viewModel) {
					return false;
				}

R
rebornix 已提交
509 510 511 512
				if (!viewModel.metadata.editable) {
					return false;
				}

513 514 515 516 517 518 519 520 521 522
				const clipboardService = accessor.get<IClipboardService>(IClipboardService);
				const notebookService = accessor.get<INotebookService>(INotebookService);
				clipboardService.writeText(activeCell.getText());
				viewModel.deleteCell(viewModel.getCellIndex(activeCell), true);
				notebookService.setToCopy([activeCell.model], false);

				return true;
			});
		}

523 524 525 526 527 528 529 530
	}

	getViewTypes(): ICustomEditorInfo[] {
		return [...this.notebookProviderInfoStore].map(info => ({
			id: info.id,
			displayName: info.displayName,
			providerDisplayName: info.providerDisplayName
		}));
R
rebornix 已提交
531 532
	}

533 534
	async canResolve(viewType: string): Promise<boolean> {
		if (!this._notebookProviders.has(viewType)) {
R
rebornix 已提交
535
			await this._extensionService.whenInstalledExtensionsRegistered();
536
			// notebook providers/kernels/renderers might use `*` as activation event.
R
rebornix 已提交
537
			await this._extensionService.activateByEvent(`*`);
538
			// this awaits full activation of all matching extensions
539 540 541
			await this._extensionService.activateByEvent(`onNotebook:${viewType}`);

			// TODO@jrieken deprecated, remove this
R
rebornix 已提交
542
			await this._extensionService.activateByEvent(`onNotebookEditor:${viewType}`);
R
rebornix 已提交
543
		}
544
		return this._notebookProviders.has(viewType);
545 546
	}

547
	registerNotebookController(viewType: string, extensionData: NotebookExtensionDescription, controller: IMainNotebookController): IDisposable {
R
rebornix 已提交
548
		this._notebookProviders.set(viewType, { extensionData, controller });
549
		this._onDidChangeViewTypes.fire();
550 551 552 553
		return toDisposable(() => {
			this._notebookProviders.delete(viewType);
			this._onDidChangeViewTypes.fire();
		});
R
rebornix 已提交
554 555
	}

R
rebornix 已提交
556
	registerNotebookKernelProvider(provider: INotebookKernelProvider): IDisposable {
R
rebornix 已提交
557
		const d = this.notebookKernelProviderInfoStore.add(provider);
R
rebornix 已提交
558 559
		const kernelChangeEventListener = provider.onDidChangeKernels((e) => {
			this._onDidChangeKernels.fire(e);
R
rebornix 已提交
560
		});
561

R
rebornix 已提交
562
		this._onDidChangeKernels.fire(undefined);
R
rebornix 已提交
563
		return toDisposable(() => {
R
rebornix 已提交
564
			kernelChangeEventListener.dispose();
R
rebornix 已提交
565
			d.dispose();
R
rebornix 已提交
566 567 568 569
		});
	}

	async getContributedNotebookKernels2(viewType: string, resource: URI, token: CancellationToken): Promise<INotebookKernelInfo2[]> {
R
rebornix 已提交
570
		const filteredProvider = this.notebookKernelProviderInfoStore.get(viewType, resource);
R
rebornix 已提交
571 572 573 574 575 576 577
		const result = new Array<INotebookKernelInfo2[]>(filteredProvider.length);

		const promises = filteredProvider.map(async (provider, index) => {
			const data = await provider.provideKernels(resource, token);
			result[index] = data.map(dto => {
				return {
					extension: dto.extension,
R
rebornix 已提交
578
					extensionLocation: URI.revive(dto.extensionLocation),
R
rebornix 已提交
579 580 581
					id: dto.id,
					label: dto.label,
					description: dto.description,
R
rebornix 已提交
582
					detail: dto.detail,
R
rebornix 已提交
583 584
					isPreferred: dto.isPreferred,
					preloads: dto.preloads,
R
rebornix 已提交
585
					providerHandle: dto.providerHandle,
R
rebornix 已提交
586 587
					resolve: async (uri: URI, editorId: string, token: CancellationToken) => {
						return provider.resolveKernel(editorId, uri, dto.id, token);
R
rebornix 已提交
588
					},
R
Rob Lourens 已提交
589 590
					executeNotebookCell: async (uri: URI, handle: number | undefined) => {
						return provider.executeNotebook(uri, dto.id, handle);
591 592 593
					},
					cancelNotebookCell: (uri: URI, handle: number | undefined): Promise<void> => {
						return provider.cancelNotebook(uri, dto.id, handle);
R
rebornix 已提交
594 595 596 597 598 599 600 601 602
					}
				};
			});
		});

		await Promise.all(promises);

		return flatten(result);
	}
R
rebornix 已提交
603

604
	getRendererInfo(id: string): INotebookRendererInfo | undefined {
605
		return this.notebookRenderersInfoStore.get(id);
606 607
	}

608
	async resolveNotebook(viewType: string, uri: URI, forceReload: boolean, editorId?: string, backupId?: string): Promise<NotebookTextModel> {
609

610
		if (!await this.canResolve(viewType)) {
611
			throw new Error(`CANNOT load notebook, no provider for '${viewType}'`);
R
rebornix 已提交
612 613
		}

614 615
		const provider = this._notebookProviders.get(viewType)!;
		let notebookModel: NotebookTextModel;
J
Johannes Rieken 已提交
616
		if (this._models.has(uri)) {
617
			// the model already exists
J
Johannes Rieken 已提交
618
			notebookModel = this._models.get(uri)!.model;
619 620 621
			if (forceReload) {
				await provider.controller.reloadNotebook(notebookModel);
			}
622
			return notebookModel;
623

624
		} else {
625
			notebookModel = this._instantiationService.createInstance(NotebookTextModel, viewType, provider.controller.supportBackup, uri);
626
			await provider.controller.createNotebook(notebookModel, backupId);
R
rebornix 已提交
627 628
		}

R
rebornix 已提交
629 630
		// new notebook model created
		const modelData = new ModelData(
631
			notebookModel,
632
			(model) => this._onWillDisposeDocument(model),
R
rebornix 已提交
633 634
		);

J
Johannes Rieken 已提交
635
		this._models.set(uri, modelData);
636
		this._onDidAddNotebookDocument.fire(notebookModel);
637
		// after the document is added to the store and sent to ext host, we transform the ouputs
638
		await this.transformTextModelOutputs(notebookModel);
639 640 641 642 643

		if (editorId) {
			await provider.controller.resolveNotebookEditor(viewType, uri, editorId);
		}

644
		return modelData.model;
R
rebornix 已提交
645 646
	}

647
	getNotebookTextModel(uri: URI): NotebookTextModel | undefined {
J
Johannes Rieken 已提交
648
		return this._models.get(uri)?.model;
649 650
	}

651 652 653 654
	getNotebookTextModels(): Iterable<NotebookTextModel> {
		return Iterable.map(this._models.values(), data => data.model);
	}

655
	private async transformTextModelOutputs(textModel: NotebookTextModel) {
656 657 658
		for (let i = 0; i < textModel.cells.length; i++) {
			const cell = textModel.cells[i];

659
			cell.outputs.forEach((output) => {
660
				if (output.outputKind === CellOutputKind.Rich) {
661
					// TODO@rebornix no string[] casting
662
					const ret = this._transformMimeTypes(output, output.outputId, textModel.metadata.displayOrder as string[] || []);
663 664 665 666 667 668 669 670 671
					const orderedMimeTypes = ret.orderedMimeTypes!;
					const pickedMimeTypeIndex = ret.pickedMimeTypeIndex!;
					output.pickedMimeTypeIndex = pickedMimeTypeIndex;
					output.orderedMimeTypes = orderedMimeTypes;
				}
			});
		}
	}

672 673
	transformEditsOutputs(textModel: NotebookTextModel, edits: ICellEditOperation[]) {
		edits.forEach((edit) => {
674
			if (edit.editType === CellEditType.Replace) {
675
				edit.cells.forEach((cell) => {
676
					const outputs = cell.outputs;
677
					outputs.map((output) => {
678
						if (output.outputKind === CellOutputKind.Rich) {
679
							const ret = this._transformMimeTypes(output, output.outputId, textModel.metadata.displayOrder as string[] || []);
680 681 682 683 684 685 686
							const orderedMimeTypes = ret.orderedMimeTypes!;
							const pickedMimeTypeIndex = ret.pickedMimeTypeIndex!;
							output.pickedMimeTypeIndex = pickedMimeTypeIndex;
							output.orderedMimeTypes = orderedMimeTypes;
						}
					});
				});
687 688 689 690 691 692 693 694 695 696
			} else if (edit.editType === CellEditType.Output) {
				edit.outputs.map((output) => {
					if (output.outputKind === CellOutputKind.Rich) {
						const ret = this._transformMimeTypes(output, output.outputId, textModel.metadata.displayOrder as string[] || []);
						const orderedMimeTypes = ret.orderedMimeTypes!;
						const pickedMimeTypeIndex = ret.pickedMimeTypeIndex!;
						output.pickedMimeTypeIndex = pickedMimeTypeIndex;
						output.orderedMimeTypes = orderedMimeTypes;
					}
				});
697 698 699 700
			}
		});
	}

701 702
	transformSpliceOutputs(textModel: NotebookTextModel, splices: NotebookCellOutputsSplice[]) {
		splices.forEach((splice) => {
703
			const outputs = splice[2];
704
			outputs.map((output) => {
705
				if (output.outputKind === CellOutputKind.Rich) {
706
					const ret = this._transformMimeTypes(output, output.outputId, textModel.metadata.displayOrder as string[] || []);
707 708 709 710 711 712 713
					const orderedMimeTypes = ret.orderedMimeTypes!;
					const pickedMimeTypeIndex = ret.pickedMimeTypeIndex!;
					output.pickedMimeTypeIndex = pickedMimeTypeIndex;
					output.orderedMimeTypes = orderedMimeTypes;
				}
			});
		});
714 715
	}

716
	private _transformMimeTypes(output: IDisplayOutput, outputId: string, documentDisplayOrder: string[]): ITransformedDisplayOutputDto {
R
Rob Lourens 已提交
717 718
		const mimeTypes = Object.keys(output.data);
		const coreDisplayOrder = this._displayOrder;
719 720
		const sorted = sortMimeTypes(mimeTypes, coreDisplayOrder?.userOrder || [], documentDisplayOrder, coreDisplayOrder?.defaultOrder || []);

R
Rob Lourens 已提交
721
		const orderMimeTypes: IOrderedMimeType[] = [];
722 723

		sorted.forEach(mimeType => {
R
Rob Lourens 已提交
724
			const handlers = this._findBestMatchedRenderer(mimeType);
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743

			if (handlers.length) {
				const handler = handlers[0];

				orderMimeTypes.push({
					mimeType: mimeType,
					rendererId: handler.id,
				});

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

				if (mimeTypeSupportedByCore(mimeType)) {
					orderMimeTypes.push({
						mimeType: mimeType,
744
						rendererId: BUILTIN_RENDERER_ID
745 746 747 748 749
					});
				}
			} else {
				orderMimeTypes.push({
					mimeType: mimeType,
750
					rendererId: BUILTIN_RENDERER_ID
751 752 753 754 755 756
				});
			}
		});

		return {
			outputKind: output.outputKind,
757
			outputId,
758 759 760 761 762 763
			data: output.data,
			orderedMimeTypes: orderMimeTypes,
			pickedMimeTypeIndex: 0
		};
	}

764
	private _findBestMatchedRenderer(mimeType: string): readonly NotebookOutputRendererInfo[] {
765 766 767
		return this.notebookRenderersInfoStore.getContributedRenderer(mimeType);
	}

R
rebornix 已提交
768
	getContributedNotebookProviders(resource: URI): readonly NotebookProviderInfo[] {
R
rebornix 已提交
769 770
		return this.notebookProviderInfoStore.getContributedNotebook(resource);
	}
R
rebornix 已提交
771

R
rebornix 已提交
772 773 774 775
	getContributedNotebookProvider(viewType: string): NotebookProviderInfo | undefined {
		return this.notebookProviderInfoStore.get(viewType);
	}

R
rebornix 已提交
776 777
	getContributedNotebookOutputRenderers(viewType: string): NotebookOutputRendererInfo | undefined {
		return this.notebookRenderersInfoStore.get(viewType);
R
rebornix 已提交
778 779
	}

R
rebornix 已提交
780
	getNotebookProviderResourceRoots(): URI[] {
R
Rob Lourens 已提交
781
		const ret: URI[] = [];
R
rebornix 已提交
782 783 784 785 786 787
		this._notebookProviders.forEach(val => {
			ret.push(URI.revive(val.extensionData.location));
		});

		return ret;
	}
R
rebornix 已提交
788

R
rebornix 已提交
789
	removeNotebookEditor(editor: INotebookEditor) {
R
Rob Lourens 已提交
790
		const editorCache = this._notebookEditors.get(editor.getId());
791 792 793 794

		if (editorCache) {
			this._notebookEditors.delete(editor.getId());
			this._onNotebookEditorsRemove.fire([editor]);
R
rebornix 已提交
795 796 797 798
		}
	}

	addNotebookEditor(editor: INotebookEditor) {
799
		this._notebookEditors.set(editor.getId(), editor);
R
rebornix 已提交
800 801 802
		this._onNotebookEditorAdd.fire(editor);
	}

803 804 805 806
	getNotebookEditor(editorId: string) {
		return this._notebookEditors.get(editorId);
	}

R
rebornix 已提交
807
	listNotebookEditors(): INotebookEditor[] {
808 809 810 811
		return [...this._notebookEditors].map(e => e[1]);
	}

	listVisibleNotebookEditors(): INotebookEditor[] {
R
rebornix 已提交
812
		return this._editorService.visibleEditorPanes
R
rebornix 已提交
813
			.filter(pane => (pane as unknown as { isNotebookEditor?: boolean }).isNotebookEditor)
814 815 816
			.map(pane => pane.getControl() as INotebookEditor)
			.filter(editor => !!editor)
			.filter(editor => this._notebookEditors.has(editor.getId()));
R
rebornix 已提交
817 818 819
	}

	listNotebookDocuments(): NotebookTextModel[] {
820
		return [...this._models].map(e => e[1].model);
R
rebornix 已提交
821 822
	}

823
	destoryNotebookDocument(viewType: string, notebook: INotebookTextModel): void {
824
		this._onWillDisposeDocument(notebook);
R
rebornix 已提交
825 826
	}

R
rebornix 已提交
827
	updateActiveNotebookEditor(editor: INotebookEditor | null) {
R
rebornix 已提交
828 829 830 831 832 833 834 835 836 837 838
		this._activeEditorDisposables.clear();

		if (editor) {
			this._activeEditorDisposables.add(editor.onDidChangeKernel(() => {
				this._onDidChangeNotebookActiveKernel.fire({
					uri: editor.uri!,
					providerHandle: editor.activeKernel?.providerHandle,
					kernelId: editor.activeKernel?.id
				});
			}));
		}
R
rebornix 已提交
839 840 841 842
		this._onDidChangeActiveEditor.fire(editor ? editor.getId() : null);
	}

	updateVisibleNotebookEditor(editors: string[]) {
843 844
		const alreadyCreated = editors.filter(editorId => this._notebookEditors.has(editorId));
		this._onDidChangeVisibleEditors.fire(alreadyCreated);
R
rebornix 已提交
845 846
	}

R
rebornix 已提交
847
	setToCopy(items: NotebookCellTextModel[], isCopy: boolean) {
R
rebornix 已提交
848
		this.cutItems = items;
R
rebornix 已提交
849
		this._lastClipboardIsCopy = isCopy;
R
rebornix 已提交
850 851
	}

R
rebornix 已提交
852 853 854 855 856 857
	getToCopy(): { items: NotebookCellTextModel[], isCopy: boolean; } | undefined {
		if (this.cutItems) {
			return { items: this.cutItems, isCopy: this._lastClipboardIsCopy };
		}

		return undefined;
R
rebornix 已提交
858 859
	}

R
rebornix 已提交
860
	async save(viewType: string, resource: URI, token: CancellationToken): Promise<boolean> {
R
Rob Lourens 已提交
861
		const provider = this._notebookProviders.get(viewType);
862 863

		if (provider) {
864 865 866 867 868 869
			const ret = await provider.controller.save(resource, token);
			if (ret) {
				this._onNotebookDocumentSaved.fire(resource);
			}

			return ret;
870 871 872 873 874
		}

		return false;
	}

R
saveAs  
rebornix 已提交
875
	async saveAs(viewType: string, resource: URI, target: URI, token: CancellationToken): Promise<boolean> {
R
Rob Lourens 已提交
876
		const provider = this._notebookProviders.get(viewType);
R
saveAs  
rebornix 已提交
877 878

		if (provider) {
879 880 881 882 883 884
			const ret = await provider.controller.saveAs(resource, target, token);
			if (ret) {
				this._onNotebookDocumentSaved.fire(resource);
			}

			return ret;
R
saveAs  
rebornix 已提交
885 886 887 888 889
		}

		return false;
	}

890
	async backup(viewType: string, uri: URI, token: CancellationToken): Promise<string | undefined> {
R
Rob Lourens 已提交
891
		const provider = this._notebookProviders.get(viewType);
892 893 894 895 896 897 898 899

		if (provider) {
			return provider.controller.backup(uri, token);
		}

		return;
	}

900
	onDidReceiveMessage(viewType: string, editorId: string, rendererType: string | undefined, message: any): void {
R
Rob Lourens 已提交
901
		const provider = this._notebookProviders.get(viewType);
902 903

		if (provider) {
904
			return provider.controller.onDidReceiveMessage(editorId, rendererType, message);
905 906 907
		}
	}

908
	private _onWillDisposeDocument(model: INotebookTextModel): void {
R
rebornix 已提交
909

J
Johannes Rieken 已提交
910 911
		const modelData = this._models.get(model.uri);
		this._models.delete(model.uri);
912 913 914 915 916 917 918 919 920 921 922 923

		if (modelData) {
			// delete editors and documents
			const willRemovedEditors: INotebookEditor[] = [];
			this._notebookEditors.forEach(editor => {
				if (editor.textModel === modelData!.model) {
					willRemovedEditors.push(editor);
				}
			});

			willRemovedEditors.forEach(e => this._notebookEditors.delete(e.getId()));

R
Rob Lourens 已提交
924
			const provider = this._notebookProviders.get(modelData!.model.viewType);
R
rebornix 已提交
925

926
			if (provider) {
927 928
				provider.controller.removeNotebookDocument(modelData!.model.uri);
				modelData!.model.dispose();
929 930 931 932
			}


			this._onNotebookEditorsRemove.fire(willRemovedEditors.map(e => e));
933 934
			this._onDidRemoveNotebookDocument.fire(modelData.model.uri);
			modelData.dispose();
935
		}
R
rebornix 已提交
936
	}
R
rebornix 已提交
937
}