forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebViewHost.ts
More file actions
269 lines (232 loc) · 12 KB
/
webViewHost.ts
File metadata and controls
269 lines (232 loc) · 12 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
// 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, WorkspaceConfiguration } from 'vscode';
import { IWebPanel, IWebPanelMessageListener, IWebPanelProvider, IWorkspaceService } from '../common/application/types';
import { traceInfo } from '../common/logger';
import { IConfigurationService, IDisposable } from '../common/types';
import { createDeferred, Deferred } from '../common/utils/async';
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 } from './types';
@injectable() // For some reason this is necessary to get the class hierarchy to work.
export class WebViewHost<IMapping> implements IDisposable {
protected viewState : { visible: boolean; active: boolean } = { visible: false, active: false };
private isDisposed: boolean = false;
private webPanel: IWebPanel | undefined;
private webPanelInit: Deferred<void>;
private messageListener: IWebPanelMessageListener;
private themeChangeHandler: IDisposable | undefined;
private settingsChangeHandler: IDisposable | undefined;
private themeIsDarkPromise: Deferred<boolean>;
private startupStopwatch = new StopWatch();
constructor(
@unmanaged() private configService: IConfigurationService,
@unmanaged() private provider: IWebPanelProvider,
@unmanaged() private cssGenerator: ICodeCssGenerator,
@unmanaged() protected themeFinder: IThemeFinder,
@unmanaged() private workspaceService: IWorkspaceService,
// tslint:disable-next-line:no-any
@unmanaged() messageListenerCtor: (callback: (message: string, payload: any) => void, viewChanged: (panel: IWebPanel) => void, disposed: () => void) => IWebPanelMessageListener,
@unmanaged() private mainScriptPath: string,
@unmanaged() private title: string,
@unmanaged() private viewColumn: ViewColumn
) {
// Create our message listener for our web panel.
this.messageListener = messageListenerCtor(this.onMessage.bind(this), this.onViewStateChanged.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().onDidChange(this.onDataScienceSettingsChanged.bind(this));
// Setup our init promise for the web panel. We use this to make sure we're in sync with our
// react control.
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 = createDeferred<boolean>();
// Load our actual web panel
this.loadWebPanel();
}
public async show(preserveFocus: boolean): Promise<void> {
if (!this.isDisposed) {
// Then show our web panel.
if (this.webPanel) {
await this.webPanel.show(preserveFocus);
}
}
}
public dispose() {
if (!this.isDisposed) {
this.isDisposed = 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;
}
}
}
public setTitle(newTitle: string) {
if (!this.isDisposed && this.webPanel) {
this.webPanel.title = newTitle;
}
}
//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 activating() : Promise<void> {
return Promise.resolve();
}
// tslint:disable-next-line:no-any
protected async postMessageInternal(type: string, payload?: any) : Promise<void> {
if (this.webPanel) {
// 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 generateDataScienceExtraSettings() : IDataScienceExtraSettings {
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().datascience,
extraSettings: {
editorCursor: this.getValue(editor, 'cursorStyle', 'line'),
editorCursorBlink: this.getValue(editor, 'cursorBlinking', 'blink'),
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.promise;
}
private getValue<T>(workspaceConfig: WorkspaceConfiguration, section: string, defaultValue: T) : T {
if (workspaceConfig) {
return workspaceConfig.get(section, defaultValue);
}
return defaultValue;
}
private onViewStateChanged = (webPanel: IWebPanel) => {
const oldActive = this.viewState.active;
this.viewState.active = webPanel.isActive();
this.viewState.visible = webPanel.isVisible();
// See if suddenly becoming active or not
if (!oldActive && this.viewState.active) {
this.activating().ignoreErrors();
}
}
@captureTelemetry(Telemetry.WebviewStyleUpdate)
private async handleCssRequest(request: IGetCssRequest) : Promise<void> {
if (!this.themeIsDarkPromise.resolved) {
this.themeIsDarkPromise.resolve(request.isDark);
} else {
this.themeIsDarkPromise = createDeferred<boolean>();
this.themeIsDarkPromise.resolve(request.isDark);
}
const settings = this.generateDataScienceExtraSettings();
const isDark = await this.themeFinder.isThemeDark(settings.extraSettings.theme);
const css = await this.cssGenerator.generateThemeCss(request.isDark, 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> {
if (!this.themeIsDarkPromise.resolved) {
this.themeIsDarkPromise.resolve(request.isDark);
} else {
this.themeIsDarkPromise = createDeferred<boolean>();
this.themeIsDarkPromise.resolve(request.isDark);
}
const settings = this.generateDataScienceExtraSettings();
const monacoTheme = await this.cssGenerator.generateMonacoTheme(request.isDark, settings.extraSettings.theme);
return this.postMessageInternal(CssMessages.GetMonacoThemeResponse, { theme: monacoTheme });
}
// tslint:disable-next-line:no-any
private webPanelRendered() {
if (!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();
}
}
// Post a message to our webpanel and update our new datascience settings
private onPossibleSettingsChange = (event: ConfigurationChangeEvent) => {
if (event.affectsConfiguration('workbench.colorTheme') ||
event.affectsConfiguration('editor.cursorStyle') ||
event.affectsConfiguration('editor.cursorBlinking')) {
// See if the theme changed
const newSettings = 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 = () => {
// Stringify our settings to send over to the panel
const dsSettings = JSON.stringify(this.generateDataScienceExtraSettings());
this.postMessageInternal(SharedMessages.UpdateSettings, dsSettings).ignoreErrors();
}
private loadWebPanel() {
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) {
// Get our settings to pass along to the react control
const settings = this.generateDataScienceExtraSettings();
traceInfo('Loading web view...');
// Use this script to create our web view panel. It should contain all of the necessary
// script to communicate with this class.
this.webPanel = this.provider.create(this.viewColumn, this.messageListener, this.title, this.mainScriptPath, '', settings);
traceInfo('Web view created.');
}
}
}