mainThreadWebview.ts 17.4 KB
Newer Older
A
Alex Dima 已提交
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 { onUnexpectedError } from 'vs/base/common/errors';
7
import { Disposable, IDisposable, DisposableStore } from 'vs/base/common/lifecycle';
8
import { Schemas } from 'vs/base/common/network';
9
import { isWeb } from 'vs/base/common/platform';
10
import { startsWith } from 'vs/base/common/strings';
11
import { URI, UriComponents } from 'vs/base/common/uri';
A
Alex Dima 已提交
12
import * as modes from 'vs/editor/common/modes';
13
import { localize } from 'vs/nls';
A
Alex Dima 已提交
14
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
15
import { IOpenerService } from 'vs/platform/opener/common/opener';
16
import { IProductService } from 'vs/platform/product/common/productService';
17
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
18
import * as extHostProtocol from 'vs/workbench/api/common/extHost.protocol';
19
import { editorGroupToViewColumn, EditorViewColumn, viewColumnToEditorGroup } from 'vs/workbench/api/common/shared/editor';
20 21
import { IEditorInput } from 'vs/workbench/common/editor';
import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';
22
import { CustomFileEditorInput } from 'vs/workbench/contrib/customEditor/browser/customEditorInput';
23
import { ICustomEditorService } from 'vs/workbench/contrib/customEditor/common/customEditor';
24
import { WebviewExtensionDescription } from 'vs/workbench/contrib/webview/browser/webview';
25
import { WebviewInput } from 'vs/workbench/contrib/webview/browser/webviewEditorInput';
26
import { ICreateWebViewShowOptions, IWebviewWorkbenchService, WebviewInputOptions } from 'vs/workbench/contrib/webview/browser/webviewWorkbenchService';
27
import { IEditorGroup, IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
28
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
29
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
A
Alex Dima 已提交
30 31
import { extHostNamedCustomer } from '../common/extHostCustomers';

32 33 34
/**
 * Bi-directional map between webview handles and inputs.
 */
35
class WebviewInputStore {
36 37
	private readonly _handlesToInputs = new Map<string, WebviewInput>();
	private readonly _inputsToHandles = new Map<WebviewInput, string>();
38

39
	public add(handle: string, input: WebviewInput): void {
40 41 42 43
		this._handlesToInputs.set(handle, input);
		this._inputsToHandles.set(input, handle);
	}

44
	public getHandleForInput(input: WebviewInput): string | undefined {
45 46 47
		return this._inputsToHandles.get(input);
	}

48
	public getInputForHandle(handle: string): WebviewInput | undefined {
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
		return this._handlesToInputs.get(handle);
	}

	public delete(handle: string): void {
		const input = this.getInputForHandle(handle);
		this._handlesToInputs.delete(handle);
		if (input) {
			this._inputsToHandles.delete(input);
		}
	}

	public get size(): number {
		return this._handlesToInputs.size;
	}
}

M
Matt Bierner 已提交
65 66 67 68
class WebviewViewTypeTransformer {
	public constructor(
		public readonly prefix: string,
	) { }
M
Matt Bierner 已提交
69

M
Matt Bierner 已提交
70 71
	public fromExternal(viewType: string): string {
		return this.prefix + viewType;
M
Matt Bierner 已提交
72 73
	}

M
Matt Bierner 已提交
74 75 76
	public toExternal(viewType: string): string | undefined {
		return startsWith(viewType, this.prefix)
			? viewType.substr(this.prefix.length)
M
Matt Bierner 已提交
77 78 79 80
			: undefined;
	}
}

M
Matt Bierner 已提交
81 82
const webviewPanelViewType = new WebviewViewTypeTransformer('mainThreadWebview-');

83 84
@extHostNamedCustomer(extHostProtocol.MainContext.MainThreadWebviews)
export class MainThreadWebviews extends Disposable implements extHostProtocol.MainThreadWebviewsShape {
85 86

	private static readonly standardSupportedLinkSchemes = new Set([
M
Matt Bierner 已提交
87 88 89 90
		Schemas.http,
		Schemas.https,
		Schemas.mailto,
		Schemas.vscode,
91 92 93
		'vscode-insider',
	]);

94
	private readonly _proxy: extHostProtocol.ExtHostWebviewsShape;
95
	private readonly _webviewInputs = new WebviewInputStore();
96
	private readonly _revivers = new Map<string, IDisposable>();
97
	private readonly _editorProviders = new Map<string, IDisposable>();
98 99

	constructor(
100
		context: extHostProtocol.IExtHostContext,
101
		@IExtensionService extensionService: IExtensionService,
102
		@ICustomEditorService private readonly _customEditorService: ICustomEditorService,
103 104 105 106
		@IEditorGroupsService private readonly _editorGroupService: IEditorGroupsService,
		@IEditorService private readonly _editorService: IEditorService,
		@IOpenerService private readonly _openerService: IOpenerService,
		@IProductService private readonly _productService: IProductService,
107 108
		@ITelemetryService private readonly _telemetryService: ITelemetryService,
		@IWebviewWorkbenchService private readonly _webviewWorkbenchService: IWebviewWorkbenchService,
109 110 111
	) {
		super();

112
		this._proxy = context.getProxy(extHostProtocol.ExtHostContext.ExtHostWebviews);
113 114
		this._register(_editorService.onDidActiveEditorChange(this.updateWebviewViewStates, this));
		this._register(_editorService.onDidVisibleEditorsChange(this.updateWebviewViewStates, this));
115

116
		// This reviver's only job is to activate webview panel extensions
117
		// This should trigger the real reviver to be registered from the extension host side.
118
		this._register(_webviewWorkbenchService.registerResolver({
119
			canResolve: (webview: WebviewInput) => {
M
Matt Bierner 已提交
120 121
				if (webview instanceof CustomFileEditorInput) {
					extensionService.activateByEvent(`onWebviewEditor:${webview.viewType}`);
M
Matt Bierner 已提交
122 123 124
					return false;
				}

M
Matt Bierner 已提交
125
				const viewType = webviewPanelViewType.toExternal(webview.viewType);
M
Matt Bierner 已提交
126
				if (typeof viewType === 'string') {
127 128 129 130
					extensionService.activateByEvent(`onWebviewPanel:${viewType}`);
				}
				return false;
			},
131
			resolveWebview: () => { throw new Error('not implemented'); }
132 133 134 135
		}));
	}

	public $createWebviewPanel(
136 137
		extensionData: extHostProtocol.WebviewExtensionDescription,
		handle: extHostProtocol.WebviewPanelHandle,
138 139
		viewType: string,
		title: string,
M
Matt Bierner 已提交
140
		showOptions: { viewColumn?: EditorViewColumn, preserveFocus?: boolean; },
141
		options: WebviewInputOptions
142 143 144 145 146 147 148
	): void {
		const mainThreadShowOptions: ICreateWebViewShowOptions = Object.create(null);
		if (showOptions) {
			mainThreadShowOptions.preserveFocus = !!showOptions.preserveFocus;
			mainThreadShowOptions.group = viewColumnToEditorGroup(this._editorGroupService, showOptions.viewColumn);
		}

149
		const extension = reviveWebviewExtension(extensionData);
150
		const webview = this._webviewWorkbenchService.createWebview(handle, webviewPanelViewType.fromExternal(viewType), title, mainThreadShowOptions, reviveWebviewOptions(options), extension);
151
		this.hookupWebviewEventDelegate(handle, webview);
152

153
		this._webviewInputs.add(handle, webview);
154 155 156 157 158 159

		/* __GDPR__
			"webviews:createWebviewPanel" : {
				"extensionId" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
			}
		*/
160
		this._telemetryService.publicLog('webviews:createWebviewPanel', { extensionId: extension.id.value });
161 162
	}

163
	public $disposeWebview(handle: extHostProtocol.WebviewPanelHandle): void {
164
		const webview = this.getWebviewInput(handle);
165 166 167
		webview.dispose();
	}

168
	public $setTitle(handle: extHostProtocol.WebviewPanelHandle, value: string): void {
169
		const webview = this.getWebviewInput(handle);
170 171 172
		webview.setName(value);
	}

173
	public $setIconPath(handle: extHostProtocol.WebviewPanelHandle, value: { light: UriComponents, dark: UriComponents; } | undefined): void {
174
		const webview = this.getWebviewInput(handle);
175 176 177
		webview.iconPath = reviveWebviewIcon(value);
	}

178
	public $setHtml(handle: extHostProtocol.WebviewPanelHandle, value: string): void {
179
		const webview = this.getWebviewInput(handle);
180
		webview.webview.html = value;
181 182
	}

183
	public $setOptions(handle: extHostProtocol.WebviewPanelHandle, options: modes.IWebviewOptions): void {
184
		const webview = this.getWebviewInput(handle);
M
Matt Bierner 已提交
185
		webview.webview.contentOptions = reviveWebviewOptions(options);
186 187
	}

188
	public $reveal(handle: extHostProtocol.WebviewPanelHandle, showOptions: extHostProtocol.WebviewPanelShowOptions): void {
189
		const webview = this.getWebviewInput(handle);
190 191 192 193 194 195
		if (webview.isDisposed()) {
			return;
		}

		const targetGroup = this._editorGroupService.getGroup(viewColumnToEditorGroup(this._editorGroupService, showOptions.viewColumn)) || this._editorGroupService.getGroup(webview.group || 0);
		if (targetGroup) {
196
			this._webviewWorkbenchService.revealWebview(webview, targetGroup, !!showOptions.preserveFocus);
197 198 199
		}
	}

200
	public async $postMessage(handle: extHostProtocol.WebviewPanelHandle, message: any): Promise<boolean> {
201
		const webview = this.getWebviewInput(handle);
202
		webview.webview.sendMessage(message);
203
		return true;
A
Alex Dima 已提交
204
	}
205 206 207 208 209 210

	public $registerSerializer(viewType: string): void {
		if (this._revivers.has(viewType)) {
			throw new Error(`Reviver for ${viewType} already registered`);
		}

211
		this._revivers.set(viewType, this._webviewWorkbenchService.registerResolver({
212 213
			canResolve: (webviewInput) => {
				return webviewInput.viewType === webviewPanelViewType.fromExternal(viewType);
214
			},
215 216
			resolveWebview: async (webviewInput): Promise<void> => {
				const viewType = webviewPanelViewType.toExternal(webviewInput.viewType);
M
Matt Bierner 已提交
217
				if (!viewType) {
218
					webviewInput.webview.html = MainThreadWebviews.getDeserializationFailedContents(webviewInput.viewType);
M
Matt Bierner 已提交
219 220 221
					return;
				}

222 223 224
				const handle = webviewInput.id;
				this._webviewInputs.add(handle, webviewInput);
				this.hookupWebviewEventDelegate(handle, webviewInput);
225

226
				let state = undefined;
227
				if (webviewInput.webview.state) {
228
					try {
229
						state = JSON.parse(webviewInput.webview.state);
230 231 232 233 234 235
					} catch {
						// noop
					}
				}

				try {
236
					await this._proxy.$deserializeWebviewPanel(handle, viewType, webviewInput.getTitle(), state, editorGroupToViewColumn(this._editorGroupService, webviewInput.group || 0), webviewInput.webview.options);
237 238
				} catch (error) {
					onUnexpectedError(error);
239
					webviewInput.webview.html = MainThreadWebviews.getDeserializationFailedContents(viewType);
240 241 242
				}
			}
		}));
A
Alex Dima 已提交
243
	}
244 245 246 247 248 249 250 251 252

	public $unregisterSerializer(viewType: string): void {
		const reviver = this._revivers.get(viewType);
		if (!reviver) {
			throw new Error(`No reviver for ${viewType} registered`);
		}

		reviver.dispose();
		this._revivers.delete(viewType);
A
Alex Dima 已提交
253
	}
254

255
	public $registerEditorProvider(extensionData: extHostProtocol.WebviewExtensionDescription, viewType: string, options: modes.IWebviewPanelOptions): void {
256 257 258 259
		if (this._editorProviders.has(viewType)) {
			throw new Error(`Provider for ${viewType} already registered`);
		}

260
		const extension = reviveWebviewExtension(extensionData);
M
Matt Bierner 已提交
261

262
		this._editorProviders.set(viewType, this._webviewWorkbenchService.registerResolver({
263
			canResolve: (webviewInput) => {
M
Matt Bierner 已提交
264
				return webviewInput instanceof CustomFileEditorInput && webviewInput.viewType === viewType;
265
			},
266
			resolveWebview: async (webviewInput: CustomFileEditorInput) => {
267 268 269
				const handle = webviewInput.id;
				this._webviewInputs.add(handle, webviewInput);
				this.hookupWebviewEventDelegate(handle, webviewInput);
270

271
				webviewInput.webview.options = options;
272
				webviewInput.webview.extension = extension;
M
Matt Bierner 已提交
273

274
				const model = await this.getModel(webviewInput);
275
				webviewInput.onDisposeWebview(() => {
276 277 278
					this._customEditorService.models.disposeModel(model);
				});

279 280
				try {
					await this._proxy.$resolveWebviewEditor(
M
Matt Bierner 已提交
281
						{ resource: webviewInput.getResource(), edits: model.currentEdits },
282 283
						handle,
						viewType,
284 285 286
						webviewInput.getTitle(),
						editorGroupToViewColumn(this._editorGroupService, webviewInput.group || 0),
						webviewInput.webview.options
287 288 289
					);
				} catch (error) {
					onUnexpectedError(error);
290
					webviewInput.webview.html = MainThreadWebviews.getDeserializationFailedContents(viewType);
M
Matt Bierner 已提交
291
					return;
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
				}
			}
		}));
	}

	public $unregisterEditorProvider(viewType: string): void {
		const provider = this._editorProviders.get(viewType);
		if (!provider) {
			throw new Error(`No provider for ${viewType} registered`);
		}

		provider.dispose();
		this._editorProviders.delete(viewType);
	}

307 308
	public async $registerCapabilities(handle: extHostProtocol.WebviewPanelHandle, capabilities: readonly extHostProtocol.WebviewEditorCapabilities[]): Promise<void> {
		const webviewInput = this.getWebviewInput(handle);
309
		const model = await this.getModel(webviewInput);
310 311

		const capabilitiesSet = new Set(capabilities);
M
Matt Bierner 已提交
312
		if (capabilitiesSet.has(extHostProtocol.WebviewEditorCapabilities.Editable)) {
313 314 315 316 317 318 319 320 321
			model.onUndo(edits => { this._proxy.$undoEdits(handle, edits.map(x => x.data)); });

			model.onApplyEdit(edits => {
				const editsToApply = edits.filter(x => x.source !== webviewInput).map(x => x.data);
				if (editsToApply.length) {
					this._proxy.$applyEdits(handle, editsToApply);
				}
			});

322
			model.onWillSave(e => { e.waitUntil(this._proxy.$onSave(handle)); });
323

324 325 326 327
			model.onWillSaveAs(e => { e.waitUntil(this._proxy.$onSaveAs(handle, e.resource.toJSON(), e.targetResource.toJSON())); });
		}
	}

328 329 330 331
	private getModel(webviewInput: WebviewInput) {
		return this._customEditorService.models.loadOrCreate(webviewInput.getResource(), webviewInput.viewType);
	}

332
	public $onEdit(handle: extHostProtocol.WebviewPanelHandle, editData: any): void {
333 334
		const webview = this.getWebviewInput(handle);
		if (!(webview instanceof CustomFileEditorInput)) {
335
			throw new Error('Webview is not a webview editor');
336
		}
337

338
		const model = this._customEditorService.models.get(webview.getResource(), webview.viewType);
339 340 341 342
		if (!model) {
			throw new Error('Could not find model for webview editor');
		}

343
		model.makeEdit({ source: webview, data: editData });
344 345
	}

346
	private hookupWebviewEventDelegate(handle: extHostProtocol.WebviewPanelHandle, input: WebviewInput) {
347 348
		const disposables = new DisposableStore();

349
		disposables.add(input.webview.onDidClickLink((uri) => this.onDidClickLink(handle, uri)));
350 351 352 353 354
		disposables.add(input.webview.onMessage((message: any) => { this._proxy.$onMessage(handle, message); }));
		disposables.add(input.webview.onMissingCsp((extension: ExtensionIdentifier) => this._proxy.$onMissingCsp(handle, extension.value)));

		input.onDispose(() => {
			disposables.dispose();
355
		});
356 357 358 359 360
		input.onDisposeWebview(() => {
			this._proxy.$onDidDisposeWebviewPanel(handle).finally(() => {
				this._webviewInputs.delete(handle);
			});
		});
A
Alex Dima 已提交
361
	}
362

363
	private updateWebviewViewStates() {
364
		if (!this._webviewInputs.size) {
365 366
			return;
		}
367

368
		const activeInput = this._editorService.activeControl && this._editorService.activeControl.input;
369
		const viewStates: extHostProtocol.WebviewPanelViewStateData = {};
370

371 372 373 374 375 376 377
		const updateViewStatesForInput = (group: IEditorGroup, topLevelInput: IEditorInput, editorInput: IEditorInput) => {
			if (!(editorInput instanceof WebviewInput)) {
				return;
			}

			editorInput.updateGroup(group.id);

378
			const handle = this._webviewInputs.getHandleForInput(editorInput);
379 380
			if (handle) {
				viewStates[handle] = {
381 382
					visible: topLevelInput === group.activeEditor,
					active: topLevelInput === activeInput,
383 384 385 386
					position: editorGroupToViewColumn(this._editorGroupService, group.id),
				};
			}
		};
387

388 389 390 391 392 393 394
		for (const group of this._editorGroupService.groups) {
			for (const input of group.editors) {
				if (input instanceof DiffEditorInput) {
					updateViewStatesForInput(group, input, input.master);
					updateViewStatesForInput(group, input, input.details);
				} else {
					updateViewStatesForInput(group, input, input);
395 396
				}
			}
397
		}
398 399 400 401

		if (Object.keys(viewStates).length) {
			this._proxy.$onDidChangeWebviewPanelViewStates(viewStates);
		}
402 403
	}

404
	private onDidClickLink(handle: extHostProtocol.WebviewPanelHandle, link: string): void {
405
		const webview = this.getWebviewInput(handle);
406
		if (this.isSupportedLink(webview, URI.parse(link))) {
407
			this._openerService.open(link, { fromUserGesture: true });
408 409 410
		}
	}

411
	private isSupportedLink(webview: WebviewInput, link: URI): boolean {
412 413 414
		if (MainThreadWebviews.standardSupportedLinkSchemes.has(link.scheme)) {
			return true;
		}
415
		if (!isWeb && this._productService.urlProtocol === link.scheme) {
416 417
			return true;
		}
M
Matt Bierner 已提交
418
		return !!webview.webview.contentOptions.enableCommandUris && link.scheme === Schemas.command;
A
Alex Dima 已提交
419
	}
420

421
	private getWebviewInput(handle: extHostProtocol.WebviewPanelHandle): WebviewInput {
422
		const webview = this.tryGetWebviewInput(handle);
423 424 425 426 427 428
		if (!webview) {
			throw new Error('Unknown webview handle:' + handle);
		}
		return webview;
	}

429
	private tryGetWebviewInput(handle: extHostProtocol.WebviewPanelHandle): WebviewInput | undefined {
430
		return this._webviewInputs.getInputForHandle(handle);
431 432
	}

433 434 435 436 437
	private static getDeserializationFailedContents(viewType: string) {
		return `<!DOCTYPE html>
		<html>
			<head>
				<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
438
				<meta http-equiv="Content-Security-Policy" content="default-src 'none';">
439 440 441
			</head>
			<body>${localize('errorMessage', "An error occurred while restoring view:{0}", viewType)}</body>
		</html>`;
A
Alex Dima 已提交
442
	}
443 444
}

445 446
function reviveWebviewExtension(extensionData: extHostProtocol.WebviewExtensionDescription): WebviewExtensionDescription {
	return { id: extensionData.id, location: URI.revive(extensionData.location) };
M
Matt Bierner 已提交
447 448
}

449
function reviveWebviewOptions(options: modes.IWebviewOptions): WebviewInputOptions {
450 451
	return {
		...options,
452
		allowScripts: options.enableScripts,
453 454 455 456 457
		localResourceRoots: Array.isArray(options.localResourceRoots) ? options.localResourceRoots.map(r => URI.revive(r)) : undefined,
	};
}

function reviveWebviewIcon(
M
Matt Bierner 已提交
458 459
	value: { light: UriComponents, dark: UriComponents; } | undefined
): { light: URI, dark: URI; } | undefined {
460 461
	if (!value) {
		return undefined;
A
Alex Dima 已提交
462
	}
463 464 465 466 467

	return {
		light: URI.revive(value.light),
		dark: URI.revive(value.dark)
	};
A
Alex Dima 已提交
468
}