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 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
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: 7 additions & 2 deletions media/editor/dataDisplay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@
import React, { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useRecoilValue, useSetRecoilState } from "recoil";
import { EditRangeOp, HexDocumentEditOp } from "../../shared/hexDocumentModel";
import { DeleteAcceptedMessage, InspectorLocation, MessageType } from "../../shared/protocol";
import {
CopyFormat,
DeleteAcceptedMessage,
InspectorLocation,
MessageType,
} from "../../shared/protocol";
import { Range } from "../../shared/util/range";
import { PastePopup } from "./copyPaste";
import _style from "./dataDisplay.css";
Expand Down Expand Up @@ -288,7 +293,7 @@ export const DataDisplay: React.FC = () => {
select.messageHandler.sendEvent({
type: MessageType.DoCopy,
selections: ctx.selection.map(r => [r.start, r.end]),
asText: ctx.focusedElement.char,
format: ctx.focusedElement.char ? CopyFormat.Utf8 : CopyFormat.Base64,
});
}
});
Expand Down
8 changes: 8 additions & 0 deletions media/editor/dataDisplayContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,14 @@ 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]),
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 @@ -178,6 +183,13 @@
"group": "9_cutcopypaste",
"when": "hexEditor:isActive"
}
],
"webview/context": [
{
"when": "webviewId == 'hexEditor.hexedit'",
"command": "hexEditor.copyAs",
"group": "9_cutcopypaste"
}
]
},
"keybindings": [
Expand All @@ -186,6 +198,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...",
"hexEditor.switchEditMode": "Switch Edit Mode",
"hexEditor.copyOffsetAsDec": "Copy Offset as Decimal",
"hexEditor.copyOffsetAsHex": "Copy Offset as Hex",
Expand Down
22 changes: 20 additions & 2 deletions 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",
Utf8 = "UTF-8",
C = "C",
Go = "Go",
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 @@ -253,7 +271,7 @@ export interface PasteMessage {
export interface CopyMessage {
type: MessageType.DoCopy;
selections: [from: number, to: number][];
asText: boolean;
format: CopyFormat;
}

export interface RequestDeletesMessage {
Expand Down
130 changes: 130 additions & 0 deletions src/copyAs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
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 copyAsFormats: { [K in CopyFormat]: (buffer: Uint8Array, filename: string) => void } =
{
[CopyFormat.Hex]: copyAsHex,
[CopyFormat.Literal]: copyAsLiteral,
[CopyFormat.Utf8]: copyAsText,
[CopyFormat.C]: copyAsC,
[CopyFormat.Go]: copyAsGo,
[CopyFormat.Java]: copyAsJava,
[CopyFormat.JSON]: copyAsJSON,
[CopyFormat.Base64]: copyAsBase64,
};

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

vscode.window.showQuickPick(formats).then(format => {
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) {
const hexString = Array.from(buffer, b => b.toString(16).padStart(2, "0")).join("");
vscode.env.clipboard.writeText(hexString);
}

export function copyAsLiteral(buffer: Uint8Array) {
let encoded: string = "";
const hexString = Array.from(buffer, b => b.toString(16).padStart(2, "0")).join("");
const digits = hexString.match(/.{1,2}/g);
if (digits) {
encoded = "\\x" + digits.join("\\x");
}

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

export function copyAsC(buffer: Uint8Array, filename: string) {
const len = buffer.length;
let content: string = `unsigned char ${filename}[${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).padStart(2, "0");
content += `0x${byte}, `;
}

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

if (typeof process !== "undefined" && process.platform === "win32") {
content = content.replace(/\n/g, "\r\n");
}

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

export function copyAsGo(buffer: Uint8Array, filename: string) {
const len = buffer.length;
let content: string = `// ${filename} (${len} bytes)\n`;
content += `var ${filename} = []byte{`;

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

content += "\n}\n";

if (typeof process !== "undefined" && process.platform === "win32") {
content = content.replace(/\n/g, "\r\n");
}

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

export function copyAsJava(buffer: Uint8Array, filename: string) {
const len = buffer.length;
let content: string = `byte ${filename}[] =\n{`;

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

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

if (typeof process !== "undefined" && process.platform === "win32") {
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));
}
10 changes: 10 additions & 0 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 @@ -73,6 +74,14 @@ export function activate(context: vscode.ExtensionContext): void {
},
);

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 =
Expand Down Expand Up @@ -105,6 +114,7 @@ export function activate(context: vscode.ExtensionContext): void {
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
13 changes: 7 additions & 6 deletions src/hexEditorProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// Licensed under the MIT license.

import TelemetryReporter from "@vscode/extension-telemetry";
import * as base64 from "js-base64";
import * as vscode from "vscode";
import {
HexDocumentEdit,
Expand All @@ -23,12 +22,13 @@ import {
} from "../shared/protocol";
import { deserializeEdits, serializeEdits } from "../shared/serialization";
import { ILocalizedStrings, placeholder1 } from "../shared/strings";
import { copyAsFormats } from "./copyAs";
import { DataInspectorView } from "./dataInspectorView";
import { disposeAll } from "./dispose";
import { HexDocument } from "./hexDocument";
import { HexEditorRegistry } from "./hexEditorRegistry";
import { ISearchRequest, LiteralSearchRequest, RegexSearchRequest } from "./searchRequest";
import { flattenBuffers, getCorrectArrayBuffer, randomString } from "./util";
import { flattenBuffers, getBaseName, getCorrectArrayBuffer, randomString } from "./util";

const defaultEditorSettings: Readonly<IEditorSettings> = {
columnWidth: 16,
Expand Down Expand Up @@ -364,10 +364,11 @@ 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);

const filenameWoutExt = getBaseName(document.uri.path);

copyAsFormats[message.format](flatParts, filenameWoutExt);

return;
}
case MessageType.RequestDeletes: {
Expand Down
6 changes: 6 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,9 @@ export const flattenBuffers = (buffers: readonly Uint8Array[]): Uint8Array => {

return target;
};

export const getBaseName = (path: string): string => {
let filename = path.split("/").pop()!;
filename = filename.substring(0, filename.lastIndexOf(".")) || filename;
return filename.replace(/[^a-z0-9]/gi, "");
};
Loading