mainThreadWebview.ts 17.9 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, DisposableStore, IDisposable } 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 { ICustomEditorModel, 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
	private readonly _customEditorModels = new Map<ICustomEditorModel, { referenceCount: number }>();
99 100

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	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 已提交
254
	}
255

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

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

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

272
				webviewInput.webview.options = options;
273
				webviewInput.webview.extension = extension;
274
				const resource = webviewInput.getResource();
M
Matt Bierner 已提交
275

276
				const model = await this.retainCustomEditorModel(webviewInput, resource, viewType, capabilities);
277
				webviewInput.onDisposeWebview(() => {
278
					this.releaseCustomEditorModel(model);
279 280
				});

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

	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);
	}

309 310 311 312 313 314 315 316
	private async retainCustomEditorModel(webviewInput: WebviewInput, resource: URI, viewType: string, capabilities: readonly extHostProtocol.WebviewEditorCapabilities[]) {
		const model = await this._customEditorService.models.loadOrCreate(webviewInput.getResource(), webviewInput.viewType);

		const existingEntry = this._customEditorModels.get(model);
		if (existingEntry) {
			++existingEntry.referenceCount;
			// no need to hook up listeners again
			return model;
317 318
		}

319
		this._customEditorModels.set(model, { referenceCount: 1 });
320 321

		const capabilitiesSet = new Set(capabilities);
M
Matt Bierner 已提交
322
		if (capabilitiesSet.has(extHostProtocol.WebviewEditorCapabilities.Editable)) {
323
			model.onUndo(edits => {
324 325
				this._proxy.$undoEdits(resource, viewType, edits.map(x => x.data));
			});
326

327 328
			model.onApplyEdit(edits => {
				const editsToApply = edits.filter(x => x.source !== model).map(x => x.data);
329
				if (editsToApply.length) {
330
					this._proxy.$applyEdits(resource, viewType, editsToApply);
331 332 333
				}
			});

334
			model.onWillSave(e => {
335 336
				e.waitUntil(this._proxy.$onSave(resource.toJSON(), viewType));
			});
337

338
			model.onWillSaveAs(e => {
339 340
				e.waitUntil(this._proxy.$onSaveAs(e.resource.toJSON(), viewType, e.targetResource.toJSON()));
			});
341
		}
342 343 344 345 346 347 348 349 350 351 352 353 354 355
		return model;
	}

	private async releaseCustomEditorModel(model: ICustomEditorModel) {
		const entry = this._customEditorModels.get(model);
		if (!entry) {
			return;
		}

		--entry.referenceCount;
		if (entry.referenceCount <= 0) {
			this._customEditorService.models.disposeModel(model);
			this._customEditorModels.delete(model);
		}
356 357
	}

358 359
	public $onEdit(resource: UriComponents, viewType: string, editData: any): void {
		const model = this._customEditorService.models.get(URI.revive(resource), viewType);
360 361 362 363
		if (!model) {
			throw new Error('Could not find model for webview editor');
		}

364
		model.pushEdit({ source: model, data: editData });
365 366
	}

367
	private hookupWebviewEventDelegate(handle: extHostProtocol.WebviewPanelHandle, input: WebviewInput) {
368 369
		const disposables = new DisposableStore();

370
		disposables.add(input.webview.onDidClickLink((uri) => this.onDidClickLink(handle, uri)));
371 372 373 374 375
		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();
376
		});
377 378 379 380 381
		input.onDisposeWebview(() => {
			this._proxy.$onDidDisposeWebviewPanel(handle).finally(() => {
				this._webviewInputs.delete(handle);
			});
		});
A
Alex Dima 已提交
382
	}
383

384
	private updateWebviewViewStates() {
385
		if (!this._webviewInputs.size) {
386 387
			return;
		}
388

389
		const activeInput = this._editorService.activeControl && this._editorService.activeControl.input;
390
		const viewStates: extHostProtocol.WebviewPanelViewStateData = {};
391

392 393 394 395 396 397 398
		const updateViewStatesForInput = (group: IEditorGroup, topLevelInput: IEditorInput, editorInput: IEditorInput) => {
			if (!(editorInput instanceof WebviewInput)) {
				return;
			}

			editorInput.updateGroup(group.id);

399
			const handle = this._webviewInputs.getHandleForInput(editorInput);
400 401
			if (handle) {
				viewStates[handle] = {
402 403
					visible: topLevelInput === group.activeEditor,
					active: topLevelInput === activeInput,
404 405 406 407
					position: editorGroupToViewColumn(this._editorGroupService, group.id),
				};
			}
		};
408

409 410 411 412 413 414 415
		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);
416 417
				}
			}
418
		}
419 420 421 422

		if (Object.keys(viewStates).length) {
			this._proxy.$onDidChangeWebviewPanelViewStates(viewStates);
		}
423 424
	}

425
	private onDidClickLink(handle: extHostProtocol.WebviewPanelHandle, link: string): void {
426
		const webview = this.getWebviewInput(handle);
427
		if (this.isSupportedLink(webview, URI.parse(link))) {
428
			this._openerService.open(link, { fromUserGesture: true });
429 430 431
		}
	}

432
	private isSupportedLink(webview: WebviewInput, link: URI): boolean {
433 434 435
		if (MainThreadWebviews.standardSupportedLinkSchemes.has(link.scheme)) {
			return true;
		}
436
		if (!isWeb && this._productService.urlProtocol === link.scheme) {
437 438
			return true;
		}
M
Matt Bierner 已提交
439
		return !!webview.webview.contentOptions.enableCommandUris && link.scheme === Schemas.command;
A
Alex Dima 已提交
440
	}
441

442
	private getWebviewInput(handle: extHostProtocol.WebviewPanelHandle): WebviewInput {
443
		const webview = this.tryGetWebviewInput(handle);
444 445 446 447 448 449
		if (!webview) {
			throw new Error('Unknown webview handle:' + handle);
		}
		return webview;
	}

450
	private tryGetWebviewInput(handle: extHostProtocol.WebviewPanelHandle): WebviewInput | undefined {
451
		return this._webviewInputs.getInputForHandle(handle);
452 453
	}

454 455 456 457 458
	private static getDeserializationFailedContents(viewType: string) {
		return `<!DOCTYPE html>
		<html>
			<head>
				<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
459
				<meta http-equiv="Content-Security-Policy" content="default-src 'none';">
460 461 462
			</head>
			<body>${localize('errorMessage', "An error occurred while restoring view:{0}", viewType)}</body>
		</html>`;
A
Alex Dima 已提交
463
	}
464 465
}

466 467
function reviveWebviewExtension(extensionData: extHostProtocol.WebviewExtensionDescription): WebviewExtensionDescription {
	return { id: extensionData.id, location: URI.revive(extensionData.location) };
M
Matt Bierner 已提交
468 469
}

470
function reviveWebviewOptions(options: modes.IWebviewOptions): WebviewInputOptions {
471 472
	return {
		...options,
473
		allowScripts: options.enableScripts,
474 475 476 477 478
		localResourceRoots: Array.isArray(options.localResourceRoots) ? options.localResourceRoots.map(r => URI.revive(r)) : undefined,
	};
}

function reviveWebviewIcon(
M
Matt Bierner 已提交
479 480
	value: { light: UriComponents, dark: UriComponents; } | undefined
): { light: URI, dark: URI; } | undefined {
481 482
	if (!value) {
		return undefined;
A
Alex Dima 已提交
483
	}
484 485 486 487 488

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