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

linuxCaptureSession.ts

149 lines4.4 KB

1// @effect-diagnostics nodeBuiltinImport:off -- Reads portal-owned screenshot files at the native boundary.
2import * as NodeFSP from "node:fs/promises";
3import * as NodeURL from "node:url";
4import type { SnapShotKeyChord } from "@t3tools/contracts";
5import { nativeImage } from "electron";
6​
7// Keep dbus-next out of desktop detection and PNG reads in the main process.
8​
9export const HYPRLAND_CAPTURE_ACTION = "capture-window";
10export const NIRI_CAPTURE_PATH = "/com/t3tools/SnapShot";
11export const NIRI_CAPTURE_INTERFACE = "com.t3tools.SnapShot";
12​
13function isDesktopSession(env: NodeJS.ProcessEnv, desktop: string): boolean {
14 return (
15 !env.FLATPAK_ID &&
16 !env.SNAP &&
17 Boolean(env.XDG_CURRENT_DESKTOP?.split(":").some((name) => name.toLowerCase() === desktop))
18 );
20​
21export function isGnomeCaptureSession(env: NodeJS.ProcessEnv): boolean {
22 return isDesktopSession(env, "gnome");
24​
25export function isKdeCaptureSession(env = process.env): boolean {
26 return isDesktopSession(env, "kde");
28​
29export function isHyprlandCaptureSession(env = process.env): boolean {
30 return isDesktopSession(env, "hyprland");
32​
33export function niriCaptureBinding(appId: string): string {
34 return `Ctrl+Shift+2 repeat=false { spawn "gdbus" "call" "--session" "--dest" "${appId}.SnapShot" "--object-path" "${NIRI_CAPTURE_PATH}" "--method" "${NIRI_CAPTURE_INTERFACE}.Capture"; }`;
36​
37const KEY_NAMES: Readonly<Record<string, string>> = {
38 " ": "space",
39 escape: "Escape",
40 esc: "Escape",
41 enter: "Return",
42 tab: "Tab",
43 backspace: "BackSpace",
44 delete: "Delete",
45 insert: "Insert",
46 home: "Home",
47 end: "End",
48 pageup: "Page_Up",
49 pagedown: "Page_Down",
50 arrowup: "Up",
51 arrowdown: "Down",
52 arrowleft: "Left",
53 arrowright: "Right",
54 up: "Up",
55 down: "Down",
56 left: "Left",
57 right: "Right",
58 "+": "plus",
59 "-": "minus",
60 "=": "equal",
61 ",": "comma",
62 ".": "period",
63 "/": "slash",
64 ";": "semicolon",
65 "'": "apostrophe",
66 "[": "bracketleft",
67 "]": "bracketright",
68 "\\": "backslash",
69 "`": "grave",
70 "!": "exclam",
71 "@": "at",
72 "#": "numbersign",
73 $: "dollar",
74 "%": "percent",
75 "^": "asciicircum",
76 "&": "ampersand",
77 "*": "asterisk",
78 "(": "parenleft",
79 ")": "parenright",
80 _: "underscore",
81 ":": "colon",
82 '"': "quotedbl",
83 "{": "braceleft",
84 "}": "braceright",
85 "|": "bar",
86 "<": "less",
87 ">": "greater",
88 "?": "question",
89 "~": "asciitilde",
90};
91​
92export function portalShortcutTrigger(shortcut: SnapShotKeyChord): string {
93 const key = shortcut.key.toLowerCase();
94 const keysym =
95 KEY_NAMES[key] ??
96 (/^[a-z0-9]$/.test(key) || /^f([1-9]|1\d|2[0-4])$/.test(key) ? key.toUpperCase() : undefined);
97 if (!keysym)
98 throw new Error("This key isn't supported as a Wayland capture shortcut. Choose another key.");
99 return [
100 shortcut.ctrlKey || shortcut.modKey ? "CTRL" : null,
101 shortcut.altKey ? "ALT" : null,
102 shortcut.shiftKey ? "SHIFT" : null,
103 shortcut.metaKey ? "LOGO" : null,
104 keysym,
105 ]
106 .filter(Boolean)
107 .join("+");
109​
110const PNG_HEADER = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
111const MAX_PNG_BYTES = 32 * 1024 * 1024;
112​
113export function resizeLinuxCapture(png: Buffer): Buffer {
114 if (png.length > MAX_PNG_BYTES || !png.subarray(0, 8).equals(PNG_HEADER)) {
115 throw new Error("Invalid or oversized window screenshot.");
116 }
117 const image = nativeImage.createFromBuffer(png);
118 if (image.isEmpty()) throw new Error("The window screenshot is empty.");
119 const { width, height } = image.getSize();
120 const scale = Math.min(2_560 / width, 1_600 / height, 1);
121 return scale < 1
122 ? image
123 .resize({
124 width: Math.max(1, Math.round(width * scale)),
125 height: Math.max(1, Math.round(height * scale)),
126 quality: "best",
127 })
128 .toPNG()
129 : png;
131​
132export async function readPortalPng(uri: string): Promise<Buffer> {
133 // fileURLToPath rejects network schemes/hosts. Never delete a portal-owned file.
134 const file = await NodeFSP.open(NodeURL.fileURLToPath(uri), "r");
135 try {
136 const stat = await file.stat();
137 if (!stat.isFile() || stat.size > MAX_PNG_BYTES) throw new Error("Invalid screenshot file.");
138 const buffer = Buffer.alloc(stat.size);
139 let offset = 0;
140 while (offset < buffer.length) {
141 const { bytesRead } = await file.read(buffer, offset, buffer.length - offset, offset);
142 if (!bytesRead) throw new Error("Incomplete screenshot file.");
143 offset += bytesRead;
144 }
145 return resizeLinuxCapture(buffer);
146 } finally {
147 await file.close();
148 }