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

add copy selection as different formats and paste hexstring support #498

Merged
merged 7 commits into from
May 8, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
6 changes: 5 additions & 1 deletion media/editor/copyPaste.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,27 @@ const style = throwOnUndefinedAccessInDev(_style);
const enum Encoding {
Base64 = "base64",
Utf8 = "utf-8",
Hex = "hex",
}

const encodings = [Encoding.Utf8, Encoding.Base64];
const encodings = [Encoding.Utf8, Encoding.Base64, Encoding.Hex];

const encodingLabel: { [key in Encoding]: string } = {
[Encoding.Base64]: "Base64",
[Encoding.Utf8]: "UTF-8",
[Encoding.Hex]: "Hex",
};

const isData: { [key in Encoding]: (data: string) => boolean } = {
[Encoding.Base64]: d => base64.isValid(d),
[Encoding.Utf8]: () => true,
[Encoding.Hex]: () => true,
};

const decode: { [key in Encoding]: (data: string) => Uint8Array } = {
[Encoding.Base64]: d => base64.toUint8Array(d),
[Encoding.Utf8]: d => new TextEncoder().encode(d),
[Encoding.Hex]: d => Uint8Array.from(d.match(/.{1,2}/g)!.map(byte => parseInt(byte, 16))),
};

const EncodingOption: React.FC<{
Expand Down
9 changes: 9 additions & 0 deletions media/editor/dataDisplayContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,15 @@ export class DisplayContext {
this.setSelectionRanges([Range.inclusive(msg.startingOffset, msg.endingOffset)]);
});

registerHandler(MessageType.TriggerCopyAs, msg => {
messageHandler.sendEvent({
type: MessageType.DoCopy,
selections: this.selection.map(r => [r.start, r.end]),
asText: false,
format: msg.format,
});
});

this.selectionChangeEmitter.addListener(() => this.publishSelections());
this.hoverChangeEmitter.addListener(() => {
// publishes the new hovered byte
Expand Down
17 changes: 17 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,11 @@
"category": "%name%",
"title": "%hexEditor.selectBetweenOffsets%"
},
{
"command": "hexEditor.copyAs",
"category": "%name%",
"title": "%hexEditor.copyAs%"
},
{
"command": "hexEditor.switchEditMode",
"category": "%name%",
Expand Down Expand Up @@ -156,6 +161,13 @@
"command": "hexEditor.openFile",
"group": "navigation@1"
}
],
"webview/context": [
{
"when": "webviewId == 'hexEditor.hexedit'",
"command": "hexEditor.copyAs",
"group": "9_cutcopypaste"
}
]
},
"keybindings": [
Expand All @@ -164,6 +176,11 @@
"key": "ctrl+g",
"when": "activeCustomEditorId == hexEditor.hexedit"
},
{
"command": "hexEditor.copyAs",
"key": "alt+ctrl+c",
"when": "activeCustomEditorId == hexEditor.hexedit"
},
{
"command": "hexEditor.switchEditMode",
"key": "Insert",
Expand Down
1 change: 1 addition & 0 deletions package.nls.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"hexEditor.openFile": "Open Active File in Hex Editor",
"hexEditor.goToOffset": "Go To Offset",
"hexEditor.selectBetweenOffsets": "Select Between Offsets",
"hexEditor.copyAs": "Copy As",
lorsanta marked this conversation as resolved.
Show resolved Hide resolved
"hexEditor.switchEditMode": "Switch Edit Mode",
"dataInspectorView": "Data Inspector"
}
21 changes: 20 additions & 1 deletion shared/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export const enum MessageType {
SetSelectedCount,
PopDisplayedOffset,
DeleteAccepted,
TriggerCopyAs,
//#endregion
//#region from webview
ReadyRequest,
Expand Down Expand Up @@ -175,6 +176,22 @@ export interface DeleteAcceptedMessage {
type: MessageType.DeleteAccepted;
}

export const enum CopyFormat {
Hex = "Hex",
Literal = "Literal",
Text = "Text",
lorsanta marked this conversation as resolved.
Show resolved Hide resolved
C = "C",
Golang = "Golang",
lorsanta marked this conversation as resolved.
Show resolved Hide resolved
Java = "Java",
JSON = "JSON",
Base64 = "Base64",
}

export interface TriggerCopyAsMessage {
type: MessageType.TriggerCopyAs;
format: CopyFormat;
}

export type ToWebviewMessage =
| ReadyResponseMessage
| ReadRangeResponseMessage
Expand All @@ -188,7 +205,8 @@ export type ToWebviewMessage =
| SetEditModeMessage
| PopDisplayedOffsetMessage
| StashDisplayedOffsetMessage
| DeleteAcceptedMessage;
| DeleteAcceptedMessage
| TriggerCopyAsMessage;

export interface OpenDocumentMessage {
type: MessageType.OpenDocument;
Expand Down Expand Up @@ -254,6 +272,7 @@ export interface CopyMessage {
type: MessageType.DoCopy;
selections: [from: number, to: number][];
asText: boolean;
format?: CopyFormat;
}

export interface RequestDeletesMessage {
Expand Down
118 changes: 118 additions & 0 deletions src/copyAs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import * as base64 from "js-base64";
import * as vscode from "vscode";
import { CopyFormat, ExtensionHostMessageHandler, MessageType } from "../shared/protocol";

interface QuickPickCopyFormat extends vscode.QuickPickItem {
label: CopyFormat;
}

export const copyAs = async (messaging: ExtensionHostMessageHandler): Promise<void> => {
const formats: QuickPickCopyFormat[] = [
{ label: CopyFormat.Hex },
{ label: CopyFormat.Literal },
{ label: CopyFormat.Text },
{ label: CopyFormat.C },
{ label: CopyFormat.Golang },
{ label: CopyFormat.Java },
{ label: CopyFormat.JSON },
{ label: CopyFormat.Base64 },
];

vscode.window.showQuickPick(formats, { ignoreFocusOut: true }).then(format => {
lorsanta marked this conversation as resolved.
Show resolved Hide resolved
if (format) {
messaging.sendEvent({ type: MessageType.TriggerCopyAs, format: format["label"] });
}
});
};

export function copyAsText(buffer: Uint8Array) {
vscode.env.clipboard.writeText(new TextDecoder().decode(buffer));
}

export function copyAsHex(buffer: Uint8Array) {
vscode.env.clipboard.writeText(Buffer.from(buffer).toString("hex"));
}

export function copyAsLiteral(buffer: Uint8Array) {
let encoded: string = "";
const digits = Buffer.from(buffer)
.toString("hex")
lorsanta marked this conversation as resolved.
Show resolved Hide resolved
.match(/.{1,2}/g);
if (digits) {
encoded = "\\x" + digits.join("\\x");
}

vscode.env.clipboard.writeText(encoded);
}

export function copyAsC(buffer: Uint8Array) {
const len = buffer.length;
let content: string = "unsigned char rawData[" + len + "] =\n{";
lorsanta marked this conversation as resolved.
Show resolved Hide resolved

for (let i = 0; i < len; ++i) {
if (i % 8 == 0) {
content += "\n\t";
}
const byte = buffer[i].toString(16);
content += (byte.length < 2 ? "0x0" : "0x") + byte + ", ";
lorsanta marked this conversation as resolved.
Show resolved Hide resolved
}

content += "\n};\n";

if (/^win/.test(process.platform)) {
lorsanta marked this conversation as resolved.
Show resolved Hide resolved
content = content.replace(/\n/g, "\r\n");
}

vscode.env.clipboard.writeText(content);
}

export function copyAsGolang(buffer: Uint8Array) {
const len = buffer.length;
let content: string = "// RawData (" + len + " bytes)\n";
content += "var RawData = []byte{";

for (let i = 0; i < len; ++i) {
if (i % 8 == 0) {
content += "\n\t";
}
const byte = buffer[i].toString(16);
content += (byte.length < 2 ? "0x0" : "0x") + byte + ", ";
lorsanta marked this conversation as resolved.
Show resolved Hide resolved
}

content += "\n}\n";

if (/^win/.test(process.platform)) {
content = content.replace(/\n/g, "\r\n");
}

vscode.env.clipboard.writeText(content);
}

export function copyAsJava(buffer: Uint8Array) {
const len = buffer.length;
let content: string = "byte rawData[] =\n{";

for (let i = 0; i < len; ++i) {
if (i % 8 == 0) {
content += "\n\t";
}
const byte = buffer[i].toString(16);
content += (byte.length < 2 ? "0x0" : "0x") + byte + ", ";
}

content += "\n};\n";

if (/^win/.test(process.platform)) {
content = content.replace(/\n/g, "\r\n");
}

vscode.env.clipboard.writeText(content);
}

export function copyAsJSON(buffer: Uint8Array) {
vscode.env.clipboard.writeText(JSON.stringify(buffer));
}

export function copyAsBase64(buffer: Uint8Array) {
vscode.env.clipboard.writeText(base64.fromUint8Array(buffer));
}
28 changes: 16 additions & 12 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import TelemetryReporter from "@vscode/extension-telemetry";
import * as vscode from "vscode";
import { HexDocumentEditOp } from "../shared/hexDocumentModel";
import { copyAs } from "./copyAs";
import { DataInspectorView } from "./dataInspectorView";
import { showGoToOffset } from "./goToOffset";
import { HexEditorProvider } from "./hexEditorProvider";
Expand Down Expand Up @@ -72,24 +73,27 @@ export function activate(context: vscode.ExtensionContext): void {
}
},
);

const switchEditModeCommand = vscode.commands.registerCommand(
"hexEditor.switchEditMode",
() => {
if (registry.activeDocument) {
registry.activeDocument.editMode =
registry.activeDocument.editMode === HexDocumentEditOp.Insert
? HexDocumentEditOp.Replace
: HexDocumentEditOp.Insert;
}
},
);
const copyAsCommand = vscode.commands.registerCommand("hexEditor.copyAs", () => {
const first = registry.activeMessaging[Symbol.iterator]().next();
if (first.value) {
copyAs(first.value);
}
});
const switchEditModeCommand = vscode.commands.registerCommand("hexEditor.switchEditMode", () => {
if (registry.activeDocument) {
registry.activeDocument.editMode =
registry.activeDocument.editMode === HexDocumentEditOp.Insert
? HexDocumentEditOp.Replace
: HexDocumentEditOp.Insert;
}
});

context.subscriptions.push(new StatusEditMode(registry));
context.subscriptions.push(new StatusFocus(registry));
context.subscriptions.push(new StatusHoverAndSelection(registry));
context.subscriptions.push(goToOffsetCommand);
context.subscriptions.push(selectBetweenOffsetsCommand);
context.subscriptions.push(copyAsCommand);
context.subscriptions.push(switchEditModeCommand);
context.subscriptions.push(openWithCommand);
context.subscriptions.push(telemetryReporter);
Expand Down
50 changes: 45 additions & 5 deletions src/hexEditorProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
// Licensed under the MIT license.

import TelemetryReporter from "@vscode/extension-telemetry";
import * as base64 from "js-base64";
import * as vscode from "vscode";
import {
HexDocumentEdit,
HexDocumentEditOp,
HexDocumentEditReference,
} from "../shared/hexDocumentModel";
import {
CopyFormat,
Endianness,
ExtensionHostMessageHandler,
FromWebviewMessage,
Expand All @@ -23,6 +23,16 @@ import {
} from "../shared/protocol";
import { deserializeEdits, serializeEdits } from "../shared/serialization";
import { ILocalizedStrings, placeholder1 } from "../shared/strings";
import {
copyAsBase64,
copyAsC,
copyAsGolang,
copyAsHex,
copyAsJSON,
copyAsJava,
copyAsLiteral,
copyAsText,
} from "./copyAs";
import { DataInspectorView } from "./dataInspectorView";
import { disposeAll } from "./dispose";
import { HexDocument } from "./hexDocument";
Expand Down Expand Up @@ -364,10 +374,40 @@ export class HexEditorProvider implements vscode.CustomEditorProvider<HexDocumen
.map(s => document.readBuffer(s[0], s[1] - s[0])),
);
const flatParts = flattenBuffers(parts);
const encoded = message.asText
? new TextDecoder().decode(flatParts)
: base64.fromUint8Array(flatParts);
vscode.env.clipboard.writeText(encoded);
if (message.format !== undefined) {
switch (message.format) {
lorsanta marked this conversation as resolved.
Show resolved Hide resolved
case CopyFormat.Hex:
copyAsHex(flatParts);
break;
case CopyFormat.Literal:
copyAsLiteral(flatParts);
break;
case CopyFormat.Text:
copyAsText(flatParts);
break;
case CopyFormat.C:
copyAsC(flatParts);
break;
case CopyFormat.Golang:
copyAsGolang(flatParts);
break;
case CopyFormat.Java:
copyAsJava(flatParts);
break;
case CopyFormat.JSON:
copyAsJSON(flatParts);
break;
case CopyFormat.Base64:
copyAsBase64(flatParts);
break;
}
} else {
if (message.asText) {
lorsanta marked this conversation as resolved.
Show resolved Hide resolved
copyAsText(flatParts);
} else {
copyAsBase64(flatParts);
}
}
return;
}
case MessageType.RequestDeletes: {
Expand Down