-
Notifications
You must be signed in to change notification settings - Fork 27.9k
/
mainThreadWebviewPanels.ts
409 lines (339 loc) · 14.8 KB
/
mainThreadWebviewPanels.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { onUnexpectedError } from 'vs/base/common/errors';
import { Disposable, DisposableMap } from 'vs/base/common/lifecycle';
import { URI } from 'vs/base/common/uri';
import { generateUuid } from 'vs/base/common/uuid';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { MainThreadWebviews, reviveWebviewContentOptions, reviveWebviewExtension } from 'vs/workbench/api/browser/mainThreadWebviews';
import * as extHostProtocol from 'vs/workbench/api/common/extHost.protocol';
import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';
import { EditorInput } from 'vs/workbench/common/editor/editorInput';
import { Memento, MementoObject } from 'vs/workbench/common/memento';
import { WebviewOptions } from 'vs/workbench/contrib/webview/browser/webview';
import { WebviewInput } from 'vs/workbench/contrib/webviewPanel/browser/webviewEditorInput';
import { WebviewIcons } from 'vs/workbench/contrib/webviewPanel/browser/webviewIconManager';
import { IWebViewShowOptions, IWebviewWorkbenchService } from 'vs/workbench/contrib/webviewPanel/browser/webviewWorkbenchService';
import { editorGroupToColumn } from 'vs/workbench/services/editor/common/editorGroupColumn';
import { GroupLocation, GroupsOrder, IEditorGroup, IEditorGroupsService, preferredSideBySideGroupDirection } from 'vs/workbench/services/editor/common/editorGroupsService';
import { ACTIVE_GROUP, IEditorService, PreferredGroup, SIDE_GROUP } from 'vs/workbench/services/editor/common/editorService';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IExtHostContext } from 'vs/workbench/services/extensions/common/extHostCustomers';
/**
* Bi-directional map between webview handles and inputs.
*/
class WebviewInputStore {
private readonly _handlesToInputs = new Map<string, WebviewInput>();
private readonly _inputsToHandles = new Map<WebviewInput, string>();
public add(handle: string, input: WebviewInput): void {
this._handlesToInputs.set(handle, input);
this._inputsToHandles.set(input, handle);
}
public getHandleForInput(input: WebviewInput): string | undefined {
return this._inputsToHandles.get(input);
}
public getInputForHandle(handle: string): WebviewInput | undefined {
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;
}
[Symbol.iterator](): Iterator<WebviewInput> {
return this._handlesToInputs.values();
}
}
class WebviewViewTypeTransformer {
public constructor(
public readonly prefix: string,
) { }
public fromExternal(viewType: string): string {
return this.prefix + viewType;
}
public toExternal(viewType: string): string | undefined {
return viewType.startsWith(this.prefix)
? viewType.substr(this.prefix.length)
: undefined;
}
}
/**
* Stores the unique origins for webviews.
*
* These are randomly generated, but keyed on extension and webview viewType.
*/
class WebviewOriginStore {
private readonly memento: Memento;
private readonly state: MementoObject;
constructor(
storageKey: string,
@IStorageService storageService: IStorageService,
) {
this.memento = new Memento(storageKey, storageService);
this.state = this.memento.getMemento(StorageScope.APPLICATION, StorageTarget.MACHINE);
}
public getOrigin(extId: ExtensionIdentifier, viewType: string): string {
const key = this.getKey(extId, viewType);
const existing = this.state[key];
if (existing && typeof existing === 'string') {
return existing;
}
const newOrigin = generateUuid();
this.state[key] = newOrigin;
this.memento.saveMemento();
return newOrigin;
}
private getKey(extId: ExtensionIdentifier, viewType: string): string {
return JSON.stringify([extId.value, viewType]);
}
}
export class MainThreadWebviewPanels extends Disposable implements extHostProtocol.MainThreadWebviewPanelsShape {
private readonly webviewPanelViewType = new WebviewViewTypeTransformer('mainThreadWebview-');
private readonly _proxy: extHostProtocol.ExtHostWebviewPanelsShape;
private readonly _webviewInputs = new WebviewInputStore();
private readonly _revivers = this._register(new DisposableMap<string>());
private readonly webviewOriginStore: WebviewOriginStore;
constructor(
context: IExtHostContext,
private readonly _mainThreadWebviews: MainThreadWebviews,
@IConfigurationService private readonly _configurationService: IConfigurationService,
@IEditorGroupsService private readonly _editorGroupService: IEditorGroupsService,
@IEditorService private readonly _editorService: IEditorService,
@IExtensionService extensionService: IExtensionService,
@IStorageService storageService: IStorageService,
@ITelemetryService private readonly _telemetryService: ITelemetryService,
@IWebviewWorkbenchService private readonly _webviewWorkbenchService: IWebviewWorkbenchService,
) {
super();
this.webviewOriginStore = new WebviewOriginStore('mainThreadWebviewPanel.origins', storageService);
this._proxy = context.getProxy(extHostProtocol.ExtHostContext.ExtHostWebviewPanels);
this._register(_editorService.onDidActiveEditorChange(() => {
this.updateWebviewViewStates(this._editorService.activeEditor);
}));
this._register(_editorService.onDidVisibleEditorsChange(() => {
this.updateWebviewViewStates(this._editorService.activeEditor);
}));
this._register(_webviewWorkbenchService.onDidChangeActiveWebviewEditor(input => {
this.updateWebviewViewStates(input);
}));
// This reviver's only job is to activate extensions.
// This should trigger the real reviver to be registered from the extension host side.
this._register(_webviewWorkbenchService.registerResolver({
canResolve: (webview: WebviewInput) => {
const viewType = this.webviewPanelViewType.toExternal(webview.viewType);
if (typeof viewType === 'string') {
extensionService.activateByEvent(`onWebviewPanel:${viewType}`);
}
return false;
},
resolveWebview: () => { throw new Error('not implemented'); }
}));
}
public get webviewInputs(): Iterable<WebviewInput> { return this._webviewInputs; }
public addWebviewInput(handle: extHostProtocol.WebviewHandle, input: WebviewInput, options: { serializeBuffersForPostMessage: boolean }): void {
this._webviewInputs.add(handle, input);
this._mainThreadWebviews.addWebview(handle, input.webview, options);
input.webview.onDidDispose(() => {
this._proxy.$onDidDisposeWebviewPanel(handle).finally(() => {
this._webviewInputs.delete(handle);
});
});
}
public $createWebviewPanel(
extensionData: extHostProtocol.WebviewExtensionDescription,
handle: extHostProtocol.WebviewHandle,
viewType: string,
initData: extHostProtocol.IWebviewInitData,
showOptions: extHostProtocol.WebviewPanelShowOptions,
): void {
const targetGroup = this.getTargetGroupFromShowOptions(showOptions);
const mainThreadShowOptions: IWebViewShowOptions = showOptions ? {
preserveFocus: !!showOptions.preserveFocus,
group: targetGroup
} : {};
const extension = reviveWebviewExtension(extensionData);
const origin = this.webviewOriginStore.getOrigin(extension.id, viewType);
const webview = this._webviewWorkbenchService.openWebview({
id: handle,
origin,
providedViewType: viewType,
options: reviveWebviewOptions(initData.panelOptions),
contentOptions: reviveWebviewContentOptions(initData.webviewOptions),
extension
}, this.webviewPanelViewType.fromExternal(viewType), initData.title, mainThreadShowOptions);
this.addWebviewInput(handle, webview, { serializeBuffersForPostMessage: initData.serializeBuffersForPostMessage });
const payload = {
extensionId: extension.id.value,
viewType
} as const;
type Classification = {
extensionId: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Id of the extension that created the webview panel' };
viewType: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Id of the webview' };
owner: 'mjbvz';
comment: 'Triggered when a webview is created. Records the type of webview and the extension which created it';
};
this._telemetryService.publicLog2<typeof payload, Classification>('webviews:createWebviewPanel', payload);
}
public $disposeWebview(handle: extHostProtocol.WebviewHandle): void {
const webview = this.getWebviewInput(handle);
webview.dispose();
}
public $setTitle(handle: extHostProtocol.WebviewHandle, value: string): void {
const webview = this.getWebviewInput(handle);
webview.setName(value);
}
public $setIconPath(handle: extHostProtocol.WebviewHandle, value: extHostProtocol.IWebviewIconPath | undefined): void {
const webview = this.getWebviewInput(handle);
webview.iconPath = reviveWebviewIcon(value);
}
public $reveal(handle: extHostProtocol.WebviewHandle, showOptions: extHostProtocol.WebviewPanelShowOptions): void {
const webview = this.getWebviewInput(handle);
if (webview.isDisposed()) {
return;
}
const targetGroup = this.getTargetGroupFromShowOptions(showOptions);
this._webviewWorkbenchService.revealWebview(webview, targetGroup, !!showOptions.preserveFocus);
}
private getTargetGroupFromShowOptions(showOptions: extHostProtocol.WebviewPanelShowOptions): PreferredGroup {
if (typeof showOptions.viewColumn === 'undefined'
|| showOptions.viewColumn === ACTIVE_GROUP
|| (this._editorGroupService.count === 1 && this._editorGroupService.activeGroup.isEmpty)
) {
return ACTIVE_GROUP;
}
if (showOptions.viewColumn === SIDE_GROUP) {
return SIDE_GROUP;
}
if (showOptions.viewColumn >= 0) {
// First check to see if an existing group exists
const groupInColumn = this._editorGroupService.getGroups(GroupsOrder.GRID_APPEARANCE)[showOptions.viewColumn];
if (groupInColumn) {
return groupInColumn.id;
}
// We are dealing with an unknown group and therefore need a new group.
// Note that the new group's id may not match the one requested. We only allow
// creating a single new group, so if someone passes in `showOptions.viewColumn = 99`
// and there are two editor groups open, we simply create a third editor group instead
// of creating all the groups up to 99.
const newGroup = this._editorGroupService.findGroup({ location: GroupLocation.LAST });
if (newGroup) {
const direction = preferredSideBySideGroupDirection(this._configurationService);
return this._editorGroupService.addGroup(newGroup, direction);
}
}
return ACTIVE_GROUP;
}
public $registerSerializer(viewType: string, options: { serializeBuffersForPostMessage: boolean }): void {
if (this._revivers.has(viewType)) {
throw new Error(`Reviver for ${viewType} already registered`);
}
this._revivers.set(viewType, this._webviewWorkbenchService.registerResolver({
canResolve: (webviewInput) => {
return webviewInput.viewType === this.webviewPanelViewType.fromExternal(viewType);
},
resolveWebview: async (webviewInput): Promise<void> => {
const viewType = this.webviewPanelViewType.toExternal(webviewInput.viewType);
if (!viewType) {
webviewInput.webview.html = this._mainThreadWebviews.getWebviewResolvedFailedContent(webviewInput.viewType);
return;
}
const handle = webviewInput.id;
this.addWebviewInput(handle, webviewInput, options);
let state = undefined;
if (webviewInput.webview.state) {
try {
state = JSON.parse(webviewInput.webview.state);
} catch (e) {
console.error('Could not load webview state', e, webviewInput.webview.state);
}
}
try {
await this._proxy.$deserializeWebviewPanel(handle, viewType, {
title: webviewInput.getTitle(),
state,
panelOptions: webviewInput.webview.options,
webviewOptions: webviewInput.webview.contentOptions,
active: webviewInput === this._editorService.activeEditor,
}, editorGroupToColumn(this._editorGroupService, webviewInput.group || 0));
} catch (error) {
onUnexpectedError(error);
webviewInput.webview.html = this._mainThreadWebviews.getWebviewResolvedFailedContent(viewType);
}
}
}));
}
public $unregisterSerializer(viewType: string): void {
if (!this._revivers.has(viewType)) {
throw new Error(`No reviver for ${viewType} registered`);
}
this._revivers.deleteAndDispose(viewType);
}
private updateWebviewViewStates(activeEditorInput: EditorInput | undefined) {
if (!this._webviewInputs.size) {
return;
}
const viewStates: extHostProtocol.WebviewPanelViewStateData = {};
const updateViewStatesForInput = (group: IEditorGroup, topLevelInput: EditorInput, editorInput: EditorInput) => {
if (!(editorInput instanceof WebviewInput)) {
return;
}
editorInput.updateGroup(group.id);
const handle = this._webviewInputs.getHandleForInput(editorInput);
if (handle) {
viewStates[handle] = {
visible: topLevelInput === group.activeEditor,
active: editorInput === activeEditorInput,
position: editorGroupToColumn(this._editorGroupService, group.id),
};
}
};
for (const group of this._editorGroupService.groups) {
for (const input of group.editors) {
if (input instanceof DiffEditorInput) {
updateViewStatesForInput(group, input, input.primary);
updateViewStatesForInput(group, input, input.secondary);
} else {
updateViewStatesForInput(group, input, input);
}
}
}
if (Object.keys(viewStates).length) {
this._proxy.$onDidChangeWebviewPanelViewStates(viewStates);
}
}
private getWebviewInput(handle: extHostProtocol.WebviewHandle): WebviewInput {
const webview = this.tryGetWebviewInput(handle);
if (!webview) {
throw new Error(`Unknown webview handle:${handle}`);
}
return webview;
}
private tryGetWebviewInput(handle: extHostProtocol.WebviewHandle): WebviewInput | undefined {
return this._webviewInputs.getInputForHandle(handle);
}
}
function reviveWebviewIcon(value: extHostProtocol.IWebviewIconPath | undefined): WebviewIcons | undefined {
if (!value) {
return undefined;
}
return {
light: URI.revive(value.light),
dark: URI.revive(value.dark),
};
}
function reviveWebviewOptions(panelOptions: extHostProtocol.IWebviewPanelOptions): WebviewOptions {
return {
enableFindWidget: panelOptions.enableFindWidget,
retainContextWhenHidden: panelOptions.retainContextWhenHidden,
};
}