-
Notifications
You must be signed in to change notification settings - Fork 29.1k
/
webviewElement.ts
494 lines (413 loc) · 15 KB
/
webviewElement.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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { addClass, addDisposableListener } from 'vs/base/browser/dom';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable } from 'vs/base/common/lifecycle';
import { URI } from 'vs/base/common/uri';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IFileService } from 'vs/platform/files/common/files';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import * as colorRegistry from 'vs/platform/theme/common/colorRegistry';
import { DARK, ITheme, IThemeService, LIGHT } from 'vs/platform/theme/common/themeService';
import { registerFileProtocol, WebviewProtocol } from 'vs/workbench/parts/webview/electron-browser/webviewProtocols';
import { areWebviewInputOptionsEqual } from './webviewEditorService';
import { WebviewFindWidget } from './webviewFindWidget';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
export interface WebviewOptions {
readonly allowScripts?: boolean;
readonly allowSvgs?: boolean;
readonly svgWhiteList?: string[];
readonly enableWrappedPostMessage?: boolean;
readonly useSameOriginForRoot?: boolean;
readonly localResourceRoots?: ReadonlyArray<URI>;
}
export class WebviewElement extends Disposable {
private _webview: Electron.WebviewTag;
private _ready: Promise<this>;
private _webviewFindWidget: WebviewFindWidget;
private _findStarted: boolean = false;
private _contents: string = '';
private _state: string | undefined = undefined;
private readonly _onDidFocus = this._register(new Emitter<void>());
public get onDidFocus(): Event<void> { return this._onDidFocus.event; }
constructor(
private readonly _styleElement: Element,
private _options: WebviewOptions,
@IInstantiationService instantiationService: IInstantiationService,
@IThemeService private readonly _themeService: IThemeService,
@IEnvironmentService private readonly _environmentService: IEnvironmentService,
@IFileService private readonly _fileService: IFileService,
@IKeybindingService private readonly _keybindingService: IKeybindingService
) {
super();
this._webview = document.createElement('webview');
this._webview.setAttribute('partition', this._options.allowSvgs ? 'webview' : `webview${Date.now()}`);
this._webview.setAttribute('webpreferences', 'contextIsolation=yes');
this._webview.style.flex = '0 1';
this._webview.style.width = '0';
this._webview.style.height = '0';
this._webview.style.outline = '0';
this._webview.preload = require.toUrl('./webview-pre.js');
this._webview.src = this._options.useSameOriginForRoot ? require.toUrl('./webview.html') : 'data:text/html;charset=utf-8,%3C%21DOCTYPE%20html%3E%0D%0A%3Chtml%20lang%3D%22en%22%20style%3D%22width%3A%20100%25%3B%20height%3A%20100%25%22%3E%0D%0A%3Chead%3E%0D%0A%09%3Ctitle%3EVirtual%20Document%3C%2Ftitle%3E%0D%0A%3C%2Fhead%3E%0D%0A%3Cbody%20style%3D%22margin%3A%200%3B%20overflow%3A%20hidden%3B%20width%3A%20100%25%3B%20height%3A%20100%25%22%3E%0D%0A%3C%2Fbody%3E%0D%0A%3C%2Fhtml%3E';
this._ready = new Promise<this>(resolve => {
const subscription = this._register(addDisposableListener(this._webview, 'ipc-message', (event) => {
if (event.channel === 'webview-ready') {
// console.info('[PID Webview] ' event.args[0]);
addClass(this._webview, 'ready'); // can be found by debug command
subscription.dispose();
resolve(this);
}
}));
});
if (!this._options.useSameOriginForRoot) {
let loaded = false;
this._register(addDisposableListener(this._webview, 'did-start-loading', () => {
if (loaded) {
return;
}
loaded = true;
const contents = this._webview.getWebContents();
this.registerFileProtocols(contents);
}));
}
if (!this._options.allowSvgs) {
let loaded = false;
this._register(addDisposableListener(this._webview, 'did-start-loading', () => {
if (loaded) {
return;
}
loaded = true;
const contents = this._webview.getWebContents();
if (!contents) {
return;
}
(contents.session.webRequest as any).onBeforeRequest((details, callback) => {
if (details.url.indexOf('.svg') > 0) {
const uri = URI.parse(details.url);
if (uri && !uri.scheme.match(/file/i) && (uri.path as any).endsWith('.svg') && !this.isAllowedSvg(uri)) {
this.onDidBlockSvg();
return callback({ cancel: true });
}
}
return callback({});
});
(contents.session.webRequest as any).onHeadersReceived((details, callback) => {
const contentType: string[] = (details.responseHeaders['content-type'] || details.responseHeaders['Content-Type']) as any;
if (contentType && Array.isArray(contentType) && contentType.some(x => x.toLowerCase().indexOf('image/svg') >= 0)) {
const uri = URI.parse(details.url);
if (uri && !this.isAllowedSvg(uri)) {
this.onDidBlockSvg();
return callback({ cancel: true });
}
}
return callback({ cancel: false, responseHeaders: details.responseHeaders });
});
}));
}
// Electron: workaround for https://github.com/electron/electron/issues/14258
// We have to detect keyboard events in the <webview> and dispatch them to our
// keybinding service because these events do not bubble to the parent window anymore.
let loaded = false;
this._register(addDisposableListener(this._webview, 'did-start-loading', () => {
if (loaded) {
return;
}
loaded = true;
const contents = this._webview.getWebContents();
if (!contents) {
return;
}
contents.on('before-input-event', (event, input) => {
if (input.type !== 'keyDown') {
return;
}
// Create a fake KeyboardEvent from the data provided
const emulatedKeyboardEvent = new KeyboardEvent('keydown', {
code: input.code,
key: input.key,
shiftKey: input.shift,
altKey: input.alt,
ctrlKey: input.control,
metaKey: input.meta,
repeat: input.isAutoRepeat
});
// Dispatch through our keybinding service
// Note: we set the <webview> as target of the event so that scoped context key
// services function properly to enable commands like select all and find.
if (this._keybindingService.dispatchEvent(new StandardKeyboardEvent(emulatedKeyboardEvent), this._webview)) {
event.preventDefault();
}
});
}));
this._register(addDisposableListener(this._webview, 'console-message', function (e: { level: number; message: string; line: number; sourceId: string; }) {
console.log(`[Embedded Page] ${e.message}`);
}));
this._register(addDisposableListener(this._webview, 'dom-ready', () => {
this.layout();
}));
this._register(addDisposableListener(this._webview, 'crashed', () => {
console.error('embedded page crashed');
}));
this._register(addDisposableListener(this._webview, 'ipc-message', (event) => {
switch (event.channel) {
case 'onmessage':
if (this._options.enableWrappedPostMessage && event.args && event.args.length) {
this._onMessage.fire(event.args[0]);
}
return;
case 'did-click-link':
let [uri] = event.args;
this._onDidClickLink.fire(URI.parse(uri));
return;
case 'did-set-content':
this._webview.style.flex = '';
this._webview.style.width = '100%';
this._webview.style.height = '100%';
this.layout();
return;
case 'did-scroll':
if (event.args && typeof event.args[0] === 'number') {
this._onDidScroll.fire({ scrollYPercentage: event.args[0] });
}
return;
case 'do-reload':
this.reload();
return;
case 'do-update-state':
this._state = event.args[0];
this._onDidUpdateState.fire(this._state);
return;
case 'did-focus':
this.handleFocusChange(true);
return;
case 'did-blur':
this.handleFocusChange(false);
return;
}
}));
this._register(addDisposableListener(this._webview, 'devtools-opened', () => {
this._send('devtools-opened');
}));
this._webviewFindWidget = this._register(instantiationService.createInstance(WebviewFindWidget, this));
this.style(this._themeService.getTheme());
this._register(this._themeService.onThemeChange(this.style, this));
}
public mountTo(parent: HTMLElement) {
parent.appendChild(this._webviewFindWidget.getDomNode());
parent.appendChild(this._webview);
}
dispose(): void {
if (this._webview) {
if (this._webview.parentElement) {
this._webview.parentElement.removeChild(this._webview);
}
}
this._webview = undefined;
this._webviewFindWidget = undefined;
super.dispose();
}
private readonly _onDidClickLink = this._register(new Emitter<URI>());
public readonly onDidClickLink = this._onDidClickLink.event;
private readonly _onDidScroll = this._register(new Emitter<{ scrollYPercentage: number }>());
public readonly onDidScroll = this._onDidScroll.event;
private readonly _onDidUpdateState = this._register(new Emitter<string | undefined>());
public readonly onDidUpdateState = this._onDidUpdateState.event;
private readonly _onMessage = this._register(new Emitter<any>());
public readonly onMessage = this._onMessage.event;
private _send(channel: string, ...args: any[]): void {
this._ready
.then(() => this._webview.send(channel, ...args))
.catch(err => console.error(err));
}
public set initialScrollProgress(value: number) {
this._send('initial-scroll-position', value);
}
public set state(value: string | undefined) {
this._state = value;
}
public set options(value: WebviewOptions) {
if (this._options && areWebviewInputOptionsEqual(value, this._options)) {
return;
}
this._options = value;
this._send('content', {
contents: this._contents,
options: this._options,
state: this._state
});
}
public set contents(value: string) {
this._contents = value;
this._send('content', {
contents: value,
options: this._options,
state: this._state
});
}
public update(value: string, options: WebviewOptions) {
this._contents = value;
this._options = options;
this._send('content', {
contents: this._contents,
options: this._options,
state: this._state
});
}
public set baseUrl(value: string) {
this._send('baseUrl', value);
}
public focus(): void {
this._webview.focus();
this._send('focus');
// Handle focus change programmatically (do not rely on event from <webview>)
this.handleFocusChange(true);
}
private handleFocusChange(isFocused: boolean): void {
if (isFocused) {
this._onDidFocus.fire();
}
}
public sendMessage(data: any): void {
this._send('message', data);
}
private onDidBlockSvg() {
this.sendMessage({
name: 'vscode-did-block-svg'
});
}
private style(theme: ITheme): void {
const { fontFamily, fontWeight, fontSize } = window.getComputedStyle(this._styleElement); // TODO@theme avoid styleElement
const exportedColors = colorRegistry.getColorRegistry().getColors().reduce((colors, entry) => {
const color = theme.getColor(entry.id);
if (color) {
colors['vscode-' + entry.id.replace('.', '-')] = color.toString();
}
return colors;
}, {});
const styles = {
// Old vars
'font-family': fontFamily,
'font-weight': fontWeight,
'font-size': fontSize,
'background-color': theme.getColor(colorRegistry.editorBackground).toString(),
'color': theme.getColor(colorRegistry.editorForeground).toString(),
'link-color': theme.getColor(colorRegistry.textLinkForeground).toString(),
'link-active-color': theme.getColor(colorRegistry.textLinkActiveForeground).toString(),
// Offical API
'vscode-editor-font-family': fontFamily,
'vscode-editor-font-weight': fontWeight,
'vscode-editor-font-size': fontSize,
...exportedColors
};
const activeTheme = ApiThemeClassName.fromTheme(theme);
this._send('styles', styles, activeTheme);
this._webviewFindWidget.updateTheme(theme);
}
public layout(): void {
const contents = (this._webview as any).getWebContents();
if (!contents || contents.isDestroyed()) {
return;
}
const window = contents.getOwnerBrowserWindow();
if (!window || !window.webContents || window.webContents.isDestroyed()) {
return;
}
window.webContents.getZoomFactor(factor => {
if (contents.isDestroyed()) {
return;
}
contents.setZoomFactor(factor);
});
}
private isAllowedSvg(uri: URI): boolean {
if (this._options.allowSvgs) {
return true;
}
if (this._options.svgWhiteList) {
return this._options.svgWhiteList.indexOf(uri.authority.toLowerCase()) >= 0;
}
return false;
}
private registerFileProtocols(contents: Electron.WebContents) {
if (!contents || contents.isDestroyed()) {
return;
}
const appRootUri = URI.file(this._environmentService.appRoot);
registerFileProtocol(contents, WebviewProtocol.CoreResource, this._fileService, () => [
appRootUri
]);
registerFileProtocol(contents, WebviewProtocol.VsCodeResource, this._fileService, () =>
(this._options.localResourceRoots || [])
);
}
public startFind(value: string, options?: Electron.FindInPageOptions) {
if (!value) {
return;
}
// ensure options is defined without modifying the original
options = options || {};
// FindNext must be false for a first request
const findOptions: Electron.FindInPageOptions = {
forward: options.forward,
findNext: false,
matchCase: options.matchCase,
medialCapitalAsWordStart: options.medialCapitalAsWordStart
};
this._findStarted = true;
this._webview.findInPage(value, findOptions);
}
/**
* Webviews expose a stateful find API.
* Successive calls to find will move forward or backward through onFindResults
* depending on the supplied options.
*
* @param value The string to search for. Empty strings are ignored.
* @param options
*/
public find(value: string, options?: Electron.FindInPageOptions): void {
// Searching with an empty value will throw an exception
if (!value) {
return;
}
if (!this._findStarted) {
this.startFind(value, options);
return;
}
this._webview.findInPage(value, options);
}
public stopFind(keepSelection?: boolean): void {
this._findStarted = false;
this._webview.stopFindInPage(keepSelection ? 'keepSelection' : 'clearSelection');
}
public showFind() {
this._webviewFindWidget.reveal();
}
public hideFind() {
this._webviewFindWidget.hide();
}
public reload() {
this.contents = this._contents;
}
public selectAll() {
this._webview.selectAll();
}
}
enum ApiThemeClassName {
light = 'vscode-light',
dark = 'vscode-dark',
highContrast = 'vscode-high-contrast'
}
namespace ApiThemeClassName {
export function fromTheme(theme: ITheme): ApiThemeClassName {
if (theme.type === LIGHT) {
return ApiThemeClassName.light;
} else if (theme.type === DARK) {
return ApiThemeClassName.dark;
} else {
return ApiThemeClassName.highContrast;
}
}
}