@sdeck/plugin-system 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/controls.d.ts +36 -0
- package/dist/controls.d.ts.map +1 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1731 -0
- package/dist/index.js.map +13 -0
- package/dist/monitor.d.ts +80 -0
- package/dist/monitor.d.ts.map +1 -0
- package/dist/watchers.d.ts +34 -0
- package/dist/watchers.d.ts.map +1 -0
- package/package.json +60 -4
- package/src/controls.ts +305 -0
- package/src/index.tsx +1075 -0
- package/src/monitor.ts +432 -0
- package/src/watchers.ts +245 -0
- package/README.md +0 -3
package/src/controls.ts
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Controlling the computer: keys and typed text, the lock screen, sleep and screenshots.
|
|
3
|
+
* Windows calls `user32.dll` directly. macOS and Linux use the tools they ship or commonly have,
|
|
4
|
+
* and say what is missing otherwise.
|
|
5
|
+
*/
|
|
6
|
+
import { execFile } from "node:child_process";
|
|
7
|
+
import { mkdir } from "node:fs/promises";
|
|
8
|
+
import { dirname } from "node:path";
|
|
9
|
+
import { type Accelerator, MODIFIER_CODES, parseAccelerator } from "@sdeck/schema";
|
|
10
|
+
|
|
11
|
+
export type MediaKey =
|
|
12
|
+
| "play-pause"
|
|
13
|
+
| "next"
|
|
14
|
+
| "previous"
|
|
15
|
+
| "stop"
|
|
16
|
+
| "mute"
|
|
17
|
+
| "volume-up"
|
|
18
|
+
| "volume-down";
|
|
19
|
+
|
|
20
|
+
export interface SystemControls {
|
|
21
|
+
media(key: MediaKey): Promise<void>;
|
|
22
|
+
/** Presses a shortcut: modifiers down, the key, everything up. */
|
|
23
|
+
hotkey(accelerator: Accelerator): Promise<void>;
|
|
24
|
+
type(text: string): Promise<void>;
|
|
25
|
+
lock(): Promise<void>;
|
|
26
|
+
sleep(): Promise<void>;
|
|
27
|
+
/** Saves the whole screen to `file` (a PNG). */
|
|
28
|
+
screenshot(file: string): Promise<void>;
|
|
29
|
+
/** Opens the system's own region picker. */
|
|
30
|
+
snip(): Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// -- Windows ------------------------------------------------------------------------------------
|
|
34
|
+
|
|
35
|
+
const MEDIA_KEYS: Record<MediaKey, string> = {
|
|
36
|
+
"play-pause": "playpause",
|
|
37
|
+
next: "medianext",
|
|
38
|
+
previous: "mediaprevious",
|
|
39
|
+
stop: "mediastop",
|
|
40
|
+
mute: "volumemute",
|
|
41
|
+
"volume-up": "volumeup",
|
|
42
|
+
"volume-down": "volumedown",
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export interface KeyEvent {
|
|
46
|
+
/** Virtual-key code (0 for typed characters). */
|
|
47
|
+
vk: number;
|
|
48
|
+
/** UTF-16 code unit of a typed character. */
|
|
49
|
+
scan: number;
|
|
50
|
+
flags: number;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const EXTENDED = 0x0001;
|
|
54
|
+
const KEY_UP = 0x0002;
|
|
55
|
+
const UNICODE = 0x0004;
|
|
56
|
+
/** Keys the keyboard reports as "extended" (arrows, navigation, media, the Windows key). */
|
|
57
|
+
const EXTENDED_KEYS = new Set([
|
|
58
|
+
0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x2c, 0x2d, 0x2e, 0x5b, 0x5d, 0x6f, 0x90, 0xad,
|
|
59
|
+
0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3,
|
|
60
|
+
]);
|
|
61
|
+
|
|
62
|
+
/** Down and up events for a shortcut. */
|
|
63
|
+
export function hotkeyEvents(accelerator: Accelerator): KeyEvent[] {
|
|
64
|
+
const codes = [...accelerator.modifiers.map((m) => MODIFIER_CODES[m]), accelerator.code];
|
|
65
|
+
const event = (vk: number, up: boolean): KeyEvent => ({
|
|
66
|
+
vk,
|
|
67
|
+
scan: 0,
|
|
68
|
+
flags: (EXTENDED_KEYS.has(vk) ? EXTENDED : 0) | (up ? KEY_UP : 0),
|
|
69
|
+
});
|
|
70
|
+
return [...codes.map((c) => event(c, false)), ...codes.reverse().map((c) => event(c, true))];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Events typing `text`, whatever the keyboard layout. Newlines press Enter. */
|
|
74
|
+
export function textEvents(text: string): KeyEvent[] {
|
|
75
|
+
const events: KeyEvent[] = [];
|
|
76
|
+
const normalized = text.replace(/\r\n?/g, "\n");
|
|
77
|
+
for (let i = 0; i < normalized.length; i++) {
|
|
78
|
+
const unit = normalized.charCodeAt(i);
|
|
79
|
+
if (unit === 10 || unit === 9) {
|
|
80
|
+
const vk = unit === 10 ? 0x0d : 0x09;
|
|
81
|
+
events.push({ vk, scan: 0, flags: 0 }, { vk, scan: 0, flags: KEY_UP });
|
|
82
|
+
} else {
|
|
83
|
+
events.push(
|
|
84
|
+
{ vk: 0, scan: unit, flags: UNICODE },
|
|
85
|
+
{ vk: 0, scan: unit, flags: UNICODE | KEY_UP },
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return events;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** `sizeof(INPUT)` on 64-bit Windows. */
|
|
93
|
+
export const INPUT_SIZE = 40;
|
|
94
|
+
|
|
95
|
+
/** `INPUT[]` for `SendInput`: type 1 (keyboard) and a `KEYBDINPUT` at offset 8. */
|
|
96
|
+
export function encodeInputs(events: readonly KeyEvent[]): Uint8Array {
|
|
97
|
+
const buffer = new Uint8Array(events.length * INPUT_SIZE);
|
|
98
|
+
const view = new DataView(buffer.buffer);
|
|
99
|
+
events.forEach((event, i) => {
|
|
100
|
+
const at = i * INPUT_SIZE;
|
|
101
|
+
view.setUint32(at, 1, true);
|
|
102
|
+
view.setUint16(at + 8, event.vk, true);
|
|
103
|
+
view.setUint16(at + 10, event.scan, true);
|
|
104
|
+
view.setUint32(at + 12, event.flags, true);
|
|
105
|
+
});
|
|
106
|
+
return buffer;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Runs a tool, failing with what it printed. */
|
|
110
|
+
function run(file: string, args: string[], env?: Record<string, string>): Promise<void> {
|
|
111
|
+
return new Promise((resolve, reject) => {
|
|
112
|
+
execFile(
|
|
113
|
+
file,
|
|
114
|
+
args,
|
|
115
|
+
{ windowsHide: true, timeout: 30_000, ...(env && { env: { ...process.env, ...env } }) },
|
|
116
|
+
(error, _stdout, stderr) => {
|
|
117
|
+
if (!error) return resolve();
|
|
118
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
|
119
|
+
return reject(new Error(`this needs "${file}", which is not installed`));
|
|
120
|
+
}
|
|
121
|
+
reject(new Error(stderr.trim() || error.message));
|
|
122
|
+
},
|
|
123
|
+
);
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The path arrives in an environment variable, so no file name can change the script. */
|
|
128
|
+
const WINDOWS_SCREENSHOT = `
|
|
129
|
+
$ErrorActionPreference = "Stop"
|
|
130
|
+
Add-Type -AssemblyName System.Windows.Forms, System.Drawing
|
|
131
|
+
Add-Type -Name Dpi -Namespace Sdeck -MemberDefinition '[System.Runtime.InteropServices.DllImport("user32.dll")] public static extern bool SetProcessDPIAware();'
|
|
132
|
+
[void][Sdeck.Dpi]::SetProcessDPIAware()
|
|
133
|
+
$area = [System.Windows.Forms.SystemInformation]::VirtualScreen
|
|
134
|
+
$image = New-Object System.Drawing.Bitmap $area.Width, $area.Height
|
|
135
|
+
$graphics = [System.Drawing.Graphics]::FromImage($image)
|
|
136
|
+
$graphics.CopyFromScreen($area.Location, [System.Drawing.Point]::Empty, $area.Size)
|
|
137
|
+
$image.Save($env:SDECK_SCREENSHOT, [System.Drawing.Imaging.ImageFormat]::Png)
|
|
138
|
+
$graphics.Dispose(); $image.Dispose()
|
|
139
|
+
`;
|
|
140
|
+
|
|
141
|
+
async function windowsControls(): Promise<SystemControls> {
|
|
142
|
+
const { dlopen, FFIType, ptr } = await import("bun:ffi");
|
|
143
|
+
const user32 = dlopen("user32.dll", {
|
|
144
|
+
SendInput: { args: [FFIType.u32, FFIType.ptr, FFIType.i32], returns: FFIType.u32 },
|
|
145
|
+
LockWorkStation: { args: [], returns: FFIType.i32 },
|
|
146
|
+
});
|
|
147
|
+
const power = dlopen("powrprof.dll", {
|
|
148
|
+
SetSuspendState: { args: [FFIType.u8, FFIType.u8, FFIType.u8], returns: FFIType.u8 },
|
|
149
|
+
});
|
|
150
|
+
const send = (events: readonly KeyEvent[]) => {
|
|
151
|
+
// In batches: a very long text in one call can be cut short.
|
|
152
|
+
for (let i = 0; i < events.length; i += 200) {
|
|
153
|
+
const batch = events.slice(i, i + 200);
|
|
154
|
+
const sent = user32.symbols.SendInput(batch.length, ptr(encodeInputs(batch)), INPUT_SIZE);
|
|
155
|
+
if (sent !== batch.length) {
|
|
156
|
+
// Windows drops input aimed at a window running as administrator.
|
|
157
|
+
throw new Error("Windows blocked the input (is the focused app running as administrator?)");
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
return {
|
|
162
|
+
media: async (key) => send(hotkeyEvents(parseAccelerator(MEDIA_KEYS[key]))),
|
|
163
|
+
hotkey: async (accelerator) => send(hotkeyEvents(accelerator)),
|
|
164
|
+
type: async (text) => send(textEvents(text)),
|
|
165
|
+
lock: async () => {
|
|
166
|
+
if (!user32.symbols.LockWorkStation()) throw new Error("Windows refused to lock");
|
|
167
|
+
},
|
|
168
|
+
sleep: async () => {
|
|
169
|
+
if (!power.symbols.SetSuspendState(0, 0, 0)) throw new Error("Windows refused to sleep");
|
|
170
|
+
},
|
|
171
|
+
screenshot: async (file) => {
|
|
172
|
+
await mkdir(dirname(file), { recursive: true });
|
|
173
|
+
const encoded = Buffer.from(WINDOWS_SCREENSHOT, "utf16le").toString("base64");
|
|
174
|
+
await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], {
|
|
175
|
+
SDECK_SCREENSHOT: file,
|
|
176
|
+
});
|
|
177
|
+
},
|
|
178
|
+
snip: async () => send(hotkeyEvents(parseAccelerator("win+shift+s"))),
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// -- macOS --------------------------------------------------------------------------------------
|
|
183
|
+
|
|
184
|
+
const appleString = (text: string) => `"${text.replace(/[\\"]/g, "\\$&")}"`;
|
|
185
|
+
|
|
186
|
+
const MAC_KEY_CODES: Record<string, number> = {
|
|
187
|
+
enter: 36,
|
|
188
|
+
tab: 48,
|
|
189
|
+
space: 49,
|
|
190
|
+
backspace: 51,
|
|
191
|
+
escape: 53,
|
|
192
|
+
left: 123,
|
|
193
|
+
right: 124,
|
|
194
|
+
down: 125,
|
|
195
|
+
up: 126,
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
const MAC_MODIFIERS = {
|
|
199
|
+
ctrl: "control down",
|
|
200
|
+
alt: "option down",
|
|
201
|
+
shift: "shift down",
|
|
202
|
+
win: "command down",
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
/** The AppleScript pressing a shortcut. */
|
|
206
|
+
export function macHotkey(accelerator: Accelerator): string {
|
|
207
|
+
const { key, modifiers } = accelerator;
|
|
208
|
+
const code = MAC_KEY_CODES[key];
|
|
209
|
+
if (code === undefined && key.length !== 1) {
|
|
210
|
+
throw new Error(`"${key}" cannot be sent on macOS`);
|
|
211
|
+
}
|
|
212
|
+
const press = code === undefined ? `keystroke ${appleString(key)}` : `key code ${code}`;
|
|
213
|
+
const using =
|
|
214
|
+
modifiers.length > 0 ? ` using {${modifiers.map((m) => MAC_MODIFIERS[m]).join(", ")}}` : "";
|
|
215
|
+
return `tell application "System Events" to ${press}${using}`;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function macControls(): SystemControls {
|
|
219
|
+
const script = (source: string) => run("osascript", ["-e", source]);
|
|
220
|
+
const volume = (change: string) =>
|
|
221
|
+
script(`set volume output volume ((output volume of (get volume settings)) ${change})`);
|
|
222
|
+
return {
|
|
223
|
+
media: async (key) => {
|
|
224
|
+
if (key === "volume-up") return volume("+ 6");
|
|
225
|
+
if (key === "volume-down") return volume("- 6");
|
|
226
|
+
if (key === "mute") {
|
|
227
|
+
return script("set volume output muted not (output muted of (get volume settings))");
|
|
228
|
+
}
|
|
229
|
+
throw new Error("playback keys are not available on macOS");
|
|
230
|
+
},
|
|
231
|
+
hotkey: async (accelerator) => script(macHotkey(accelerator)),
|
|
232
|
+
type: (text) => script(`tell application "System Events" to keystroke ${appleString(text)}`),
|
|
233
|
+
lock: () => run("pmset", ["displaysleepnow"]),
|
|
234
|
+
sleep: () => run("pmset", ["sleepnow"]),
|
|
235
|
+
screenshot: async (file) => {
|
|
236
|
+
await mkdir(dirname(file), { recursive: true });
|
|
237
|
+
await run("screencapture", ["-x", file]);
|
|
238
|
+
},
|
|
239
|
+
snip: () => run("screencapture", ["-i", "-c"]),
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// -- Linux --------------------------------------------------------------------------------------
|
|
244
|
+
|
|
245
|
+
const X_KEYS: Record<string, string> = {
|
|
246
|
+
enter: "Return",
|
|
247
|
+
escape: "Escape",
|
|
248
|
+
backspace: "BackSpace",
|
|
249
|
+
tab: "Tab",
|
|
250
|
+
space: "space",
|
|
251
|
+
delete: "Delete",
|
|
252
|
+
insert: "Insert",
|
|
253
|
+
home: "Home",
|
|
254
|
+
end: "End",
|
|
255
|
+
pageup: "Prior",
|
|
256
|
+
pagedown: "Next",
|
|
257
|
+
left: "Left",
|
|
258
|
+
right: "Right",
|
|
259
|
+
up: "Up",
|
|
260
|
+
down: "Down",
|
|
261
|
+
printscreen: "Print",
|
|
262
|
+
playpause: "XF86AudioPlay",
|
|
263
|
+
medianext: "XF86AudioNext",
|
|
264
|
+
mediaprevious: "XF86AudioPrev",
|
|
265
|
+
mediastop: "XF86AudioStop",
|
|
266
|
+
volumemute: "XF86AudioMute",
|
|
267
|
+
volumeup: "XF86AudioRaiseVolume",
|
|
268
|
+
volumedown: "XF86AudioLowerVolume",
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
const X_MODIFIERS = { ctrl: "ctrl", alt: "alt", shift: "shift", win: "super" };
|
|
272
|
+
|
|
273
|
+
/** The `xdotool key` argument of a shortcut. */
|
|
274
|
+
export function xHotkey(accelerator: Accelerator): string {
|
|
275
|
+
const { key, modifiers } = accelerator;
|
|
276
|
+
const name = X_KEYS[key] ?? (/^f\d+$/.test(key) ? key.toUpperCase() : key);
|
|
277
|
+
return [...modifiers.map((m) => X_MODIFIERS[m]), name].join("+");
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function linuxControls(): SystemControls {
|
|
281
|
+
const hotkey = (accelerator: Accelerator) => run("xdotool", ["key", xHotkey(accelerator)]);
|
|
282
|
+
return {
|
|
283
|
+
media: (key) => hotkey(parseAccelerator(MEDIA_KEYS[key])),
|
|
284
|
+
hotkey,
|
|
285
|
+
type: (text) => run("xdotool", ["type", "--clearmodifiers", "--", text]),
|
|
286
|
+
lock: () => run("loginctl", ["lock-session"]),
|
|
287
|
+
sleep: () => run("systemctl", ["suspend"]),
|
|
288
|
+
screenshot: async (file) => {
|
|
289
|
+
await mkdir(dirname(file), { recursive: true });
|
|
290
|
+
await run("gnome-screenshot", ["-f", file]);
|
|
291
|
+
},
|
|
292
|
+
snip: () => run("gnome-screenshot", ["-a", "-c"]),
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
let controls: Promise<SystemControls> | undefined;
|
|
297
|
+
|
|
298
|
+
/** The controls of this computer, loaded on first use. */
|
|
299
|
+
export function systemControls(): Promise<SystemControls> {
|
|
300
|
+
controls ??=
|
|
301
|
+
process.platform === "win32"
|
|
302
|
+
? windowsControls()
|
|
303
|
+
: Promise.resolve(process.platform === "darwin" ? macControls() : linuxControls());
|
|
304
|
+
return controls;
|
|
305
|
+
}
|