Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ContextMenuImage.ts

107 lines3.8 KB

1import * as Electron from "electron";
2import { sourceDimensions } from "../preview/FaviconCapture.ts";
3​
4const MAX_IMAGE_BYTES = 32 * 1024 * 1024;
5// The clipboard is shared, so only the most recent Copy Image may write to it.
6let latestCopy = 0;
7​
8export async function copyContextMenuImage(
9 contents: Electron.WebContents,
10 params: Electron.ContextMenuParams,
11): Promise<void> {
12 const frame = params.frame;
13 if (contents.isDestroyed() || !frame || frame.isDestroyed()) return;
14 const copy = ++latestCopy;
15 if (frame === contents.mainFrame) {
16 contents.copyImageAt(params.x, params.y);
17 return;
18 }
19​
20 const url = new URL(params.srcURL);
21 if (
22 !["https:", "http:", "data:"].includes(url.protocol) ||
23 url.username ||
24 url.password ||
25 (url.protocol === "data:" && params.srcURL.length > MAX_IMAGE_BYTES * 3)
26 ) {
27 throw new Error("Unsupported image URL");
28 }
29 const fetchImage = url.protocol === "data:" ? globalThis.fetch : Electron.net.fetch;
30 const response = await fetchImage(url.href, {
31 credentials: "omit",
32 redirect: "error",
33 signal: AbortSignal.timeout(10_000),
34 });
35 if (!response.ok || Number(response.headers.get("content-length")) > MAX_IMAGE_BYTES) {
36 await response.body?.cancel();
37 throw new Error("Image request failed or exceeded the size limit");
38 }
39 if (!response.body) throw new Error("Image response has no body");
40​
41 const reader = response.body.getReader();
42 const chunks: Uint8Array[] = [];
43 let byteLength = 0;
44 try {
45 while (true) {
46 const chunk = await reader.read();
47 if (chunk.done) break;
48 byteLength += chunk.value.byteLength;
49 if (byteLength > MAX_IMAGE_BYTES) {
50 await reader.cancel();
51 throw new Error("Image exceeded the size limit");
52 }
53 chunks.push(chunk.value);
54 }
55 } finally {
56 reader.releaseLock();
57 }
58​
59 const bytes = Buffer.concat(chunks, byteLength);
60 const dimensions = sourceDimensions(bytes, MAX_IMAGE_BYTES / 4);
61 if (
62 !dimensions ||
63 dimensions.width <= 0 ||
64 dimensions.height <= 0 ||
65 dimensions.width * dimensions.height > MAX_IMAGE_BYTES / 4
66 ) {
67 throw new Error("Image dimensions exceed the size limit");
68 }
69 if (contents.isDestroyed() || frame.isDestroyed()) return;
70 const image = Electron.nativeImage.createFromBuffer(bytes);
71 let png: Buffer;
72 if (image.isEmpty()) {
73 const decoded: unknown = await contents.executeJavaScriptInIsolatedWorld(1002, [
74 {
75 code: `(async () => {
76 const source = Uint8Array.from(atob("${bytes.toString("base64")}"), char => char.charCodeAt(0));
77 const bitmap = await createImageBitmap(new Blob([source]));
78 try {
79 if (bitmap.width <= 0 || bitmap.height <= 0 || bitmap.width * bitmap.height > ${MAX_IMAGE_BYTES / 4}) {
80 throw new Error("Image dimensions exceed the size limit");
81 }
82 const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
83 const context = canvas.getContext("2d");
84 if (!context) throw new Error("Image could not be decoded");
85 context.drawImage(bitmap, 0, 0);
86 const output = await canvas.convertToBlob({ type: "image/png" });
87 if (output.size > ${MAX_IMAGE_BYTES}) throw new Error("PNG exceeded the size limit");
88 return await output.arrayBuffer();
89 } finally {
90 bitmap.close();
91 }
92 })()`,
93 },
94 ]);
95 if (!(decoded instanceof ArrayBuffer)) throw new Error("Image could not be decoded");
96 png = Buffer.from(decoded);
97 } else {
98 png = image.toPNG();
99 }
100 if (png.byteLength > MAX_IMAGE_BYTES) throw new Error("PNG exceeded the size limit");
101 if (contents.isDestroyed() || frame.isDestroyed() || copy !== latestCopy) return;
102 await Electron.clipboard.write([
103 new Electron.ClipboardItem({
104 "image/png": new Blob([Uint8Array.from(png)], { type: "image/png" }),
105 }),
106 ]);