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

HyprlandSnapShot.ts

221 lines8.3 KB

1// @effect-diagnostics nodeBuiltinImport:off -- Bundled Wayland helper installed only by explicit setup.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFSP from "node:fs/promises";
4import * as NodeOS from "node:os";
5import * as NodePath from "node:path";
6import * as NodeURL from "node:url";
7import * as Schema from "effect/Schema";
8import type { DesktopCaptureHelperState } from "@t3tools/contracts";
9import type { LinuxWindowSnapshot } from "./LinuxSnapShot.ts";
10import { readPortalPng } from "./linuxCaptureSession.ts";
11import { startNativeCaptureFeedback } from "./NativeCaptureFeedback.ts";
12import { HYPRLAND_CAPTURE_ACTION } from "./linuxCaptureSession.ts";
13export { isHyprlandCaptureSession } from "./linuxCaptureSession.ts";
14​
15export const HYPRLAND_CAPTURE_EXECUTABLE = "t3-hyprland-snap-shot";
16export type HyprlandCapturePaths = { readonly bundle: string; readonly dataHome: string };
17export function hyprlandCaptureExecutable(paths: HyprlandCapturePaths) {
18 return NodePath.join(paths.dataHome, "t3code", "hyprland-capture", HYPRLAND_CAPTURE_EXECUTABLE);
20​
21function hyprlandCaptureBinding(appId: string, lua: boolean): string {
22 if (!/^[A-Za-z0-9_.-]+$/.test(appId)) throw new Error("Invalid capture application ID.");
23 const action = `${appId}:${HYPRLAND_CAPTURE_ACTION}`;
24 return lua
25 ? `hl.bind("CTRL + SHIFT + 2", hl.dsp.global("${action}"))`
26 : `bind = CTRL SHIFT, 2, global, ${action}`;
28​
29/** Omarchy owns its defaults; instructions always point at a user-owned config. */
30export async function hyprlandCaptureShortcut(
31 appId: string,
32 configHome = process.env.XDG_CONFIG_HOME || NodePath.join(NodeOS.homedir(), ".config"),
33) {
34 const directory = NodePath.join(configHome, "hypr");
35 const exists = async (name: string) =>
36 NodeFSP.access(NodePath.join(directory, name)).then(
37 () => true,
38 () => false,
39 );
40 const lua = await exists("hyprland.lua");
41 const bindings = lua ? "bindings.lua" : "bindings.conf";
42 const config = (await exists(bindings)) ? bindings : lua ? "hyprland.lua" : "hyprland.conf";
43 return {
44 shortcutBinding: hyprlandCaptureBinding(appId, lua),
45 shortcutConfigPath: NodePath.join(directory, config),
46 };
48​
49function run(executable: string, args: string[], signal?: AbortSignal): Promise<string> {
50 return new Promise((resolve, reject) => {
51 NodeChildProcess.execFile(
52 executable,
53 args,
54 { timeout: 20_000, maxBuffer: 128 * 1024, encoding: "utf8", ...(signal ? { signal } : {}) },
55 (error, stdout, stderr) => {
56 if (error)
57 reject(
58 new Error(
59 stderr.trim() ||
60 "Hyprland capture did not respond. Check capture setup and try again.",
61 ),
62 );
63 else resolve(stdout);
64 },
65 );
66 });
68async function regularFile(path: string): Promise<Buffer | undefined> {
69 const stat = await NodeFSP.lstat(path).catch((error: NodeJS.ErrnoException) => {
70 if (error.code !== "ENOENT") throw error;
71 return undefined;
72 });
73 if (!stat) return undefined;
74 if (!stat.isFile() || stat.isSymbolicLink())
75 throw new Error("The capture helper must be a regular file, not a link.");
76 return NodeFSP.readFile(path);
78const decodeCapabilities = Schema.decodeUnknownSync(
79 Schema.fromJsonString(Schema.Struct({ feedbackAvailable: Schema.Boolean })),
80);
81​
82export class HyprlandCaptureSetup {
83 private readonly paths: HyprlandCapturePaths;
84 constructor(paths: HyprlandCapturePaths) {
85 this.paths = paths;
86 }
87 async state(): Promise<DesktopCaptureHelperState> {
88 try {
89 const installed = await regularFile(hyprlandCaptureExecutable(this.paths));
90 if (!installed)
91 return {
92 status: "not-installed",
93 message: "Install the bundled helper to capture the window you're using.",
94 };
95 const bundle = await regularFile(this.paths.bundle);
96 if (!bundle)
97 throw new Error(
98 "The Hyprland capture helper is missing from this build. Update or reinstall T3 Code.",
99 );
100 if (!installed.equals(bundle))
101 return {
102 status: "update-required",
103 message: "Update the bundled capture helper to continue.",
104 };
105 return {
106 status: "ready",
107 message:
108 "Helper ready. Hyprland may ask for screen-sharing permission on your first capture.",
109 ...decodeCapabilities(await run(hyprlandCaptureExecutable(this.paths), ["check"])),
110 };
111 } catch (error) {
112 return {
113 status: "error",
114 message: error instanceof Error ? error.message : "Couldn't check Hyprland capture access.",
115 };
116 }
117 }
118 async perform(action: "install-hyprland-helper" | "remove-hyprland-helper") {
119 const executable = hyprlandCaptureExecutable(this.paths);
120 const directory = NodePath.dirname(executable);
121 const stat = await NodeFSP.lstat(directory).catch((error: NodeJS.ErrnoException) => {
122 if (error.code !== "ENOENT") throw error;
123 return undefined;
124 });
125 if (stat && (!stat.isDirectory() || stat.isSymbolicLink()))
126 throw new Error("The capture helper directory must not be a link.");
127 await regularFile(executable);
128 if (action === "remove-hyprland-helper") {
129 await NodeFSP.rm(executable, { force: true });
130 return;
131 }
132 const bundle = await regularFile(this.paths.bundle);
133 if (!bundle) throw new Error("The Hyprland capture helper is missing from this build.");
134 await NodeFSP.mkdir(directory, { recursive: true });
135 const staging = await NodeFSP.mkdtemp(NodePath.join(directory, ".install-"));
136 try {
137 const staged = NodePath.join(staging, HYPRLAND_CAPTURE_EXECUTABLE);
138 await NodeFSP.writeFile(staged, bundle, { mode: 0o755, flag: "wx" });
139 await NodeFSP.rename(staged, executable);
140 } finally {
141 await NodeFSP.rm(staging, { recursive: true, force: true });
142 }
143 }
145​
146const Dimension = Schema.Int.check(Schema.isGreaterThan(0));
147const Bounds = Schema.Struct({ x: Schema.Int, y: Schema.Int, width: Dimension, height: Dimension });
148const decodeCapture = Schema.decodeUnknownSync(
149 Schema.fromJsonString(
150 Schema.Struct({
151 window: Schema.NullOr(
152 Schema.Struct({
153 title: Schema.String,
154 appName: Schema.String,
155 appIdentifier: Schema.String,
156 processId: Dimension,
157 bounds: Bounds,
158 clientBounds: Bounds,
159 }),
160 ),
161 }),
162 ),
163);
164​
165export async function captureHyprlandWindow(
166 paths: HyprlandCapturePaths,
167 options?: { readonly flash: boolean; readonly animate: boolean },
168): Promise<LinuxWindowSnapshot> {
169 const state = await new HyprlandCaptureSetup(paths).state();
170 if (state.status !== "ready")
171 throw new Error(`${state.message} Open Settings → SnapShots to continue setup.`);
172 const executable = hyprlandCaptureExecutable(paths);
173 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-hyprland-capture-"));
174 const cleanup = () => NodeFSP.rm(directory, { recursive: true, force: true });
175 let retained = false;
176 try {
177 const result = decodeCapture(await run(executable, ["capture", directory]));
178 const png = await readPortalPng(
179 NodeURL.pathToFileURL(NodePath.join(directory, "capture.png")).href,
180 );
181 const effects =
182 state.feedbackAvailable && result.window && options && (options.flash || options.animate)
183 ? await startNativeCaptureFeedback(executable, directory, {
184 bounds: result.window.bounds,
185 pid: process.pid,
186 ...options,
187 }).catch(() => undefined)
188 : undefined;
189 if (effects) {
190 retained = true;
191 void effects.closed.then(cleanup).catch(() => undefined);
192 }
193 const activation = new AbortController();
194 let targetTitle = "";
195 return {
196 png,
197 ...(result.window ? { window: result.window } : {}),
198 feedback: {
199 animationStarted: effects?.animationStarted ?? false,
200 activate: async (title) => {
201 targetTitle = title;
202 await run(executable, ["activate", String(process.pid), title], activation.signal);
203 },
204 animateTo: async (frame) => {
205 await effects?.animateTo(targetTitle, frame);
206 },
207 complete: async () => {
208 await effects?.complete();
209 activation.abort();
210 await cleanup();
211 },
212 close: () => {
213 effects?.close();
214 activation.abort();
215 },
216 },
217 };
218 } finally {
219 if (!retained) await cleanup();
220 }