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

MacModifierPairShortcutProcess.ts

89 lines2.4 KB

1// @effect-diagnostics nodeBuiltinImport:off -- This macOS platform boundary spawns the native modifier-key poller with Node.
2​
3import * as NodeChildProcess from "node:child_process";
4​
5import type { SnapShotModifier } from "@t3tools/contracts";
6​
7const MAC_MODIFIER_PAIR_DEVICE_MASKS: Record<SnapShotModifier, readonly [number, number]> = {
8 shift: [0x2, 0x4],
9 control: [0x1, 0x2000],
10 alt: [0x20, 0x40],
11 meta: [0x8, 0x10],
12};
13​
14const POLLER_SCRIPT = `
15ObjC.import("CoreGraphics");
16ObjC.import("unistd");
17function run(argv) {
18 const left = Number(argv[0]);
19 const right = Number(argv[1]);
20 const both = left | right;
21 let active = false;
22 console.log("ready");
23 while ($.getppid() !== 1) {
24 const pressed = ($.CGEventSourceFlagsState(0) & both) === both;
25 if (pressed && !active) console.log("trigger");
26 active = pressed;
27 delay(0.05);
28 }
29 return "orphaned";
30}`;
31​
32export function startMacModifierPairShortcutProcess(
33 modifier: SnapShotModifier,
34 onTrigger: () => void,
35 onFailure: (error: Error) => void,
36): Promise<() => void> {
37 const [left, right] = MAC_MODIFIER_PAIR_DEVICE_MASKS[modifier];
38 const poller = NodeChildProcess.spawn(
39 "/usr/bin/osascript",
40 ["-l", "JavaScript", "-e", POLLER_SCRIPT, String(left), String(right)],
41 { stdio: ["ignore", "ignore", "pipe"] },
42 );
43​
44 return new Promise((resolve, reject) => {
45 let settled = false;
46 let stopped = false;
47 let buffered = "";
48 const stop = () => {
49 if (stopped) return;
50 stopped = true;
51 poller.kill();
52 };
53 const fail = (error: Error) => {
54 if (stopped) return;
55 if (settled) {
56 stop();
57 onFailure(error);
58 return;
59 }
60 settled = true;
61 stop();
62 reject(error);
63 };
64​
65 poller.stderr.on("data", (chunk: Buffer) => {
66 buffered += chunk.toString();
67 const lines = buffered.split("\n");
68 buffered = lines.pop() ?? "";
69 for (const line of lines) {
70 const message = line.trim();
71 if (message === "ready" && !settled) {
72 settled = true;
73 resolve(stop);
74 continue;
75 }
76 if (message !== "trigger" || !settled || stopped) continue;
77 try {
78 onTrigger();
79 } catch {}
80 }
81 });
82 poller.once("error", (error) => {
83 fail(error);
84 });
85 poller.once("exit", (code) => {
86 fail(new Error(`Snapshot shortcut helper exited with code ${code}`));
87 });
88 });