forked from microsoft/vscode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebBrowserPanel.ts
More file actions
241 lines (222 loc) · 8.89 KB
/
webBrowserPanel.ts
File metadata and controls
241 lines (222 loc) · 8.89 KB
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import * as cors from 'cors';
import * as express from 'express';
import * as http from 'http';
import { IDisposable } from 'monaco-editor';
import * as path from 'path';
import * as socketIO from 'socket.io';
import { env, Event, EventEmitter, Uri, WebviewOptions, WebviewPanel, window } from 'vscode';
import { IWebviewPanel, IWebviewPanelOptions } from '../../client/common/application/types';
import { IDisposableRegistry } from '../../client/common/types';
import { createDeferred } from '../../client/common/utils/async';
import { noop } from '../../client/common/utils/misc';
import { EXTENSION_ROOT_DIR } from '../../client/constants';
const nocache = require('nocache');
export interface IWebServer extends IDisposable {
onDidReceiveMessage: Event<any>;
postMessage(message: {}): void;
launchServer(cwd: string, resourcesRoot: string, port?: number): Promise<number>;
waitForConnection(): Promise<void>;
}
export class WebServer implements IWebServer {
public get onDidReceiveMessage() {
return this._onDidReceiveMessage.event;
}
private app?: express.Express;
private io?: socketIO.Server;
private server?: http.Server;
private disposed: boolean = false;
private readonly socketPromise = createDeferred<socketIO.Socket>();
private readonly _onDidReceiveMessage = new EventEmitter<any>();
private socket?: socketIO.Socket;
public static create() {
return new WebServer();
}
public dispose() {
this.server?.close();
this.io?.close();
this.disposed = true;
this.socketPromise.promise.then((s) => s.disconnect()).catch(noop);
}
public postMessage(message: {}) {
if (this.disposed) {
return;
}
this.socketPromise.promise
.then(() => {
this.socket?.emit('fromServer', message);
})
.catch((ex) => {
console.error('Failed to connect to socket', ex);
});
}
/**
* Starts a WebServer, and optionally displays a Message when server is ready.
* Used only for debugging and testing purposes.
*/
public async launchServer(cwd: string, resourcesRoot: string, port: number = 0): Promise<number> {
this.app = express();
this.server = http.createServer(this.app);
this.io = socketIO(this.server);
this.app.use(express.static(resourcesRoot, { cacheControl: false, etag: false }));
this.app.use(express.static(cwd));
this.app.use(cors());
// Ensure browser does'nt cache anything (for UI tests/debugging).
this.app.use(nocache());
this.app.disable('view cache');
this.app.get('/source', (req, res) => {
// Query has been messed up in sending to the web site. Works in vscode though, so don't try
// to fix the encoding.
const queryKeys = Object.keys(req.query);
const hashKey = queryKeys ? queryKeys.find((q) => q.startsWith('hash=')) : undefined;
if (hashKey) {
const diskLocation = path.join(EXTENSION_ROOT_DIR, 'tmp', 'scripts', hashKey.substr(5), 'index.js');
res.sendFile(diskLocation);
} else {
res.status(404).end();
}
});
this.io.on('connection', (socket) => {
// Possible we close browser and reconnect, or hit refresh button.
this.socket = socket;
this.socketPromise.resolve(socket);
socket.on('fromClient', (data) => {
this._onDidReceiveMessage.fire(data);
});
});
port = await new Promise<number>((resolve, reject) => {
this.server?.listen(port, () => {
const address = this.server?.address();
if (address && typeof address !== 'string' && 'port' in address) {
resolve(address.port);
} else {
reject(new Error('Address not available'));
}
});
});
// Display a message if this env variable is set (used when debugging).
const url = `http:///localhost:${port}/index.html`;
if (process.env.VSC_PYTHON_DS_UI_PROMPT) {
window.showInformationMessage(`Open browser to '${url}'`, 'Copy').then((selection) => {
if (selection === 'Copy') {
env.clipboard.writeText(url).then(noop, noop);
}
}, noop);
}
return port;
}
public async waitForConnection(): Promise<void> {
await this.socketPromise.promise;
}
}
/**
* Instead of displaying the UI in VS Code WebViews, we'll display in a browser.
* Ensure environment variable `VSC_PYTHON_DS_UI_PORT` is set to a port number.
* Also, if you set `VSC_PYTHON_DS_UI_PROMPT`, you'll be presented with a VS Code messagebox when URL/endpoint is ready.
*/
export class WebBrowserPanel implements IWebviewPanel, IDisposable {
private panel?: WebviewPanel;
private server?: IWebServer;
private serverUrl: string | undefined;
private loadFailedEmitter = new EventEmitter<void>();
constructor(
private readonly disposableRegistry: IDisposableRegistry,
private readonly options: IWebviewPanelOptions,
) {
this.disposableRegistry.push(this);
const webViewOptions: WebviewOptions = {
enableScripts: true,
localResourceRoots: [Uri.file(this.options.rootPath), Uri.file(this.options.cwd)],
};
if (options.webViewPanel) {
this.panel = options.webViewPanel;
this.panel.webview.options = webViewOptions;
} else {
this.panel = window.createWebviewPanel(
options.title.toLowerCase().replace(' ', ''),
options.title,
{ viewColumn: options.viewColumn, preserveFocus: true },
{
retainContextWhenHidden: true,
enableFindWidget: true,
...webViewOptions,
},
);
}
this.panel.webview.html = '<!DOCTYPE html><html><html><body><h1>Loading</h1></body>';
// Reset when the current panel is closed
this.disposableRegistry.push(
this.panel.onDidDispose(() => {
this.panel = undefined;
this.options.listener.dispose().ignoreErrors();
}),
);
this.launchServer(this.options.cwd, this.options.rootPath)
.then((p) => {
this.serverUrl = p;
})
.catch((ex) => console.error('Failed to start Web Browser Panel', ex));
}
public get loadFailed(): Event<void> {
return this.loadFailedEmitter.event;
}
public asWebviewUri(localResource: Uri): Uri {
const filePath = localResource.fsPath;
const name = path.basename(path.dirname(filePath));
if (name !== 'nbextensions' && this.serverUrl) {
// This is a CDN download, Remap to our webserver
const remapped = `${this.serverUrl}/source?hash=${name}`;
return Uri.parse(remapped);
}
return localResource;
}
public setTitle(newTitle: string): void {
if (this.panel) {
this.panel.title = newTitle;
}
}
public async show(preserveFocus: boolean): Promise<void> {
this.panel?.reveal(this.panel?.viewColumn, preserveFocus);
}
public isVisible(): boolean {
return this.panel?.visible === true;
}
public close(): void {
this.dispose();
}
public isActive(): boolean {
return this.panel?.active === true;
}
public updateCwd(_cwd: string): void {
// Noop
}
public dispose() {
this.server?.dispose();
this.panel?.dispose();
}
public postMessage(message: any) {
this.server?.postMessage(message);
}
/**
* Starts a WebServer, and optionally displays a Message when server is ready.
* Used only for debugging and testing purposes.
*/
public async launchServer(cwd: string, resourcesRoot: string): Promise<string> {
// If no port is provided, use a random port.
const dsUIPort = parseInt(process.env.VSC_PYTHON_DS_UI_PORT || '', 10);
const portToUse = isNaN(dsUIPort) ? 0 : dsUIPort;
this.server = WebServer.create();
this.server.onDidReceiveMessage((data) => {
this.options.listener.onMessage(data.type, data.payload);
});
const port = await this.server.launchServer(cwd, resourcesRoot, portToUse);
if (this.panel?.webview) {
const url = `http:///localhost:${port}/index.html`;
this.panel.webview.html = `<!DOCTYPE html><html><html><body><h1>${url}</h1></body>`;
}
await this.server.waitForConnection();
return `http://localhost:${port}`;
}
}