notebook.contribution.ts 12.2 KB
Newer Older
P
Peng Lyu 已提交
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 7 8
import { IDisposable } from 'vs/base/common/lifecycle';
import { ResourceMap } from 'vs/base/common/map';
import { parse } from 'vs/base/common/marshalling';
R
rebornix 已提交
9
import { basename, isEqual } from 'vs/base/common/resources';
R
rebornix 已提交
10 11 12 13 14 15
import { assertType } from 'vs/base/common/types';
import { URI } from 'vs/base/common/uri';
import { ITextModel } from 'vs/editor/common/model';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { ITextModelContentProvider, ITextModelService } from 'vs/editor/common/services/resolverService';
R
rebornix 已提交
16
import * as nls from 'vs/nls';
R
rebornix 已提交
17
import { Extensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry';
18
import { IEditorOptions, ITextEditorOptions } from 'vs/platform/editor/common/editor';
P
Peng Lyu 已提交
19
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
20 21 22
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle';
P
Peng Lyu 已提交
23 24
import { Registry } from 'vs/platform/registry/common/platform';
import { EditorDescriptor, Extensions as EditorExtensions, IEditorRegistry } from 'vs/workbench/browser/editor';
25
import { Extensions as WorkbenchExtensions, IWorkbenchContribution, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions';
R
rebornix 已提交
26
import { EditorInput, Extensions as EditorInputExtensions, IEditorInput, IEditorInputFactory, IEditorInputFactoryRegistry } from 'vs/workbench/common/editor';
27
import { NotebookEditor, NotebookEditorOptions } from 'vs/workbench/contrib/notebook/browser/notebookEditor';
28
import { NotebookEditorInput } from 'vs/workbench/contrib/notebook/browser/notebookEditorInput';
R
rebornix 已提交
29
import { INotebookService, NotebookService } from 'vs/workbench/contrib/notebook/browser/notebookService';
R
rebornix 已提交
30 31
import { CellKind, CellUri } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { NotebookProviderInfo } from 'vs/workbench/contrib/notebook/common/notebookProvider';
32 33
import { IEditorGroup } from 'vs/workbench/services/editor/common/editorGroupsService';
import { IEditorService, IOpenEditorOverride } from 'vs/workbench/services/editor/common/editorService';
R
rebornix 已提交
34 35 36 37
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { CustomEditorsAssociations, customEditorsAssociationsSettingId } from 'vs/workbench/services/editor/common/editorAssociationsSetting';
import { coalesce, distinct } from 'vs/base/common/arrays';
import { CustomEditorInfo } from 'vs/workbench/contrib/customEditor/common/customEditor';
R
rebornix 已提交
38

R
rebornix 已提交
39 40
// Editor Contribution

R
rebornix 已提交
41 42
import 'vs/workbench/contrib/notebook/browser/contrib/coreActions';
import 'vs/workbench/contrib/notebook/browser/contrib/find/findController';
43 44
import 'vs/workbench/contrib/notebook/browser/contrib/fold/folding';
import 'vs/workbench/contrib/notebook/browser/contrib/format/formatting';
45
import 'vs/workbench/contrib/notebook/browser/contrib/toc/tocProvider';
R
rebornix 已提交
46

R
rebornix 已提交
47 48
// Output renderers registration

R
rebornix 已提交
49 50 51
import 'vs/workbench/contrib/notebook/browser/view/output/transforms/streamTransform';
import 'vs/workbench/contrib/notebook/browser/view/output/transforms/errorTransform';
import 'vs/workbench/contrib/notebook/browser/view/output/transforms/richTransform';
R
rebornix 已提交
52

R
rebornix 已提交
53
/*--------------------------------------------------------------------------------------------- */
P
Peng Lyu 已提交
54 55 56 57 58 59 60 61 62 63 64 65

Registry.as<IEditorRegistry>(EditorExtensions.Editors).registerEditor(
	EditorDescriptor.create(
		NotebookEditor,
		NotebookEditor.ID,
		'Notebook Editor'
	),
	[
		new SyncDescriptor(NotebookEditorInput)
	]
);

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
Registry.as<IEditorInputFactoryRegistry>(EditorInputExtensions.EditorInputFactories).registerEditorInputFactory(
	NotebookEditorInput.ID,
	class implements IEditorInputFactory {
		canSerialize(): boolean {
			return true;
		}
		serialize(input: EditorInput): string {
			assertType(input instanceof NotebookEditorInput);
			return JSON.stringify({
				resource: input.resource,
				name: input.name,
				viewType: input.viewType,
			});
		}
		deserialize(instantiationService: IInstantiationService, raw: string) {
			type Data = { resource: URI, name: string, viewType: string };
			const data = <Data>parse(raw);
			if (!data) {
				return undefined;
			}
			const { resource, name, viewType } = data;
			if (!data || !URI.isUri(resource) || typeof name !== 'string' || typeof viewType !== 'string') {
				return undefined;
			}
90
			return NotebookEditorInput.getOrCreate(instantiationService, resource, name, viewType);
91 92 93 94
		}
	}
);

J
Johannes Rieken 已提交
95 96 97 98
function getFirstNotebookInfo(notebookService: INotebookService, uri: URI): NotebookProviderInfo | undefined {
	return notebookService.getContributedNotebookProviders(uri)[0];
}

99
export class NotebookContribution implements IWorkbenchContribution {
100
	private _resourceMapping = new ResourceMap<NotebookEditorInput>();
P
Peng Lyu 已提交
101 102 103

	constructor(
		@IEditorService private readonly editorService: IEditorService,
R
rebornix 已提交
104
		@INotebookService private readonly notebookService: INotebookService,
R
rebornix 已提交
105 106
		@IInstantiationService private readonly instantiationService: IInstantiationService,
		@IConfigurationService private readonly configurationService: IConfigurationService
107

P
Peng Lyu 已提交
108
	) {
R
rebornix 已提交
109
		this.editorService.overrideOpenEditor({
110 111
			getEditorOverrides: (resource: URI, options: IEditorOptions | undefined, group: IEditorGroup | undefined) => {
				const currentEditorForResource = group?.editors.find(editor => isEqual(editor.resource, resource));
R
rebornix 已提交
112

R
rebornix 已提交
113 114 115 116
				const associatedEditors = distinct([
					...this.getUserAssociatedNotebookEditors(resource),
					...this.getContributedEditors(resource)
				], editor => editor.id);
R
rebornix 已提交
117

R
rebornix 已提交
118
				return associatedEditors.map(info => {
R
rebornix 已提交
119 120 121
					return {
						label: info.displayName,
						id: info.id,
122
						active: currentEditorForResource instanceof NotebookEditorInput && currentEditorForResource.viewType === info.id,
R
rebornix 已提交
123 124 125 126 127 128
						detail: info.providerDisplayName
					};
				});
			},
			open: (editor, options, group, id) => this.onEditorOpening(editor, options, group, id)
		});
R
rebornix 已提交
129

R
rebornix 已提交
130 131 132
		this.editorService.onDidActiveEditorChange(() => {
			if (this.editorService.activeEditor && this.editorService.activeEditor! instanceof NotebookEditorInput) {
				let editorInput = this.editorService.activeEditor! as NotebookEditorInput;
J
Johannes Rieken 已提交
133
				this.notebookService.updateActiveNotebookDocument(editorInput.viewType!, editorInput.resource!);
R
rebornix 已提交
134 135
			}
		});
P
Peng Lyu 已提交
136 137
	}

R
rebornix 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
	getUserAssociatedEditors(resource: URI) {
		const rawAssociations = this.configurationService.getValue<CustomEditorsAssociations>(customEditorsAssociationsSettingId) || [];

		return coalesce(rawAssociations
			.filter(association => CustomEditorInfo.selectorMatches(association, resource)));
	}

	getUserAssociatedNotebookEditors(resource: URI) {
		const rawAssociations = this.configurationService.getValue<CustomEditorsAssociations>(customEditorsAssociationsSettingId) || [];

		return coalesce(rawAssociations
			.filter(association => CustomEditorInfo.selectorMatches(association, resource))
			.map(association => this.notebookService.getContributedNotebookProvider(association.viewType)));
	}

	getContributedEditors(resource: URI) {
		return this.notebookService.getContributedNotebookProviders(resource);
	}

R
rebornix 已提交
157
	private onEditorOpening(originalInput: IEditorInput, options: IEditorOptions | ITextEditorOptions | undefined, group: IEditorGroup, id: string | undefined): IOpenEditorOverride | undefined {
158 159 160 161
		let resource = originalInput.resource;
		if (!resource) {
			return undefined;
		}
162

R
rebornix 已提交
163
		if (id === undefined) {
R
rebornix 已提交
164
			const existingEditors = group.editors.filter(editor => editor.resource && isEqual(editor.resource, resource) && !(editor instanceof NotebookEditorInput));
R
rebornix 已提交
165 166

			if (existingEditors.length) {
R
rebornix 已提交
167
				return undefined;
R
rebornix 已提交
168 169
			}

R
rebornix 已提交
170 171 172 173 174 175 176 177 178
			const userAssociatedEditors = this.getUserAssociatedEditors(resource);
			const notebookEditor = userAssociatedEditors.filter(association => this.notebookService.getContributedNotebookProvider(association.viewType));

			if (userAssociatedEditors.length && !notebookEditor.length) {
				// user pick a non-notebook editor for this resource
				return undefined;
			}
		}

179 180 181 182 183 184 185 186
		if (this._resourceMapping.has(resource)) {
			const input = this._resourceMapping.get(resource);

			if (!input!.isDisposed()) {
				return { override: this.editorService.openEditor(input!, new NotebookEditorOptions(options || {}).with({ ignoreOverrides: true }), group) };
			}
		}

J
Johannes Rieken 已提交
187 188
		let info: NotebookProviderInfo | undefined;
		const data = CellUri.parse(resource);
R
rebornix 已提交
189
		if (data) {
R
rebornix 已提交
190
			const infos = this.getContributedEditors(data.notebook);
R
rebornix 已提交
191 192 193 194 195

			if (infos.length) {
				const info = id === undefined ? infos[0] : (infos.find(info => info.id === id) || infos[0]);
				// cell-uri -> open (container) notebook
				const name = basename(data.notebook);
196 197 198 199 200
				let input = this._resourceMapping.get(data.notebook);
				if (!input || input.isDisposed()) {
					input = NotebookEditorInput.getOrCreate(this.instantiationService, data.notebook, name, info.id);
					this._resourceMapping.set(data.notebook, input);
				}
R
rebornix 已提交
201 202
				return { override: this.editorService.openEditor(input, new NotebookEditorOptions({ ...options, forceReload: true, cellOptions: { resource, options } }), group) };
			}
203 204
		}

R
rebornix 已提交
205 206 207
		const infos = this.notebookService.getContributedNotebookProviders(resource);
		info = id === undefined ? infos[0] : infos.find(info => info.id === id);

J
Johannes Rieken 已提交
208
		if (!info) {
R
rebornix 已提交
209
			return undefined;
R
rebornix 已提交
210 211
		}

212
		const input = NotebookEditorInput.getOrCreate(this.instantiationService, resource, originalInput.getName(), info.id);
213
		this._resourceMapping.set(resource, input);
214

R
rebornix 已提交
215
		return { override: this.editorService.openEditor(input, options, group) };
P
Peng Lyu 已提交
216 217 218
	}
}

219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
class CellContentProvider implements ITextModelContentProvider {

	private readonly _registration: IDisposable;

	constructor(
		@ITextModelService textModelService: ITextModelService,
		@IModelService private readonly _modelService: IModelService,
		@IModeService private readonly _modeService: IModeService,
		@INotebookService private readonly _notebookService: INotebookService,
	) {
		this._registration = textModelService.registerTextModelContentProvider('vscode-notebook', this);
	}

	dispose(): void {
		this._registration.dispose();
	}

	async provideTextContent(resource: URI): Promise<ITextModel | null> {
J
Johannes Rieken 已提交
237 238 239 240
		const existing = this._modelService.getModel(resource);
		if (existing) {
			return existing;
		}
J
Johannes Rieken 已提交
241 242
		const data = CellUri.parse(resource);
		// const data = parseCellUri(resource);
243 244 245
		if (!data) {
			return null;
		}
J
Johannes Rieken 已提交
246 247 248 249 250
		const info = getFirstNotebookInfo(this._notebookService, data.notebook);
		if (!info) {
			return null;
		}
		const notebook = await this._notebookService.resolveNotebook(info.id, data.notebook);
251 252 253 254
		if (!notebook) {
			return null;
		}
		for (let cell of notebook.cells) {
255
			if (cell.uri.toString() === resource.toString()) {
256 257
				const bufferFactory = cell.resolveTextBufferFactory();
				const language = cell.cellKind === CellKind.Markdown ? this._modeService.create('markdown') : (cell.language ? this._modeService.create(cell.language) : this._modeService.createByFilepathOrFirstLine(resource, cell.source[0]));
258
				return this._modelService.createModel(
R
rebornix 已提交
259
					bufferFactory,
260
					language,
261 262 263 264 265 266 267 268 269
					resource
				);
			}
		}

		return null;
	}
}

270 271
const workbenchContributionsRegistry = Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench);
workbenchContributionsRegistry.registerWorkbenchContribution(NotebookContribution, LifecyclePhase.Starting);
272
workbenchContributionsRegistry.registerWorkbenchContribution(CellContentProvider, LifecyclePhase.Starting);
R
rebornix 已提交
273 274

registerSingleton(INotebookService, NotebookService);
R
rebornix 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292

const configurationRegistry = Registry.as<IConfigurationRegistry>(Extensions.Configuration);
configurationRegistry.registerConfiguration({
	id: 'notebook',
	order: 100,
	title: nls.localize('notebookConfigurationTitle', "Notebook"),
	type: 'object',
	properties: {
		'notebook.displayOrder': {
			markdownDescription: nls.localize('notebook.displayOrder.description', "Priority list for output mime types"),
			type: ['array'],
			items: {
				type: 'string'
			},
			default: []
		}
	}
});