mainThreadWebview.ts 18.3 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 { IFileService } from 'vs/platform/files/common/files';
16
import { IOpenerService } from 'vs/platform/opener/common/opener';
17
import { IProductService } from 'vs/platform/product/common/productService';
18
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
19
import * as extHostProtocol from 'vs/workbench/api/common/extHost.protocol';
20
import { editorGroupToViewColumn, EditorViewColumn, viewColumnToEditorGroup } from 'vs/workbench/api/common/shared/editor';
21 22
import { IEditorInput } from 'vs/workbench/common/editor';
import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';
23
import { CustomFileEditorInput } from 'vs/workbench/contrib/customEditor/browser/customEditorInput';
24
import { ICustomEditorModel, ICustomEditorService } from 'vs/workbench/contrib/customEditor/common/customEditor';
25
import { WebviewExtensionDescription } from 'vs/workbench/contrib/webview/browser/webview';
26
import { WebviewInput } from 'vs/workbench/contrib/webview/browser/webviewEditorInput';
27
import { ICreateWebViewShowOptions, IWebviewWorkbenchService, WebviewInputOptions } from 'vs/workbench/contrib/webview/browser/webviewWorkbenchService';
28
import { IEditorGroup, IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
29
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
30
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
A
Alex Dima 已提交
31 32
import { extHostNamedCustomer } from '../common/extHostCustomers';

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

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

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

49
	public getInputForHandle(handle: string): WebviewInput | undefined {
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
		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 已提交
66 67 68 69
class WebviewViewTypeTransformer {
	public constructor(
		public readonly prefix: string,
	) { }
M
Matt Bierner 已提交
70

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

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

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

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

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

95
	private readonly _proxy: extHostProtocol.ExtHostWebviewsShape;
96
	private readonly _webviewInputs = new WebviewInputStore();
97
	private readonly _revivers = new Map<string, IDisposable>();
98
	private readonly _editorProviders = new Map<string, IDisposable>();
99
	private readonly _customEditorModels = new Map<ICustomEditorModel, { referenceCount: number }>();
100 101

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

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

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

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

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

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

156
		this._webviewInputs.add(handle, webview);
157 158 159 160 161 162

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	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 已提交
256
	}
257

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

263
		const extension = reviveWebviewExtension(extensionData);
M
Matt Bierner 已提交
264

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

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

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

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

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

311
	private async retainCustomEditorModel(webviewInput: WebviewInput, resource: URI, viewType: string, capabilities: readonly extHostProtocol.WebviewEditorCapabilities[]) {
B
Benjamin Pasero 已提交
312
		const model = await this._customEditorService.models.resolve(webviewInput.getResource(), webviewInput.viewType);
313 314 315 316 317 318

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

321
		this._customEditorModels.set(model, { referenceCount: 1 });
322 323

		const capabilitiesSet = new Set(capabilities);
324 325
		const isEditable = capabilitiesSet.has(extHostProtocol.WebviewEditorCapabilities.Editable);
		if (isEditable) {
326
			model.onUndo(edits => {
327 328
				this._proxy.$undoEdits(resource, viewType, edits.map(x => x.data));
			});
329

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

337
			model.onWillSave(e => {
338 339
				e.waitUntil(this._proxy.$onSave(resource.toJSON(), viewType));
			});
340

341
		}
342 343 344 345 346 347 348 349 350 351

		// Save as should always be implemented even if the model is readonly
		model.onWillSaveAs(e => {
			if (isEditable) {
				e.waitUntil(this._proxy.$onSaveAs(e.resource.toJSON(), viewType, e.targetResource.toJSON()));
			} else {
				// Since the editor is readonly, just copy the file over
				e.waitUntil(this._fileService.copy(e.resource, e.targetResource, false /* overwrite */));
			}
		});
352 353 354 355 356 357 358 359 360 361 362 363 364 365
		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);
		}
366 367
	}

368 369
	public $onEdit(resource: UriComponents, viewType: string, editData: any): void {
		const model = this._customEditorService.models.get(URI.revive(resource), viewType);
370 371 372 373
		if (!model) {
			throw new Error('Could not find model for webview editor');
		}

374
		model.pushEdit({ source: model, data: editData });
375 376
	}

377
	private hookupWebviewEventDelegate(handle: extHostProtocol.WebviewPanelHandle, input: WebviewInput) {
378 379
		const disposables = new DisposableStore();

380
		disposables.add(input.webview.onDidClickLink((uri) => this.onDidClickLink(handle, uri)));
381 382 383 384 385
		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();
386
		});
387 388 389 390 391
		input.onDisposeWebview(() => {
			this._proxy.$onDidDisposeWebviewPanel(handle).finally(() => {
				this._webviewInputs.delete(handle);
			});
		});
A
Alex Dima 已提交
392
	}
393

394
	private updateWebviewViewStates() {
395
		if (!this._webviewInputs.size) {
396 397
			return;
		}
398

399
		const activeInput = this._editorService.activeControl && this._editorService.activeControl.input;
400
		const viewStates: extHostProtocol.WebviewPanelViewStateData = {};
401

402 403 404 405 406 407 408
		const updateViewStatesForInput = (group: IEditorGroup, topLevelInput: IEditorInput, editorInput: IEditorInput) => {
			if (!(editorInput instanceof WebviewInput)) {
				return;
			}

			editorInput.updateGroup(group.id);

409
			const handle = this._webviewInputs.getHandleForInput(editorInput);
410 411
			if (handle) {
				viewStates[handle] = {
412 413
					visible: topLevelInput === group.activeEditor,
					active: topLevelInput === activeInput,
414 415 416 417
					position: editorGroupToViewColumn(this._editorGroupService, group.id),
				};
			}
		};
418

419 420 421 422 423 424 425
		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);
426 427
				}
			}
428
		}
429 430 431 432

		if (Object.keys(viewStates).length) {
			this._proxy.$onDidChangeWebviewPanelViewStates(viewStates);
		}
433 434
	}

435
	private onDidClickLink(handle: extHostProtocol.WebviewPanelHandle, link: string): void {
436
		const webview = this.getWebviewInput(handle);
437
		if (this.isSupportedLink(webview, URI.parse(link))) {
438
			this._openerService.open(link, { fromUserGesture: true });
439 440 441
		}
	}

442
	private isSupportedLink(webview: WebviewInput, link: URI): boolean {
443 444 445
		if (MainThreadWebviews.standardSupportedLinkSchemes.has(link.scheme)) {
			return true;
		}
446
		if (!isWeb && this._productService.urlProtocol === link.scheme) {
447 448
			return true;
		}
M
Matt Bierner 已提交
449
		return !!webview.webview.contentOptions.enableCommandUris && link.scheme === Schemas.command;
A
Alex Dima 已提交
450
	}
451

452
	private getWebviewInput(handle: extHostProtocol.WebviewPanelHandle): WebviewInput {
453
		const webview = this.tryGetWebviewInput(handle);
454 455 456 457 458 459
		if (!webview) {
			throw new Error('Unknown webview handle:' + handle);
		}
		return webview;
	}

460
	private tryGetWebviewInput(handle: extHostProtocol.WebviewPanelHandle): WebviewInput | undefined {
461
		return this._webviewInputs.getInputForHandle(handle);
462 463
	}

464 465 466 467 468
	private static getDeserializationFailedContents(viewType: string) {
		return `<!DOCTYPE html>
		<html>
			<head>
				<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
469
				<meta http-equiv="Content-Security-Policy" content="default-src 'none';">
470 471 472
			</head>
			<body>${localize('errorMessage', "An error occurred while restoring view:{0}", viewType)}</body>
		</html>`;
A
Alex Dima 已提交
473
	}
474 475
}

476 477
function reviveWebviewExtension(extensionData: extHostProtocol.WebviewExtensionDescription): WebviewExtensionDescription {
	return { id: extensionData.id, location: URI.revive(extensionData.location) };
M
Matt Bierner 已提交
478 479
}

480
function reviveWebviewOptions(options: modes.IWebviewOptions): WebviewInputOptions {
481 482
	return {
		...options,
483
		allowScripts: options.enableScripts,
484 485 486 487 488
		localResourceRoots: Array.isArray(options.localResourceRoots) ? options.localResourceRoots.map(r => URI.revive(r)) : undefined,
	};
}

function reviveWebviewIcon(
M
Matt Bierner 已提交
489 490
	value: { light: UriComponents, dark: UriComponents; } | undefined
): { light: URI, dark: URI; } | undefined {
491 492
	if (!value) {
		return undefined;
A
Alex Dima 已提交
493
	}
494 495 496 497 498

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