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

CaptureShortcutConfig.ts

303 lines10.9 KB

1// @effect-diagnostics nodeBuiltinImport:off -- Native, consent-gated compositor config I/O.
2import * as NodeFSP from "node:fs/promises";
3import * as NodeFS from "node:fs";
4import * as NodePath from "node:path";
5import * as NodeOS from "node:os";
6import * as NodeCrypto from "node:crypto";
7import * as NodeChildProcess from "node:child_process";
8import * as NodeUtil from "node:util";
9import * as Schema from "effect/Schema";
10import type {
11 DesktopCaptureConfigApplied,
12 DesktopCaptureConfigPreview,
13 DesktopCaptureConfigRequest,
14} from "@t3tools/contracts";
15import {
16 captureConfigKeys,
17 editCaptureConfig,
18 niriConfigConflict,
19 niriConfigIncludes,
20 type CaptureConfigFormat,
21} from "./captureConfigEdit.ts";
22​
23const execute = (file: string, args: string[], options: { timeout: number; maxBuffer: number }) =>
24 NodeUtil.promisify(NodeChildProcess.execFile)(file, args, options);
25const MAX_BYTES = 1024 * 1024;
26const MAX_FILES = 64;
27type Target = { desktop: "niri" | "hyprland"; path: string; appId: string };
28type Snapshot = Awaited<ReturnType<typeof readSnapshot>>;
29const decodeHyprlandBindings = Schema.decodeUnknownSync(
30 Schema.fromJsonString(
31 Schema.Array(
32 Schema.Struct({
33 modmask: Schema.Number,
34 key: Schema.String,
35 dispatcher: Schema.String,
36 arg: Schema.String,
37 }),
38 ),
39 ),
40);
41​
42export function niriCaptureConfigPath(env = process.env, home = NodeOS.homedir()) {
43 return (
44 env.NIRI_CONFIG ||
45 NodePath.join(env.XDG_CONFIG_HOME || NodePath.join(home, ".config"), "niri", "config.kdl")
46 );
48​
49async function readSnapshot(path: string) {
50 const resolvedPath = await NodeFSP.realpath(path);
51 const file = await NodeFSP.open(
52 resolvedPath,
53 NodeFS.constants.O_RDONLY | NodeFS.constants.O_NONBLOCK | NodeFS.constants.O_NOFOLLOW,
54 );
55 try {
56 const stat = await file.stat();
57 if (!stat.isFile() || stat.size > MAX_BYTES)
58 throw new Error("Choose a config file smaller than 1 MB.");
59 const bytes = await file.readFile();
60 if (bytes.length > MAX_BYTES) throw new Error("Choose a config file smaller than 1 MB.");
61 const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
62 if (text.includes("\0")) throw new Error("Choose a text config file.");
63 return { path, resolvedPath, text, bytes, stat };
64 } finally {
65 await file.close();
66 }
68​
69const defaultTools = {
70 validateNiri: async (path: string) => {
71 try {
72 await execute("niri", ["validate", "--config", path], {
73 timeout: 5000,
74 maxBuffer: 64 * 1024,
75 });
76 } catch {
77 throw new Error(
78 "Niri couldn't validate the proposed config. Nothing was changed. Check your config in Advanced.",
79 );
80 }
81 },
82 hyprlandBindings: async () =>
83 decodeHyprlandBindings(
84 (await execute("hyprctl", ["-j", "binds"], { timeout: 5000, maxBuffer: MAX_BYTES })).stdout,
85 ),
86 reloadHyprland: async () => {
87 await execute("hyprctl", ["reload"], { timeout: 5000, maxBuffer: 64 * 1024 });
88 const errors = await execute("hyprctl", ["configerrors"], {
89 timeout: 5000,
90 maxBuffer: 64 * 1024,
91 });
92 if (errors.stdout.trim()) throw new Error("Hyprland reported config errors.");
93 },
94};
95​
96/** The renderer can apply only the exact proposal retained by the desktop process. */
97export class CaptureShortcutConfig {
98 private pending:
99 | { preview: DesktopCaptureConfigPreview; target: Target; files: Snapshot[]; missing: string[] }
100 | undefined;
101 private applying = false;
102 private readonly tools: typeof defaultTools;
103 constructor(tools = defaultTools) {
104 this.tools = tools;
105 }
106​
107 private async checkHyprlandKeys(appId: string, shortcut: string) {
108 const keys = captureConfigKeys(shortcut);
109 const bindings = await this.tools.hyprlandBindings().catch(() => {
110 throw new Error(
111 "Couldn't check Hyprland's current shortcuts. Try again from your Hyprland session.",
112 );
113 });
114 if (
115 bindings.some(
116 (binding) =>
117 binding.modmask === keys.mask &&
118 binding.key.toUpperCase() === keys.key &&
119 !(binding.dispatcher === "global" && binding.arg === `${appId}:capture-window`),
120 )
121 )
122 throw new Error(`${keys.label} is already used by Hyprland. Choose another shortcut.`);
123 }
124​
125 async preview(
126 target: Target,
127 request: DesktopCaptureConfigRequest,
128 ): Promise<DesktopCaptureConfigPreview> {
129 if (this.applying) throw new Error("Wait for the current config change to finish.");
130 this.pending = undefined;
131 const root = await readSnapshot(target.path).catch(() => {
132 throw new Error("Couldn't read your settings file. Choose a different file in Advanced.");
133 });
134 if (root.stat.uid !== process.getuid?.() || /\/omarchy\/default\//.test(root.resolvedPath))
135 throw new Error("Choose your own config, not system or Omarchy defaults.");
136 const format: CaptureConfigFormat =
137 target.desktop === "niri"
138 ? "niri"
139 : target.path.endsWith(".lua")
140 ? "hyprland-lua"
141 : "hyprland";
142 if (
143 !target.path.endsWith(
144 format === "niri" ? ".kdl" : format === "hyprland-lua" ? ".lua" : ".conf",
145 )
146 )
147 throw new Error("Choose a .kdl Niri config or a .conf/.lua Hyprland config.");
148 const edit = editCaptureConfig(
149 root.text,
150 format,
151 target.appId,
152 request.operation,
153 request.shortcut,
154 );
155 const files = [root];
156 const missing: string[] = [];
157 if (target.desktop === "niri") {
158 const visit = async (file: Snapshot, depth: number) => {
159 if (
160 depth > 10 ||
161 files.length > MAX_FILES ||
162 files.reduce((size, item) => size + item.bytes.length, 0) > MAX_BYTES
163 )
164 throw new Error("This config has too many included files. Use manual setup in Advanced.");
165 for (const include of niriConfigIncludes(file.text)) {
166 if (include.path.includes("$") || /[*?[\]]/.test(include.path))
167 throw new Error("This config uses a dynamic include. Use manual setup in Advanced.");
168 const path = include.path.startsWith("~/")
169 ? NodePath.join(NodeOS.homedir(), include.path.slice(2))
170 : NodePath.resolve(NodePath.dirname(file.path), include.path);
171 let child: Snapshot;
172 try {
173 child = await readSnapshot(path);
174 } catch (error) {
175 if (include.optional && (error as NodeJS.ErrnoException).code === "ENOENT") {
176 missing.push(path);
177 continue;
178 }
179 throw new Error(
180 "Couldn't read an included Niri config. Check its location in Advanced.",
181 { cause: error },
182 );
183 }
184 if (files.some((item) => item.resolvedPath === child.resolvedPath)) continue;
185 files.push(child);
186 if (
187 request.operation === "install" &&
188 niriConfigConflict(child.text, target.appId, edit.shortcut)
189 )
190 throw new Error(
191 `${edit.shortcut} is already used in ${child.path}. Choose another shortcut.`,
192 );
193 await visit(child, depth + 1);
194 }
195 };
196 await visit(root, 0);
197 } else if (request.operation === "install") {
198 await this.checkHyprlandKeys(target.appId, edit.shortcut);
199 }
200 const preview = {
201 id: NodeCrypto.randomUUID(),
202 path: root.path,
203 resolvedPath: root.resolvedPath,
204 before: root.text,
205 after: edit.after,
206 shortcut: edit.shortcut,
207 operation: request.operation,
208 };
209 this.pending = { preview, target, files, missing };
210 return preview;
211 }
212​
213 async apply(id: string, desktop: Target["desktop"]): Promise<DesktopCaptureConfigApplied> {
214 const pending = this.pending;
215 if (
216 this.applying ||
217 !pending ||
218 pending.preview.id !== id ||
219 pending.target.desktop !== desktop
220 )
221 throw new Error("This preview expired. Review changes again before saving.");
222 this.pending = undefined;
223 this.applying = true;
224 const { preview, files } = pending;
225 const root = files[0]!;
226 const directory = NodePath.dirname(root.resolvedPath);
227 const temporary = NodePath.join(directory, `.t3-capture-${NodeCrypto.randomUUID()}.tmp`);
228 let staged = false;
229 try {
230 const unchanged = async () => {
231 for (const path of pending.missing) {
232 if (
233 await NodeFSP.lstat(path).then(
234 () => true,
235 (error: NodeJS.ErrnoException) => error.code !== "ENOENT",
236 )
237 )
238 throw new Error(
239 "Your config changed since this preview. Review changes again before saving.",
240 );
241 }
242 for (const original of files) {
243 const current = await readSnapshot(original.path).catch(() => undefined);
244 if (
245 !current ||
246 current.resolvedPath !== original.resolvedPath ||
247 current.stat.ino !== original.stat.ino ||
248 current.stat.mode !== original.stat.mode ||
249 !current.bytes.equals(original.bytes)
250 )
251 throw new Error(
252 "Your config changed since this preview. Nothing was saved. Review changes again before saving.",
253 );
254 }
255 };
256 await unchanged();
257 if (desktop === "hyprland" && preview.operation === "install")
258 await this.checkHyprlandKeys(pending.target.appId, preview.shortcut);
259 if (preview.before === preview.after) return { backupPath: null, warning: null };
260 await NodeFSP.writeFile(temporary, preview.after, {
261 flag: "wx",
262 mode: root.stat.mode & 0o777,
263 });
264 staged = true;
265 await NodeFSP.chmod(temporary, root.stat.mode & 0o777);
266 if (desktop === "niri") {
267 // Niri resolves includes against the selected path, not a dotfile symlink's target.
268 const validationPath = NodePath.join(
269 NodePath.dirname(root.path),
270 NodePath.basename(temporary),
271 );
272 if (NodePath.resolve(validationPath) === NodePath.resolve(temporary)) {
273 await this.tools.validateNiri(temporary);
274 } else {
275 await NodeFSP.symlink(temporary, validationPath);
276 try {
277 await this.tools.validateNiri(validationPath);
278 } finally {
279 await NodeFSP.unlink(validationPath);
280 }
281 }
282 }
283 await unchanged();
284 const backupPath = `${root.resolvedPath}.t3-capture-backup-${NodeCrypto.randomUUID()}`;
285 await NodeFSP.writeFile(backupPath, root.bytes, { flag: "wx", mode: 0o600 });
286 await NodeFSP.rename(temporary, root.resolvedPath);
287 staged = false;
288 let warning: string | null = null;
289 if (desktop === "hyprland") {
290 try {
291 await this.tools.reloadHyprland();
292 } catch {
293 warning =
294 "Config saved, but Hyprland couldn't reload it cleanly. Check hyprctl configerrors, then run hyprctl reload.";
295 }
296 }
297 return { backupPath, warning };
298 } finally {
299 if (staged) await NodeFSP.unlink(temporary).catch(() => undefined);
300 this.applying = false;
301 }
302 }