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

GlobalShiftShortcutWorker.ts

146 lines4.6 KB

1// @effect-diagnostics globalTimers:off -- A plain Node child; the poll runs outside any Effect fiber.
2import { SNAP_SHOT_MODIFIERS, type SnapShotModifier } from "@t3tools/contracts";
3​
4import { loadWindowsForegroundApi } from "../electron/WindowsForeground.ts";
5import { WINDOWS_MODIFIER_PAIR_VIRTUAL_KEYS } from "./snapShot.ts";
6​
7const POLL_INTERVAL_MS = 50;
8​
9const requested = process.argv[2];
10if (!(SNAP_SHOT_MODIFIERS as readonly string[]).includes(requested ?? "")) {
11 process.exit(1);
13const [left, right] = WINDOWS_MODIFIER_PAIR_VIRTUAL_KEYS[requested as SnapShotModifier];
14const MODIFIER_VIRTUAL_KEYS = new Set([
15 0x10,
16 0x11,
17 0x12,
18 0xff,
19 ...Object.values(WINDOWS_MODIFIER_PAIR_VIRTUAL_KEYS).flat(),
20]);
21​
22const HWND_MESSAGE = -3n;
23const RIDEV_INPUTSINK = 0x100;
24const WM_INPUT = 0x00ff;
25const PM_REMOVE = 1;
26const RID_INPUT = 0x10000003;
27const RIM_TYPEKEYBOARD = 1;
28const RI_KEY_BREAK = 1;
29// x64/arm64 layouts: MSG is 48 bytes (lParam at 24), RAWINPUTHEADER is 24, RAWKEYBOARD follows it.
30const MSG_SIZE = 48;
31const RAW_INPUT_HEADER_SIZE = 24;
32​
33// Raw Input queues every key event, so a keystroke between two polls is still seen.
34async function openKeyboardActivity(): Promise<() => boolean> {
35 const { DataType, load, open } = await import("ffi-rs");
36 const library = "t3-user32-raw-input";
37 open({ library, path: "user32.dll" });
38 const className = Buffer.from("STATIC\0", "utf16le");
39 const window = load({
40 library,
41 funcName: "CreateWindowExW",
42 retType: DataType.BigInt,
43 paramsType: [
44 DataType.U32,
45 DataType.U8Array,
46 DataType.BigInt,
47 DataType.U32,
48 DataType.I32,
49 DataType.I32,
50 DataType.I32,
51 DataType.I32,
52 DataType.BigInt,
53 DataType.BigInt,
54 DataType.BigInt,
55 DataType.BigInt,
56 ],
57 paramsValue: [0, className, 0n, 0, 0, 0, 0, 0, HWND_MESSAGE, 0n, 0n, 0n],
58 }) as bigint;
59 if (window === 0n) throw new Error("CreateWindowExW failed");
60 const device = Buffer.alloc(16);
61 device.writeUInt16LE(0x01, 0);
62 device.writeUInt16LE(0x06, 2);
63 device.writeUInt32LE(RIDEV_INPUTSINK, 4);
64 device.writeBigUInt64LE(window, 8);
65 const registered = load({
66 library,
67 funcName: "RegisterRawInputDevices",
68 retType: DataType.Boolean,
69 paramsType: [DataType.U8Array, DataType.U32, DataType.U32],
70 paramsValue: [device, 1, device.byteLength],
71 });
72 if (!registered) throw new Error("RegisterRawInputDevices failed");
73​
74 const message = Buffer.alloc(MSG_SIZE);
75 const input = Buffer.alloc(64);
76 const inputSize = Buffer.alloc(4);
77 return () => {
78 let typed = false;
79 while (
80 load({
81 library,
82 funcName: "PeekMessageW",
83 retType: DataType.Boolean,
84 paramsType: [DataType.U8Array, DataType.BigInt, DataType.U32, DataType.U32, DataType.U32],
85 paramsValue: [message, window, WM_INPUT, WM_INPUT, PM_REMOVE],
86 })
87 ) {
88 inputSize.writeUInt32LE(input.byteLength, 0);
89 const read = load({
90 library,
91 funcName: "GetRawInputData",
92 retType: DataType.U32,
93 paramsType: [
94 DataType.BigInt,
95 DataType.U32,
96 DataType.U8Array,
97 DataType.U8Array,
98 DataType.U32,
99 ],
100 paramsValue: [
101 message.readBigUInt64LE(24),
102 RID_INPUT,
103 input,
104 inputSize,
105 RAW_INPUT_HEADER_SIZE,
106 ],
107 });
108 if (read === 0xffffffff || input.readUInt32LE(0) !== RIM_TYPEKEYBOARD) continue;
109 const flags = input.readUInt16LE(RAW_INPUT_HEADER_SIZE + 2);
110 const virtualKey = input.readUInt16LE(RAW_INPUT_HEADER_SIZE + 6);
111 if ((flags & RI_KEY_BREAK) === 0 && !MODIFIER_VIRTUAL_KEYS.has(virtualKey)) typed = true;
112 }
113 return typed;
114 };
116​
117async function poll() {
118 const api = await loadWindowsForegroundApi();
119 const drainTyping = await openKeyboardActivity();
120 let active = false;
121 // A key typed since the pair was last fully up means the overlap came from typing (rolled
122 // Shifts for consecutive capitals), not a deliberate press, so it does not trigger.
123 let typed = false;
124 process.send?.("ready");
125 const timer = setInterval(() => {
126 if (drainTyping()) typed = true;
127 const leftDown = api.isKeyDown(left);
128 const rightDown = api.isKeyDown(right);
129 const pressed = leftDown && rightDown;
130 if (pressed && !active && !typed) {
131 try {
132 process.send?.("trigger");
133 } catch {}
134 }
135 active = pressed;
136 if (!leftDown && !rightDown) typed = false;
137 }, POLL_INTERVAL_MS);
138 const shutdown = () => {
139 clearInterval(timer);
140 process.exit(0);
141 };
142 process.once("disconnect", shutdown);
143 process.once("SIGTERM", shutdown);
145​
146void poll().catch(() => process.exit(1));