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

linuxCaptureSession.ts

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