notebook.contribution.ts 12.1 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 110 111 112 113 114 115
		this.editorService.overrideOpenEditor({
			getEditorOverrides: (editor: IEditorInput, options: IEditorOptions | undefined, group: IEditorGroup | undefined) => {
				let resource = editor.resource;
				if (!resource) {
					return [];
				}

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

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

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

R
rebornix 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
	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 已提交
160
	private onEditorOpening(originalInput: IEditorInput, options: IEditorOptions | ITextEditorOptions | undefined, group: IEditorGroup, id: string | undefined): IOpenEditorOverride | undefined {
161 162 163 164
		let resource = originalInput.resource;
		if (!resource) {
			return undefined;
		}
165

R
rebornix 已提交
166
		if (id === undefined) {
R
rebornix 已提交
167 168 169 170 171 172
			const existingEditors = group.editors.filter(editor => editor.resource && isEqual(editor.resource, resource));

			if (existingEditors.length) {
				return;
			}

R
rebornix 已提交
173 174 175 176 177 178 179 180 181
			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;
			}
		}

182 183 184 185 186 187 188 189
		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 已提交
190 191
		let info: NotebookProviderInfo | undefined;
		const data = CellUri.parse(resource);
R
rebornix 已提交
192
		if (data) {
R
rebornix 已提交
193
			const infos = this.getContributedEditors(data.notebook);
R
rebornix 已提交
194 195 196 197 198

			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);
199 200 201 202 203
				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 已提交
204 205
				return { override: this.editorService.openEditor(input, new NotebookEditorOptions({ ...options, forceReload: true, cellOptions: { resource, options } }), group) };
			}
206 207
		}

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

J
Johannes Rieken 已提交
211
		if (!info) {
R
rebornix 已提交
212
			return undefined;
R
rebornix 已提交
213 214
		}

215
		const input = NotebookEditorInput.getOrCreate(this.instantiationService, resource, originalInput.getName(), info.id);
216
		this._resourceMapping.set(resource, input);
217

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

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
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 已提交
240 241 242 243
		const existing = this._modelService.getModel(resource);
		if (existing) {
			return existing;
		}
J
Johannes Rieken 已提交
244 245
		const data = CellUri.parse(resource);
		// const data = parseCellUri(resource);
246 247 248
		if (!data) {
			return null;
		}
J
Johannes Rieken 已提交
249 250 251 252 253
		const info = getFirstNotebookInfo(this._notebookService, data.notebook);
		if (!info) {
			return null;
		}
		const notebook = await this._notebookService.resolveNotebook(info.id, data.notebook);
254 255 256 257
		if (!notebook) {
			return null;
		}
		for (let cell of notebook.cells) {
258
			if (cell.uri.toString() === resource.toString()) {
259 260
				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]));
261
				return this._modelService.createModel(
R
rebornix 已提交
262
					bufferFactory,
263
					language,
264 265 266 267 268 269 270 271 272
					resource
				);
			}
		}

		return null;
	}
}

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

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

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: []
		}
	}
});