notebook.contribution.ts 12.9 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
import { assertType } from 'vs/base/common/types';
import { URI } from 'vs/base/common/uri';
12
import { ITextModel, ITextBufferFactory, DefaultEndOfLine, ITextBuffer } from 'vs/editor/common/model';
R
rebornix 已提交
13 14 15
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';
R
rebornix 已提交
27
import { NotebookEditor } from 'vs/workbench/contrib/notebook/browser/notebookEditor';
28
import { NotebookEditorInput } from 'vs/workbench/contrib/notebook/browser/notebookEditorInput';
29 30
import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
import { NotebookService } from 'vs/workbench/contrib/notebook/browser/notebookServiceImpl';
R
rebornix 已提交
31 32
import { CellKind, CellUri } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { NotebookProviderInfo } from 'vs/workbench/contrib/notebook/common/notebookProvider';
33 34
import { IEditorGroup } from 'vs/workbench/services/editor/common/editorGroupsService';
import { IEditorService, IOpenEditorOverride } from 'vs/workbench/services/editor/common/editorService';
R
rebornix 已提交
35 36 37 38
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 已提交
39

R
rebornix 已提交
40 41
// Editor Contribution

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

R
rebornix 已提交
49 50
// Output renderers registration

R
rebornix 已提交
51 52 53
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 已提交
54
import { NotebookEditorOptions } from 'vs/workbench/contrib/notebook/browser/notebookEditorWidget';
R
rebornix 已提交
55

R
rebornix 已提交
56
/*--------------------------------------------------------------------------------------------- */
P
Peng Lyu 已提交
57 58 59 60 61 62 63 64 65 66 67 68

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

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
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;
			}
93
			return NotebookEditorInput.getOrCreate(instantiationService, resource, name, viewType);
94 95 96 97
		}
	}
);

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

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

	constructor(
		@IEditorService private readonly editorService: IEditorService,
R
rebornix 已提交
107
		@INotebookService private readonly notebookService: INotebookService,
R
rebornix 已提交
108 109
		@IInstantiationService private readonly instantiationService: IInstantiationService,
		@IConfigurationService private readonly configurationService: IConfigurationService
110

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

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
					return {
						label: info.displayName,
						id: info.id,
125
						active: currentEditorForResource instanceof NotebookEditorInput && currentEditorForResource.viewType === info.id,
R
rebornix 已提交
126 127 128 129 130 131
						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
			const existingEditors = group.editors.filter(editor => editor.resource && isEqual(editor.resource, resource) && !(editor instanceof NotebookEditorInput));
R
rebornix 已提交
168 169

			if (existingEditors.length) {
R
rebornix 已提交
170
				return undefined;
R
rebornix 已提交
171 172
			}

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
		const info = getFirstNotebookInfo(this._notebookService, data.notebook);
		if (!info) {
			return null;
		}
253 254 255

		const editorModel = await this._notebookService.modelManager.get(data.notebook);
		if (!editorModel) {
256 257
			return null;
		}
258 259

		for (let cell of editorModel.notebook.cells) {
260
			if (cell.uri.toString() === resource.toString()) {
261 262 263 264 265 266 267 268 269 270 271
				const bufferFactory: ITextBufferFactory = {
					create: (defaultEOL) => {
						const newEOL = (defaultEOL === DefaultEndOfLine.CRLF ? '\r\n' : '\n');
						(cell.textBuffer as ITextBuffer).setEOL(newEOL);
						return cell.textBuffer as ITextBuffer;
					},
					getFirstLineText: (limit: number) => {
						return cell.textBuffer.getLineContent(1).substr(0, limit);
					}
				};
				const language = cell.cellKind === CellKind.Markdown ? this._modeService.create('markdown') : (cell.language ? this._modeService.create(cell.language) : this._modeService.createByFilepathOrFirstLine(resource, cell.textBuffer.getLineContent(1)));
272
				return this._modelService.createModel(
R
rebornix 已提交
273
					bufferFactory,
274
					language,
275 276 277 278 279 280 281 282 283
					resource
				);
			}
		}

		return null;
	}
}

284 285
const workbenchContributionsRegistry = Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench);
workbenchContributionsRegistry.registerWorkbenchContribution(NotebookContribution, LifecyclePhase.Starting);
286
workbenchContributionsRegistry.registerWorkbenchContribution(CellContentProvider, LifecyclePhase.Starting);
R
rebornix 已提交
287 288

registerSingleton(INotebookService, NotebookService);
R
rebornix 已提交
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306

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