forked from microsoft/vscode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebViewHost.ts
More file actions
370 lines (322 loc) · 16.9 KB
/
webViewHost.ts
File metadata and controls
370 lines (322 loc) · 16.9 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
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import '../common/extensions';
import { injectable, unmanaged } from 'inversify';
import { ConfigurationChangeEvent, ViewColumn, WebviewPanel, WorkspaceConfiguration } from 'vscode';
import { IWebPanel, IWebPanelMessageListener, IWebPanelProvider, IWorkspaceService } from '../common/application/types';
import { traceInfo, traceWarning } from '../common/logger';
import { IConfigurationService, IDisposable, Resource } from '../common/types';
import { createDeferred, Deferred } from '../common/utils/async';
import * as localize from '../common/utils/localize';
import { noop } from '../common/utils/misc';
import { StopWatch } from '../common/utils/stopWatch';
import { captureTelemetry, sendTelemetryEvent } from '../telemetry';
import { DefaultTheme, Telemetry } from './constants';
import { CssMessages, IGetCssRequest, IGetMonacoThemeRequest, SharedMessages } from './messages';
import { ICodeCssGenerator, IDataScienceExtraSettings, IThemeFinder, WebViewViewChangeEventArgs } from './types';
@injectable() // For some reason this is necessary to get the class hierarchy to work.
export abstract class WebViewHost<IMapping> implements IDisposable {
protected viewState: { visible: boolean; active: boolean } = { visible: false, active: false };
private disposed: boolean = false;
private webPanel: IWebPanel | undefined;
private webPanelInit: Deferred<void> | undefined = createDeferred<void>();
private messageListener: IWebPanelMessageListener;
private themeChangeHandler: IDisposable | undefined;
private settingsChangeHandler: IDisposable | undefined;
private themeIsDarkPromise: Deferred<boolean> | undefined = createDeferred<boolean>();
private startupStopwatch = new StopWatch();
constructor(
@unmanaged() protected configService: IConfigurationService,
@unmanaged() private provider: IWebPanelProvider,
@unmanaged() private cssGenerator: ICodeCssGenerator,
@unmanaged() protected themeFinder: IThemeFinder,
@unmanaged() protected workspaceService: IWorkspaceService,
@unmanaged()
messageListenerCtor: (
callback: (message: string, payload: {}) => void,
viewChanged: (panel: IWebPanel) => void,
disposed: () => void
) => IWebPanelMessageListener,
@unmanaged() private rootPath: string,
@unmanaged() private scripts: string[],
@unmanaged() private title: string,
@unmanaged() private viewColumn: ViewColumn,
@unmanaged() private readonly useWebViewServer: boolean
) {
// Create our message listener for our web panel.
this.messageListener = messageListenerCtor(
this.onMessage.bind(this),
this.webPanelViewStateChanged.bind(this),
this.dispose.bind(this)
);
// Listen for settings changes from vscode.
this.themeChangeHandler = this.workspaceService.onDidChangeConfiguration(this.onPossibleSettingsChange, this);
// Listen for settings changes
this.settingsChangeHandler = this.configService
.getSettings(undefined)
.onDidChange(this.onDataScienceSettingsChanged.bind(this));
// Send the first settings message
this.onDataScienceSettingsChanged().ignoreErrors();
// Send the loc strings
this.postMessageInternal(SharedMessages.LocInit, localize.getCollectionJSON()).ignoreErrors();
}
public async show(preserveFocus: boolean): Promise<void> {
if (!this.isDisposed) {
// Then show our web panel.
if (this.webPanel) {
await this.webPanel.show(preserveFocus);
}
}
}
public updateCwd(cwd: string): void {
if (this.webPanel) {
this.webPanel.updateCwd(cwd);
}
}
public dispose() {
if (!this.isDisposed) {
this.disposed = true;
if (this.webPanel) {
this.webPanel.close();
this.webPanel = undefined;
}
if (this.themeChangeHandler) {
this.themeChangeHandler.dispose();
this.themeChangeHandler = undefined;
}
if (this.settingsChangeHandler) {
this.settingsChangeHandler.dispose();
this.settingsChangeHandler = undefined;
}
this.webPanelInit = undefined;
this.themeIsDarkPromise = undefined;
}
}
public setTitle(newTitle: string) {
if (!this.isDisposed && this.webPanel) {
this.webPanel.setTitle(newTitle);
}
}
public setTheme(isDark: boolean) {
if (this.themeIsDarkPromise && !this.themeIsDarkPromise.resolved) {
this.themeIsDarkPromise.resolve(isDark);
} else {
this.themeIsDarkPromise = createDeferred<boolean>();
this.themeIsDarkPromise.resolve(isDark);
}
}
protected abstract getOwningResource(): Promise<Resource>;
protected get isDisposed(): boolean {
return this.disposed;
}
//tslint:disable-next-line:no-any
protected onMessage(message: string, payload: any) {
switch (message) {
case SharedMessages.Started:
this.webPanelRendered();
break;
case CssMessages.GetCssRequest:
this.handleCssRequest(payload as IGetCssRequest).ignoreErrors();
break;
case CssMessages.GetMonacoThemeRequest:
this.handleMonacoThemeRequest(payload as IGetMonacoThemeRequest).ignoreErrors();
break;
default:
break;
}
}
protected postMessage<M extends IMapping, T extends keyof M>(type: T, payload?: M[T]): Promise<void> {
// Then send it the message
return this.postMessageInternal(type.toString(), payload);
}
protected shareMessage<M extends IMapping, T extends keyof M>(type: T, payload?: M[T]) {
// Send our remote message.
this.messageListener.onMessage(type.toString(), payload);
}
protected onViewStateChanged(_args: WebViewViewChangeEventArgs) {
noop();
}
// tslint:disable-next-line:no-any
protected async postMessageInternal(type: string, payload?: any): Promise<void> {
if (this.webPanelInit) {
// Make sure the webpanel is up before we send it anything.
await this.webPanelInit.promise;
// Then send it the message
this.webPanel?.postMessage({ type: type.toString(), payload: payload });
}
}
protected async generateDataScienceExtraSettings(): Promise<IDataScienceExtraSettings> {
const resource = await this.getOwningResource();
const editor = this.workspaceService.getConfiguration('editor');
const workbench = this.workspaceService.getConfiguration('workbench');
const theme = !workbench ? DefaultTheme : workbench.get<string>('colorTheme', DefaultTheme);
return {
...this.configService.getSettings(resource).datascience,
extraSettings: {
editor: {
cursor: this.getValue(editor, 'cursorStyle', 'line'),
cursorBlink: this.getValue(editor, 'cursorBlinking', 'blink'),
autoClosingBrackets: this.getValue(editor, 'autoClosingBrackets', 'languageDefined'),
autoClosingQuotes: this.getValue(editor, 'autoClosingQuotes', 'languageDefined'),
autoSurround: this.getValue(editor, 'autoSurround', 'languageDefined'),
autoIndent: this.getValue(editor, 'autoIndent', false),
fontLigatures: this.getValue(editor, 'fontLigatures', false),
scrollBeyondLastLine: this.getValue(editor, 'scrollBeyondLastLine', true),
// VS Code puts a value for this, but it's 10 (the explorer bar size) not 14 the editor size for vert
verticalScrollbarSize: this.getValue(editor, 'scrollbar.verticalScrollbarSize', 14),
horizontalScrollbarSize: this.getValue(editor, 'scrollbar.horizontalScrollbarSize', 10),
fontSize: this.getValue(editor, 'fontSize', 14),
fontFamily: this.getValue(editor, 'fontFamily', "Consolas, 'Courier New', monospace")
},
theme: theme
},
intellisenseOptions: {
quickSuggestions: {
other: this.getValue(editor, 'quickSuggestions.other', true),
comments: this.getValue(editor, 'quickSuggestions.comments', false),
strings: this.getValue(editor, 'quickSuggestions.strings', false)
},
acceptSuggestionOnEnter: this.getValue(editor, 'acceptSuggestionOnEnter', 'on'),
quickSuggestionsDelay: this.getValue(editor, 'quickSuggestionsDelay', 10),
suggestOnTriggerCharacters: this.getValue(editor, 'suggestOnTriggerCharacters', true),
tabCompletion: this.getValue(editor, 'tabCompletion', 'on'),
suggestLocalityBonus: this.getValue(editor, 'suggest.localityBonus', true),
suggestSelection: this.getValue(editor, 'suggestSelection', 'recentlyUsed'),
wordBasedSuggestions: this.getValue(editor, 'wordBasedSuggestions', true),
parameterHintsEnabled: this.getValue(editor, 'parameterHints.enabled', true)
}
};
}
protected isDark(): Promise<boolean> {
return this.themeIsDarkPromise ? this.themeIsDarkPromise.promise : Promise.resolve(false);
}
protected async loadWebPanel(cwd: string, webViewPanel?: WebviewPanel) {
// Make not disposed anymore
this.disposed = false;
// Setup our init promise for the web panel. We use this to make sure we're in sync with our
// react control.
this.webPanelInit = this.webPanelInit ? this.webPanelInit : createDeferred();
// Setup a promise that will wait until the webview passes back
// a message telling us what them is in use
this.themeIsDarkPromise = this.themeIsDarkPromise ? this.themeIsDarkPromise : createDeferred<boolean>();
// Load our actual web panel
traceInfo(`Loading web panel. Panel is ${this.webPanel ? 'set' : 'notset'}`);
// Create our web panel (it's the UI that shows up for the history)
if (this.webPanel === undefined) {
const resource = await this.getOwningResource();
// Get our settings to pass along to the react control
const settings = await this.generateDataScienceExtraSettings();
const insiders = this.configService.getSettings(resource).insidersChannel;
traceInfo('Loading web view...');
let startHttpServer = false;
if (typeof settings.useWebViewServer === 'boolean') {
// Always allow user to turn this feature on/off via settings.
startHttpServer = settings.useWebViewServer === true;
} else {
// Determine if we should start an HTTP server or not based on if in the insider's channel or
// if it's forced on.
startHttpServer = this.useWebViewServer || insiders !== 'off';
}
traceWarning(`startHttpServer=${startHttpServer}, will not be used. Temporarily turned off`);
// Use this script to create our web view panel. It should contain all of the necessary
// script to communicate with this class.
this.webPanel = await this.provider.create({
viewColumn: this.viewColumn,
listener: this.messageListener,
title: this.title,
rootPath: this.rootPath,
scripts: this.scripts,
settings,
startHttpServer: false,
cwd,
webViewPanel
});
traceInfo('Web view created.');
}
}
private getValue<T>(workspaceConfig: WorkspaceConfiguration, section: string, defaultValue: T): T {
if (workspaceConfig) {
return workspaceConfig.get(section, defaultValue);
}
return defaultValue;
}
private webPanelViewStateChanged = (webPanel: IWebPanel) => {
const visible = webPanel.isVisible();
const active = webPanel.isActive();
const current = { visible, active };
const previous = { visible: this.viewState.visible, active: this.viewState.active };
this.viewState.visible = visible;
this.viewState.active = active;
this.onViewStateChanged({ current, previous });
};
@captureTelemetry(Telemetry.WebviewStyleUpdate)
private async handleCssRequest(request: IGetCssRequest): Promise<void> {
const settings = await this.generateDataScienceExtraSettings();
const requestIsDark = settings.ignoreVscodeTheme ? false : request.isDark;
this.setTheme(requestIsDark);
const isDark = settings.ignoreVscodeTheme
? false
: await this.themeFinder.isThemeDark(settings.extraSettings.theme);
const resource = await this.getOwningResource();
const css = await this.cssGenerator.generateThemeCss(resource, requestIsDark, settings.extraSettings.theme);
return this.postMessageInternal(CssMessages.GetCssResponse, {
css,
theme: settings.extraSettings.theme,
knownDark: isDark
});
}
@captureTelemetry(Telemetry.WebviewMonacoStyleUpdate)
private async handleMonacoThemeRequest(request: IGetMonacoThemeRequest): Promise<void> {
const settings = await this.generateDataScienceExtraSettings();
const isDark = settings.ignoreVscodeTheme ? false : request.isDark;
this.setTheme(isDark);
const resource = await this.getOwningResource();
const monacoTheme = await this.cssGenerator.generateMonacoTheme(resource, isDark, settings.extraSettings.theme);
return this.postMessageInternal(CssMessages.GetMonacoThemeResponse, { theme: monacoTheme });
}
// tslint:disable-next-line:no-any
private webPanelRendered() {
if (this.webPanelInit && !this.webPanelInit.resolved) {
// Send telemetry for startup
sendTelemetryEvent(Telemetry.WebviewStartup, this.startupStopwatch.elapsedTime, { type: this.title });
// Resolve our started promise. This means the webpanel is ready to go.
this.webPanelInit.resolve();
traceInfo('Web view react rendered');
}
}
// Post a message to our webpanel and update our new datascience settings
private onPossibleSettingsChange = async (event: ConfigurationChangeEvent) => {
if (
event.affectsConfiguration('workbench.colorTheme') ||
event.affectsConfiguration('editor.fontSize') ||
event.affectsConfiguration('editor.fontFamily') ||
event.affectsConfiguration('editor.cursorStyle') ||
event.affectsConfiguration('editor.cursorBlinking') ||
event.affectsConfiguration('editor.autoClosingBrackets') ||
event.affectsConfiguration('editor.autoClosingQuotes') ||
event.affectsConfiguration('editor.autoSurround') ||
event.affectsConfiguration('editor.autoIndent') ||
event.affectsConfiguration('editor.scrollBeyondLastLine') ||
event.affectsConfiguration('editor.fontLigatures') ||
event.affectsConfiguration('editor.scrollbar.verticalScrollbarSize') ||
event.affectsConfiguration('editor.scrollbar.horizontalScrollbarSize') ||
event.affectsConfiguration('files.autoSave') ||
event.affectsConfiguration('files.autoSaveDelay') ||
event.affectsConfiguration('python.dataScience.enableGather')
) {
// See if the theme changed
const newSettings = await this.generateDataScienceExtraSettings();
if (newSettings) {
const dsSettings = JSON.stringify(newSettings);
this.postMessageInternal(SharedMessages.UpdateSettings, dsSettings).ignoreErrors();
}
}
};
// Post a message to our webpanel and update our new datascience settings
private onDataScienceSettingsChanged = async () => {
// Stringify our settings to send over to the panel
const dsSettings = JSON.stringify(await this.generateDataScienceExtraSettings());
this.postMessageInternal(SharedMessages.UpdateSettings, dsSettings).ignoreErrors();
};
}