Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Memory Table Editability #110

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions media/memory-table.css
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@
white-space: nowrap;
}

.memory-inspector-table .column-data .byte-group.editable:hover {
border-bottom: 1px dotted var(--vscode-editorHoverWidget-border);
}

/* == MoreMemorySelect == */

.bytes-select {
Expand Down
12 changes: 11 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,11 @@
"title": "Apply Memory from File",
"enablement": "memory-inspector.canWrite",
"category": "Memory"
},
{
"command": "memory-inspector.edit-current-selection",
"title": "Edit currently selected memory",
"enablement": "memory-inspector.canWrite && webviewId === memory-inspector.memory"
}
],
"menus": {
Expand Down Expand Up @@ -200,6 +205,11 @@
"command": "memory-inspector.apply-file",
"group": "display@6",
"when": "webviewId === memory-inspector.memory"
},
{
"command": "memory-inspector.edit-current-selection",
"group": "actions@1",
"when": "webviewId === memory-inspector.memory"
}
]
},
Expand Down Expand Up @@ -383,4 +393,4 @@
"extensionKind": [
"ui"
]
}
}
6 changes: 5 additions & 1 deletion src/common/memory-range.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,11 @@ export function areVariablesEqual(one: BigIntVariableRange, other: BigIntVariabl
&& one.type === other.type
&& one.value === other.value;
}

/**
* @param wordSize Size of an addressable unit in bits
*
* Computes the number of 8-bit bytes between two addresses
*/
export function toOffset(startAddress: bigint, targetAddress: bigint, wordSize: number): number {
return Number(targetAddress - startAddress) * (wordSize / 8);
}
Expand Down
1 change: 1 addition & 0 deletions src/common/messaging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export const resetMemoryViewSettingsType: NotificationType<void> = { method: 're
export const setTitleType: NotificationType<string> = { method: 'setTitle' };
export const memoryWrittenType: NotificationType<WrittenMemory> = { method: 'memoryWritten' };
export const sessionContextChangedType: NotificationType<SessionContext> = { method: 'sessionContextChanged' };
export const editSelectedMemoryType: NotificationType<void> = { method: 'editSelectedMemory' };

// Requests
export const setOptionsType: RequestType<MemoryOptions, void> = { method: 'setOptions' };
Expand Down
9 changes: 8 additions & 1 deletion src/plugin/memory-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ export class MemoryProvider {
protected readonly sessionDebugCapabilities = new Map<string, DebugProtocol.Capabilities | undefined>();
protected readonly sessionClientCapabilities = new Map<string, DebugProtocol.InitializeRequestArguments | undefined>();

/**
* Debug adapters can use the 'memory' event to indicate that the contents of a memory range has changed due to some request but do not specify which requests.
* We therefore track explicitly whether the debug adapter actually sends 'memory' events to know whether we should mimic the event ourselves.
*/
protected adapterSupportsMemoryEvent = false;

constructor(protected adapterRegistry: AdapterRegistry) {
}

Expand Down Expand Up @@ -70,6 +76,7 @@ export class MemoryProvider {
} else if (isDebugEvent('stopped', message)) {
this._onDidStopDebug.fire(session);
} else if (isDebugEvent('memory', message)) {
this.adapterSupportsMemoryEvent = true;
this._onDidWriteMemory.fire(message.body);
}
contributedTracker?.onDidSendMessage?.(message);
Expand Down Expand Up @@ -148,7 +155,7 @@ export class MemoryProvider {
public async writeMemory(args: DebugProtocol.WriteMemoryArguments): Promise<WriteMemoryResult> {
const session = this.assertCapability('supportsWriteMemoryRequest', 'write memory');
return sendRequest(session, 'writeMemory', args).then(response => {
if (!this.hasClientCapabilitiy(session, 'supportsMemoryEvent')) {
if (!this.adapterSupportsMemoryEvent || !this.hasClientCapabilitiy(session, 'supportsMemoryEvent')) {
// we only send out a custom event if we don't expect the client to handle the memory event
// since our client is VS Code we can assume that they will always support this but better to be safe
const offset = response?.offset ? (args.offset ?? 0) + response.offset : args.offset;
Expand Down
5 changes: 5 additions & 0 deletions src/plugin/memory-webview-main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { WebviewIdMessageParticipant } from 'vscode-messenger-common';
import { Endianness, VariableRange } from '../common/memory-range';
import {
applyMemoryType,
editSelectedMemoryType,
getVariablesType,
getWebviewSelectionType,
logMessageType,
Expand Down Expand Up @@ -70,6 +71,7 @@ export class MemoryWebview implements vscode.CustomReadonlyEditorProvider {
public static ToggleRadixPrefixCommandType = `${manifest.PACKAGE_NAME}.toggle-radix-prefix`;
public static ShowAdvancedDisplayConfigurationCommandType = `${manifest.PACKAGE_NAME}.show-advanced-display-options`;
public static GetWebviewSelectionCommandType = `${manifest.PACKAGE_NAME}.get-webview-selection`;
public static EditCurrentSelectionCommandType = `${manifest.PACKAGE_NAME}.edit-current-selection`;

protected messenger: Messenger;
protected refreshOnStop: RefreshEnum;
Expand Down Expand Up @@ -110,6 +112,9 @@ export class MemoryWebview implements vscode.CustomReadonlyEditorProvider {
this.messenger.sendNotification(showAdvancedOptionsType, ctx.messageParticipant, undefined);
}),
vscode.commands.registerCommand(MemoryWebview.GetWebviewSelectionCommandType, (ctx: WebviewContext) => this.getWebviewSelection(ctx.messageParticipant)),
vscode.commands.registerCommand(MemoryWebview.EditCurrentSelectionCommandType, (ctx: WebviewContext) => {
this.messenger.sendNotification(editSelectedMemoryType, ctx.messageParticipant, undefined);
})
);
};

Expand Down
200 changes: 182 additions & 18 deletions src/webview/columns/data-column.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,62 +14,131 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
********************************************************************************/

import { InputText } from 'primereact/inputtext';
import * as React from 'react';
import { HOST_EXTENSION } from 'vscode-messenger-common';
import { Memory } from '../../common/memory';
import { BigIntMemoryRange, Endianness, toOffset } from '../../common/memory-range';
import { BigIntMemoryRange, Endianness, isWithin, toHexStringWithRadixMarker, toOffset } from '../../common/memory-range';
import { writeMemoryType } from '../../common/messaging';
import type { MemorySizeOptions } from '../components/memory-table';
import { decorationService } from '../decorations/decoration-service';
import { FullNodeAttributes } from '../utils/view-types';
import { EventEmitter } from '../utils/events';
import { Disposable, FullNodeAttributes } from '../utils/view-types';
import { characterWidthInContainer, elementInnerWidth } from '../utils/window';
import { messenger } from '../view-messenger';
import { ColumnContribution, TableRenderOptions } from './column-contribution-service';

function getSelectionEdit(): BigIntMemoryRange | undefined {
const selectionRange = document.getSelection();
if (!selectionRange) { return; }
const anchorWord = selectionRange.anchorNode?.parentElement?.closest<HTMLSpanElement>('.single-word');
const focusWord = selectionRange.focusNode?.parentElement?.closest<HTMLSpanElement>('.single-word');
if (!anchorWord?.dataset.address || !focusWord?.dataset.address) { return; }
const anchorAddress = BigInt(anchorWord.dataset.address);
const focusAddress = BigInt(focusWord.dataset.address);
const startAddress = anchorAddress <= focusAddress ? anchorAddress : focusAddress;
const endAddress = (anchorAddress < focusAddress ? focusAddress : anchorAddress) + 1n;
return { startAddress, endAddress };
}

export class DataColumn implements ColumnContribution {
static CLASS_NAME = 'column-data';
private static onEditRequestedEmitter = new EventEmitter<BigIntMemoryRange>();
public static onEditRequested = this.onEditRequestedEmitter.event;

readonly id = 'data';
readonly className = DataColumn.CLASS_NAME;
readonly label = 'Data';
readonly priority = 1;

protected byteGroupStyle: React.CSSProperties = {
marginRight: `${DataColumn.Styles.MARGIN_RIGHT_PX}px`
};
static editCurrentSelection(): void {
const toEdit = getSelectionEdit();
if (!toEdit) { return; }
this.onEditRequestedEmitter.fire(toEdit);
}

render(range: BigIntMemoryRange, memory: Memory, options: TableRenderOptions): React.ReactNode {
return this.renderGroups(range, memory, options);
return <EditableDataColumnRow range={range} memory={memory} options={options} />;
}
}

export interface EditableDataColumnRowProps {
range: BigIntMemoryRange;
memory: Memory;
options: TableRenderOptions;
}

export interface EditableDataColumnRowState {
editedRange?: BigIntMemoryRange;
}

export class EditableDataColumnRow extends React.Component<EditableDataColumnRowProps, EditableDataColumnRowState> {
state: EditableDataColumnRowState = {};
protected inputText = React.createRef<HTMLInputElement>();
protected toDisposeOnUnmount?: Disposable;

componentDidMount(): void {
this.toDisposeOnUnmount = DataColumn.onEditRequested(this.setSelectionEdit);
}

componentWillUnmount(): void {
this.toDisposeOnUnmount?.dispose();
}

render(): React.ReactNode {
return this.renderGroups();
}

protected renderGroups(range: BigIntMemoryRange, memory: Memory, options: TableRenderOptions): React.ReactNode {
protected renderGroups(): React.ReactNode {
const { range, options, memory } = this.props;
const groups = [];
let words: React.ReactNode[] = [];
for (let address = range.startAddress; address < range.endAddress; address++) {
let address = range.startAddress;
let groupStartAddress = address;
while (address < range.endAddress) {
words.push(this.renderWord(memory, options, address));
const next = address + 1n;
if (words.length % options.wordsPerGroup === 0) {
this.applyEndianness(words, options);
const isLast = address + 1n >= range.endAddress;
const style: React.CSSProperties | undefined = isLast ? undefined : this.byteGroupStyle;
groups.push(<span className='byte-group hoverable' data-column='data' style={style} key={address.toString(16)}>{words}</span>);
const isLast = next >= range.endAddress;
const style: React.CSSProperties | undefined = isLast ? undefined : DataColumn.Styles.byteGroupStyle;
groups.push(this.renderGroup(words, groupStartAddress, next, style));
groupStartAddress = next;
words = [];
}
address = next;
}
if (words.length) { groups.push(<span className='byte-group hoverable' data-column='data' key={(range.endAddress - BigInt(words.length)).toString(16)}>{words}</span>); }
if (words.length) { groups.push(this.renderGroup(words, groupStartAddress, range.endAddress)); }
return groups;
}

protected renderGroup(words: React.ReactNode, startAddress: bigint, endAddress: bigint, style?: React.CSSProperties): React.ReactNode {
return <span
className='byte-group hoverable'
data-column='data'
data-range={`${startAddress}-${endAddress}`}
style={style}
key={startAddress.toString(16)}
onDoubleClick={this.setGroupEdit}
>
{words}
</span>;
}

protected renderWord(memory: Memory, options: TableRenderOptions, currentAddress: bigint): React.ReactNode {
if (currentAddress === this.state.editedRange?.startAddress) {
return this.renderEditingGroup(this.state.editedRange);
} else if (this.state.editedRange && isWithin(currentAddress, this.state.editedRange)) {
return;
}
const initialOffset = toOffset(memory.address, currentAddress, options.bytesPerWord * 8);
const finalOffset = initialOffset + options.bytesPerWord;
const bytes: React.ReactNode[] = [];
for (let i = initialOffset; i < finalOffset; i++) {
bytes.push(this.renderEightBits(memory, currentAddress, i));
}
this.applyEndianness(bytes, options);
return <span className='single-word' key={currentAddress.toString(16)}>{bytes}</span>;
}

protected applyEndianness<T>(group: T[], options: TableRenderOptions): T[] {
// Assume data from the DAP comes in Big Endian so we need to revert the order if we use Little Endian
return options.endianness === Endianness.Big ? group : group.reverse();
return <span className='single-word' data-address={currentAddress.toString()} key={currentAddress.toString(16)}>{bytes}</span>;
}

protected renderEightBits(memory: Memory, currentAddress: bigint, offset: number): React.ReactNode {
Expand All @@ -92,11 +161,106 @@ export class DataColumn implements ColumnContribution {
content: (memory.bytes[offset] ?? 0).toString(16).padStart(2, '0')
};
}

protected applyEndianness<T>(group: T[], options: TableRenderOptions): T[] {
// Assume data from the DAP comes in Big Endian so we need to revert the order if we use Little Endian
return options.endianness === Endianness.Big ? group : group.reverse();
}

protected renderEditingGroup(editedRange: BigIntMemoryRange): React.ReactNode {
const isLast = editedRange.endAddress === this.props.range.endAddress;
const bitsPerWord = this.props.options.bytesPerWord * 8;
const startOffset = toOffset(this.props.memory.address, editedRange.startAddress, bitsPerWord);
const numBytes = toOffset(editedRange.startAddress, editedRange.endAddress, bitsPerWord);
const characters = numBytes * 2;
const defaultValue = Array.from(this.props.memory.bytes.slice(startOffset, startOffset + numBytes)).map(byte => byte.toString(16).padStart(2, '0')).join('');

const style: React.CSSProperties = {
...decorationService.getDecoration(editedRange.startAddress)?.style,
width: `calc(${characters}ch + 10px)`,
padding: '0 4px',
marginRight: isLast ? undefined : DataColumn.Styles.byteGroupStyle.marginRight,
minHeight: 'unset',
border: '1px solid var(--vscode-inputOption-activeBorder)',
background: 'unset'
};

return <InputText key={editedRange.startAddress.toString(16)}
ref={this.inputText}
maxLength={characters}
defaultValue={defaultValue}
onBlur={this.onBlur}
onKeyDown={this.onKeyDown}
autoFocus
style={style}
/>;
}

protected onBlur: React.FocusEventHandler<HTMLInputElement> = () => {
this.submitChanges();
};

protected onKeyDown: React.KeyboardEventHandler<HTMLInputElement> = event => {
switch (event.key) {
case 'Escape': {
this.disableEdit();
break;
}
case 'Enter': {
this.submitChanges();
}
}
event.stopPropagation();
};

protected setGroupEdit: React.MouseEventHandler<HTMLSpanElement> = event => {
event.stopPropagation();
const range = event.currentTarget.dataset.range;
if (!range) { return; }
const [startAddress, endAddress] = range.split('-').map(BigInt);
this.setState({ editedRange: { startAddress, endAddress } });
};

protected setSelectionEdit = (editedRange: BigIntMemoryRange): void => {
if (isWithin(editedRange.startAddress, this.props.range)) {
const endAddress = editedRange.endAddress <= this.props.range.endAddress ? editedRange.endAddress : this.props.range.endAddress;
this.setState({ editedRange: { startAddress: editedRange.startAddress, endAddress } });
}
};

protected disableEdit(): void {
this.setState({ editedRange: undefined });
}

protected async submitChanges(): Promise<void> {
if (!this.inputText.current || !this.state.editedRange) { return; }
const newData = this.processData(this.inputText.current.value, this.state.editedRange);
const converted = Buffer.from(newData, 'hex').toString('base64');
await messenger.sendRequest(writeMemoryType, HOST_EXTENSION, {
memoryReference: toHexStringWithRadixMarker(this.state.editedRange.startAddress),
data: converted
}).catch(() => { });
this.disableEdit();
}

protected processData(data: string, editedRange: BigIntMemoryRange): string {
const characters = toOffset(editedRange.startAddress, editedRange.endAddress, this.props.options.bytesPerWord * 8) * 2;
// Revert Endianness
if (this.props.options.endianness === Endianness.Little) {
const chunks = data.padStart(characters, '0').match(/.{1,2}/g) || [];
return chunks.reverse().join('');
}

return data.padStart(characters, '0');
}
}

export namespace DataColumn {
export namespace Styles {
export const MARGIN_RIGHT_PX = 2;
export const byteGroupStyle: React.CSSProperties = {
marginRight: `${DataColumn.Styles.MARGIN_RIGHT_PX}px`
};
}

/**
Expand Down
2 changes: 2 additions & 0 deletions src/webview/memory-webview-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { createMemoryFromRead, Memory } from '../common/memory';
import { BigIntMemoryRange, doOverlap, Endianness, getAddressLength, getAddressString, WrittenMemory } from '../common/memory-range';
import {
applyMemoryType,
editSelectedMemoryType,
getWebviewSelectionType,
logMessageType,
MemoryOptions,
Expand Down Expand Up @@ -135,6 +136,7 @@ class App extends React.Component<{}, MemoryAppState> {
messenger.onRequest(getWebviewSelectionType, () => this.getWebviewSelection());
messenger.onNotification(showAdvancedOptionsType, () => this.showAdvancedOptions());
messenger.sendNotification(readyType, HOST_EXTENSION, undefined);
messenger.onNotification(editSelectedMemoryType, () => DataColumn.editCurrentSelection());
}

public componentDidUpdate(_: {}, prevState: MemoryAppState): void {
Expand Down
Loading