-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathmemory-webview-main.ts
417 lines (367 loc) · 21.6 KB
/
memory-webview-main.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
/********************************************************************************
* Copyright (C) 2022 Ericsson, Arm and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the Eclipse
* Public License v. 2.0 are satisfied: GNU General Public License, version 2
* with the GNU Classpath Exception which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
********************************************************************************/
import * as vscode from 'vscode';
import { Messenger } from 'vscode-messenger';
import { WebviewIdMessageParticipant } from 'vscode-messenger-common';
import { isVariablesContext } from '../common/external-views';
import * as manifest from '../common/manifest';
import { VariableRange } from '../common/memory-range';
import {
ApplyMemoryResult,
applyMemoryType,
getVariablesType,
getWebviewSelectionType,
logMessageType,
MemoryOptions,
memoryWrittenType,
ReadMemoryArguments,
ReadMemoryResult,
readMemoryType,
readyType,
Session,
SessionContext,
sessionContextChangedType,
sessionsChangedType,
setMemoryViewSettingsType,
setOptionsType,
setSessionType,
setTitleType,
showAdvancedOptionsType,
StoreMemoryArguments,
storeMemoryType,
WebviewSelection,
WriteMemoryArguments,
WriteMemoryResult,
writeMemoryType,
} from '../common/messaging';
import { MemoryDisplaySettings, MemoryDisplaySettingsContribution, MemoryViewSettings, ScrollingBehavior } from '../common/webview-configuration';
import { getVisibleColumns, isWebviewVariableContext, WebviewContext } from '../common/webview-context';
import { AddressPaddingOptions } from '../webview/utils/view-types';
import { outputChannelLogger } from './logger';
import type { MemoryProvider } from './memory-provider';
import type { MemoryProviderManager } from './memory-provider-manager';
import type { MemoryStorage } from './memory-storage';
import { isSessionEvent, SessionEvent, SessionTracker } from './session-tracker';
const CONFIGURABLE_COLUMNS = [
manifest.CONFIG_SHOW_ASCII_COLUMN,
manifest.CONFIG_SHOW_VARIABLES_COLUMN,
];
export class MemoryWebview implements vscode.CustomReadonlyEditorProvider {
public static ViewType = `${manifest.PACKAGE_NAME}.memory`;
public static ShowCommandType = `${manifest.PACKAGE_NAME}.show`;
public static VariableCommandType = `${manifest.PACKAGE_NAME}.show-variable`;
public static GoToValueCommandType = `${manifest.PACKAGE_NAME}.go-to-value`;
public static ToggleAsciiColumnCommandType = `${manifest.PACKAGE_NAME}.toggle-ascii-column`;
public static ToggleVariablesColumnCommandType = `${manifest.PACKAGE_NAME}.toggle-variables-column`;
public static ToggleRadixPrefixCommandType = `${manifest.PACKAGE_NAME}.toggle-radix-prefix`;
public static ResetDisplayOptionsToDefaultsType = `${manifest.PACKAGE_NAME}.reset-display-options`;
public static ResetDisplayOptionsToDebuggerDefaultsType = `${manifest.PACKAGE_NAME}.reset-display-options-to-debugger-defaults`;
public static ShowAdvancedDisplayConfigurationCommandType = `${manifest.PACKAGE_NAME}.show-advanced-display-options`;
public static GetWebviewSelectionCommandType = `${manifest.PACKAGE_NAME}.get-webview-selection`;
protected messenger: Messenger;
protected panelIndices: number = 1;
protected participantSessions = new Map<WebviewIdMessageParticipant, string>();
public constructor(
protected extensionUri: vscode.Uri,
protected memoryProviderManager: MemoryProviderManager,
protected sessionTracker: SessionTracker,
protected memoryStorage: MemoryStorage) {
this.messenger = new Messenger({ ignoreHiddenViews: false });
}
public activate(context: vscode.ExtensionContext): void {
context.subscriptions.push(
vscode.window.registerCustomEditorProvider(manifest.EDITOR_NAME, this),
vscode.commands.registerCommand(MemoryWebview.ShowCommandType, () => this.show()),
vscode.commands.registerCommand(MemoryWebview.VariableCommandType, async args => {
if (isVariablesContext(args)) {
const sessionId = args.sessionId || vscode.debug.activeDebugSession?.id;
const memoryProvider = this.memoryProviderManager.getProvider(sessionId);
const memoryReference = args.variable.memoryReference ?? await memoryProvider.getAddressOfVariable(args.variable.name);
this.show({ memoryReference });
}
}),
vscode.commands.registerCommand(MemoryWebview.GoToValueCommandType, async args => {
if (isWebviewVariableContext(args) && args.variable.isPointer) {
this.show({ memoryReference: args.variable.value });
}
}),
vscode.commands.registerCommand(MemoryWebview.ToggleVariablesColumnCommandType, (ctx: WebviewContext) => {
this.toggleWebviewColumn(ctx, manifest.CONFIG_SHOW_VARIABLES_COLUMN);
}),
vscode.commands.registerCommand(MemoryWebview.ToggleAsciiColumnCommandType, (ctx: WebviewContext) => {
this.toggleWebviewColumn(ctx, manifest.CONFIG_SHOW_ASCII_COLUMN);
}),
vscode.commands.registerCommand(MemoryWebview.ToggleRadixPrefixCommandType, (ctx: WebviewContext) => {
this.setMemoryViewSettings(ctx.messageParticipant, { showRadixPrefix: !ctx.showRadixPrefix });
}),
vscode.commands.registerCommand(MemoryWebview.ShowAdvancedDisplayConfigurationCommandType, async (ctx: WebviewContext) => {
this.messenger.sendNotification(showAdvancedOptionsType, ctx.messageParticipant, undefined);
}),
vscode.commands.registerCommand(MemoryWebview.ResetDisplayOptionsToDefaultsType, (ctx: WebviewContext) => {
this.setMemoryDisplaySettings(ctx.messageParticipant, undefined, false);
}),
vscode.commands.registerCommand(MemoryWebview.ResetDisplayOptionsToDebuggerDefaultsType, (ctx: WebviewContext) => {
this.setMemoryDisplaySettings(ctx.messageParticipant);
}),
vscode.commands.registerCommand(MemoryWebview.GetWebviewSelectionCommandType, (ctx: WebviewContext) => this.getWebviewSelection(ctx.messageParticipant)),
);
};
public openCustomDocument(uri: vscode.Uri): vscode.CustomDocument {
return {
uri,
dispose: () => { }
};
}
public async resolveCustomEditor(document: vscode.CustomDocument, webviewPanel: vscode.WebviewPanel): Promise<void> {
/*
memoryReference = debugprotocol.variable.memoryReference
displayName = 'memory'
DEBUG_MEMORY_SCHEME = 'vscode-debug-memory'
sessionId = <debug session ID>
range = undefined
document.uri is:
scheme: DEBUG_MEMORY_SCHEME,
authority: sessionId,
path: '/' + encodeURIComponent(memoryReference) + `/${encodeURIComponent(displayName)}.bin`,
query: range ? `?range=${range.fromOffset}:${range.toOffset}` : undefined,
*/
const memoryReference = decodeURIComponent(document.uri.path.split('/')[1]);
await this.show({ memoryReference }, webviewPanel);
}
public async show(initialMemory?: MemoryOptions, panel?: vscode.WebviewPanel): Promise<void> {
const distPathUri = vscode.Uri.joinPath(this.extensionUri, 'dist', 'views');
const mediaPathUri = vscode.Uri.joinPath(this.extensionUri, 'media');
const codiconPathUri = vscode.Uri.joinPath(this.extensionUri, 'node_modules', '@vscode', 'codicons', 'dist');
const options = {
retainContextWhenHidden: true,
enableScripts: true, // enable scripts in the webview
localResourceRoots: [distPathUri, mediaPathUri, codiconPathUri] // restrict extension's local file access
};
if (!panel) {
panel = vscode.window.createWebviewPanel(MemoryWebview.ViewType, `Memory ${this.panelIndices++}`, vscode.ViewColumn.Active, options);
} else {
panel.webview.options = options;
}
// Set HTML content
await this.getWebviewContent(panel, initialMemory);
// Sets up an event listener to listen for messages passed from the webview view context
// and executes code based on the message that is received
this.setWebviewMessageListener(panel, initialMemory);
}
protected async getWebviewContent(panel: vscode.WebviewPanel, initialMemory?: MemoryOptions): Promise<void> {
const mainUri = panel.webview.asWebviewUri(vscode.Uri.joinPath(
this.extensionUri,
'dist',
'views',
'memory.js'
));
const cspSrc = panel.webview.cspSource;
const codiconsUri = panel.webview.asWebviewUri(vscode.Uri.joinPath(this.extensionUri, 'node_modules', '@vscode/codicons', 'dist', 'codicon.css'));
const memoryInspectorCSS = panel.webview.asWebviewUri(vscode.Uri.joinPath(this.extensionUri, 'media', 'index.css'));
panel.webview.html = `
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<meta http-equiv='Content-Security-Policy' content="default-src 'none'; font-src ${cspSrc}; style-src ${cspSrc} 'unsafe-inline'; script-src ${cspSrc};">
<script type='module' src='${mainUri}'></script>
<link href="${codiconsUri}" rel="stylesheet" />
<link href="${memoryInspectorCSS}" rel="stylesheet" />
</head>
<body>
<div id='root'></div>${initialMemory ? `<div id='initial-data' data-options='${JSON.stringify(initialMemory)}'></div>` : ''}
</body>
</html>
`;
}
protected setWebviewMessageListener(panel: vscode.WebviewPanel, options?: MemoryOptions): void {
const participant = this.messenger.registerWebviewPanel(panel);
const disposables = [
this.messenger.onNotification(readyType, () => this.ready(participant, panel), { sender: participant }),
this.messenger.onRequest(setOptionsType, newOptions => { options = { ...options, ...newOptions }; }, { sender: participant }),
this.messenger.onRequest(logMessageType, message => outputChannelLogger.info('[webview]:', message), { sender: participant }),
this.messenger.onRequest(readMemoryType, request => this.readMemory(participant, request), { sender: participant }),
this.messenger.onRequest(writeMemoryType, request => this.writeMemory(participant, request), { sender: participant }),
this.messenger.onRequest(getVariablesType, request => this.getVariables(participant, request), { sender: participant }),
this.messenger.onNotification(setTitleType, title => { panel.title = title; }, { sender: participant }),
this.messenger.onNotification(setSessionType, sessionId => this.setSession(participant, sessionId), { sender: participant }),
this.messenger.onRequest(storeMemoryType, args => this.storeMemory(participant, args), { sender: participant }),
this.messenger.onRequest(applyMemoryType, () => this.applyMemory(participant), { sender: participant }),
this.sessionTracker.onSessionEvent(event => this.handleSessionEvent(participant, event))
];
panel.onDidDispose(() => disposables.forEach(disposable => disposable.dispose()));
}
protected async setMemoryDisplaySettings(messageParticipant: WebviewIdMessageParticipant, title?: string, includeContributions: boolean = true): Promise<void> {
const defaultSettings = this.getDefaultMemoryDisplaySettings();
const settingsContribution = includeContributions ? await this.getMemoryDisplaySettingsContribution(messageParticipant) : {};
const settings = settingsContribution.settings ? { ...settingsContribution.settings, hasDebuggerDefaults: true } : {};
this.setMemoryViewSettings(messageParticipant, {
messageParticipant,
title,
...defaultSettings,
...settings,
contributionMessage: settingsContribution.message
});
}
protected async refresh(participant: WebviewIdMessageParticipant, options: MemoryOptions = {}): Promise<void> {
this.messenger.sendRequest(setOptionsType, participant, options);
}
protected setMemoryViewSettings(webviewParticipant: WebviewIdMessageParticipant, settings: Partial<MemoryViewSettings>): void {
this.messenger.sendNotification(setMemoryViewSettingsType, webviewParticipant, settings);
}
protected setSessions(webviewParticipant: WebviewIdMessageParticipant, sessions: Session[]): void {
this.messenger.sendNotification(sessionsChangedType, webviewParticipant, sessions);
}
protected setSessionContext(webviewParticipant: WebviewIdMessageParticipant, context: SessionContext): void {
this.messenger.sendNotification(sessionContextChangedType, webviewParticipant, context);
}
protected getDefaultMemoryDisplaySettings(): MemoryDisplaySettings {
const memoryInspectorSettings = vscode.workspace.getConfiguration(manifest.PACKAGE_NAME);
const bytesPerMau = memoryInspectorSettings.get<number>(manifest.CONFIG_BYTES_PER_MAU, manifest.DEFAULT_BYTES_PER_MAU);
const mausPerGroup = memoryInspectorSettings.get<number>(manifest.CONFIG_MAUS_PER_GROUP, manifest.DEFAULT_MAUS_PER_GROUP);
const groupsPerRow = memoryInspectorSettings.get<manifest.GroupsPerRowOption>(manifest.CONFIG_GROUPS_PER_ROW, manifest.DEFAULT_GROUPS_PER_ROW);
const endianness = memoryInspectorSettings.get<manifest.Endianness>(manifest.CONFIG_ENDIANNESS, manifest.DEFAULT_ENDIANNESS);
const scrollingBehavior = memoryInspectorSettings.get<ScrollingBehavior>(manifest.CONFIG_SCROLLING_BEHAVIOR, manifest.DEFAULT_SCROLLING_BEHAVIOR);
const visibleColumns = CONFIGURABLE_COLUMNS.filter(column => memoryInspectorSettings.get<boolean>(`columns.${column}`, false));
const addressPadding = AddressPaddingOptions[memoryInspectorSettings.get(manifest.CONFIG_ADDRESS_PADDING, manifest.DEFAULT_ADDRESS_PADDING)];
const addressRadix = memoryInspectorSettings.get<number>(manifest.CONFIG_ADDRESS_RADIX, manifest.DEFAULT_ADDRESS_RADIX);
const showRadixPrefix = memoryInspectorSettings.get<boolean>(manifest.CONFIG_SHOW_RADIX_PREFIX, manifest.DEFAULT_SHOW_RADIX_PREFIX);
const refreshOnStop = memoryInspectorSettings.get<manifest.RefreshOnStop>(manifest.CONFIG_REFRESH_ON_STOP, manifest.DEFAULT_REFRESH_ON_STOP);
const periodicRefresh = memoryInspectorSettings.get<manifest.PeriodicRefresh>(manifest.CONFIG_PERIODIC_REFRESH, manifest.DEFAULT_PERIODIC_REFRESH);
const periodicRefreshInterval = memoryInspectorSettings.get<number>(manifest.CONFIG_PERIODIC_REFRESH_INTERVAL, manifest.DEFAULT_PERIODIC_REFRESH_INTERVAL);
return {
bytesPerMau, mausPerGroup, groupsPerRow, endianness, scrollingBehavior,
visibleColumns, addressPadding, addressRadix, showRadixPrefix,
refreshOnStop, periodicRefresh, periodicRefreshInterval
};
}
protected async getMemoryDisplaySettingsContribution(messageParticipant: WebviewIdMessageParticipant): Promise<MemoryDisplaySettingsContribution> {
const memoryInspectorSettings = vscode.workspace.getConfiguration(manifest.PACKAGE_NAME);
const allowDebuggerOverwriteSettings = memoryInspectorSettings.get<boolean>(manifest.CONFIG_ALLOW_DEBUGGER_OVERWRITE_SETTINGS, true);
if (allowDebuggerOverwriteSettings) {
const memoryProvider = this.getMemoryProvider(messageParticipant);
return memoryProvider.getMemoryDisplaySettingsContribution();
}
return { settings: {}, message: undefined };
}
protected handleSessionEvent(participant: WebviewIdMessageParticipant, event: SessionEvent): void {
const sessionId = this.participantSessions.get(participant);
if (isSessionEvent('sessions-changed', event)) {
this.setSessions(participant, this.sessionTracker.getSessions());
// Current session may have stopped
if (!this.sessionTracker.validSession(sessionId)) {
this.participantSessions.delete(participant);
this.setSessionContext(participant, {
sessionId: undefined,
canRead: false,
canWrite: false,
stopped: false
});
}
return;
}
if (isSessionEvent('active', event)) {
// If our participanr is not associated with a session, set it
if (!this.participantSessions.has(participant)) {
const session = this.sessionTracker.assertSession(event.session?.raw.id);
this.participantSessions.set(participant, session.id);
this.setSessionContext(participant, this.createContext(session));
}
return;
}
// we are only interested in the events of the current session
if (sessionId && event.session && sessionId === event.session.raw.id) {
if (isSessionEvent('memory-written', event)) {
this.messenger.sendNotification(memoryWrittenType, participant, event.data);
} else {
this.setSessionContext(participant, this.createContext(event.session.raw));
}
}
}
protected async ready(participant: WebviewIdMessageParticipant, panel: vscode.WebviewPanel): Promise<void> {
this.setSession(participant, vscode.debug.activeDebugSession?.id);
this.setSessions(participant, this.sessionTracker.getSessions());
await this.setMemoryDisplaySettings(participant, panel.title);
}
protected async setSession(participant: WebviewIdMessageParticipant, sessionId: string | undefined): Promise<void> {
const session = this.sessionTracker.assertSession(sessionId);
this.participantSessions.set(participant, session.id);
this.setSessionContext(participant, this.createContext(session));
}
protected createContext(session: vscode.DebugSession): SessionContext {
const sessionId = session?.id;
return {
sessionId,
canRead: !!this.sessionTracker.hasDebugCapability(session, 'supportsReadMemoryRequest'),
canWrite: !!this.sessionTracker.hasDebugCapability(session, 'supportsWriteMemoryRequest'),
stopped: this.sessionTracker.isStopped(session)
};
}
protected async readMemory(participant: WebviewIdMessageParticipant, request: ReadMemoryArguments): Promise<ReadMemoryResult> {
const memoryProvider = this.getMemoryProvider(participant);
try {
return await memoryProvider.readMemory(request);
} catch (err) {
this.logError('Error fetching memory', err);
}
}
protected async writeMemory(participant: WebviewIdMessageParticipant, request: WriteMemoryArguments): Promise<WriteMemoryResult> {
const memoryProvider = this.getMemoryProvider(participant);
try {
return await memoryProvider.writeMemory(request);
} catch (err) {
this.logError('Error writing memory', err);
}
}
protected async getVariables(participant: WebviewIdMessageParticipant, request: ReadMemoryArguments): Promise<VariableRange[]> {
const memoryProvider = this.getMemoryProvider(participant);
try {
return await memoryProvider.getVariables(request);
} catch (err) {
this.logError('Error fetching variables', err);
return [];
}
}
protected getWebviewSelection(webviewParticipant: WebviewIdMessageParticipant): Promise<WebviewSelection> {
return this.messenger.sendRequest(getWebviewSelectionType, webviewParticipant, undefined);
}
protected toggleWebviewColumn(ctx: WebviewContext, column: string): void {
const visibleColumns = getVisibleColumns(ctx);
const index = visibleColumns.indexOf(column);
if (index === -1) {
visibleColumns.push(column);
} else {
visibleColumns.splice(index, 1);
}
this.setMemoryViewSettings(ctx.messageParticipant, { visibleColumns });
}
protected async storeMemory(participant: WebviewIdMessageParticipant, args: StoreMemoryArguments): Promise<void> {
const sessionId = this.participantSessions.get(participant);
this.memoryStorage.storeMemory(sessionId, args);
}
protected async applyMemory(participant: WebviewIdMessageParticipant): Promise<ApplyMemoryResult> {
const sessionId = this.participantSessions.get(participant);
return this.memoryStorage.applyMemory(sessionId);
}
protected logError(msg: string, err: unknown): void {
outputChannelLogger.error(msg, err instanceof Error ? `: ${err.message}\n${err.stack}` : '');
}
protected getMemoryProvider(messageParticipant: WebviewIdMessageParticipant): MemoryProvider {
const sessionId = this.participantSessions.get(messageParticipant);
return this.memoryProviderManager.getProvider(sessionId);
}
}