@sdeck/plugin-system 0.0.0-stage → 0.2.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 +2417 -0
- package/dist/index.js.map +24 -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 +1009 -0
- package/src/monitor.ts +432 -0
- package/src/watchers.ts +245 -0
- package/README.md +0 -3
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/** This computer (or what is installed on it) cannot provide a value. */
|
|
2
|
+
export declare class Unavailable extends Error {
|
|
3
|
+
}
|
|
4
|
+
/** Runs a program; a missing one is {@link Unavailable}. */
|
|
5
|
+
export declare function capture(file: string, args: string[], options?: {
|
|
6
|
+
timeoutMs?: number;
|
|
7
|
+
signal?: AbortSignal;
|
|
8
|
+
}): Promise<{
|
|
9
|
+
code: number;
|
|
10
|
+
stdout: string;
|
|
11
|
+
stderr: string;
|
|
12
|
+
}>;
|
|
13
|
+
type Times = {
|
|
14
|
+
idle: number;
|
|
15
|
+
total: number;
|
|
16
|
+
};
|
|
17
|
+
/** Each core's use since the previous call, 0–100. */
|
|
18
|
+
export declare function coreSampler(read?: () => Times[]): () => number[];
|
|
19
|
+
export interface Disk {
|
|
20
|
+
/** 0–100. */
|
|
21
|
+
percent: number;
|
|
22
|
+
free: number;
|
|
23
|
+
total: number;
|
|
24
|
+
}
|
|
25
|
+
/** The disk holding `path`. */
|
|
26
|
+
export declare function diskUsage(path: string): Promise<Disk>;
|
|
27
|
+
/** Bytes moved since the computer started, over its physical interfaces. */
|
|
28
|
+
export interface Counters {
|
|
29
|
+
received: number;
|
|
30
|
+
sent: number;
|
|
31
|
+
}
|
|
32
|
+
export declare function parseProcNetDev(text: string): Counters;
|
|
33
|
+
/** `netstat -ibn`: one `<Link#n>` row per interface, with its byte columns. */
|
|
34
|
+
export declare function parseNetstat(text: string): Counters;
|
|
35
|
+
/** Bytes per second between two readings; counters that went backwards count as zero. */
|
|
36
|
+
export declare function throughput(before: Counters, after: Counters, seconds: number): Counters;
|
|
37
|
+
/** Download and upload speed in bytes per second, about once a second. */
|
|
38
|
+
export declare function watchNetwork(emit: (rate: Counters) => void, onError: (error: Error) => void): () => void;
|
|
39
|
+
/** A host name or address; nothing that `ping` could read as an option. */
|
|
40
|
+
export declare function isHost(host: string): boolean;
|
|
41
|
+
/**
|
|
42
|
+
* The round trip in a `ping` reply, in ms. Output is localised (`time=12ms`, `Zeit<1ms`,
|
|
43
|
+
* `temps=3 ms`), so only the `=`/`<`, the number and `ms` on a line with a TTL are relied on.
|
|
44
|
+
*/
|
|
45
|
+
export declare function parsePing(output: string): number | undefined;
|
|
46
|
+
/** One ping to `host`; its round trip in ms. Rejects when there is no answer. */
|
|
47
|
+
export declare function ping(host: string, signal?: AbortSignal): Promise<number>;
|
|
48
|
+
export interface Gpu {
|
|
49
|
+
name: string;
|
|
50
|
+
/** Percent busy. */
|
|
51
|
+
load: number | undefined;
|
|
52
|
+
/** °C. */
|
|
53
|
+
temperature: number | undefined;
|
|
54
|
+
/** Percent of its memory in use. */
|
|
55
|
+
memory: number | undefined;
|
|
56
|
+
}
|
|
57
|
+
export declare const NVIDIA_QUERY: string[];
|
|
58
|
+
/** The first GPU in `nvidia-smi`'s CSV (`[N/A]` fields are left out). */
|
|
59
|
+
export declare function parseNvidia(csv: string): Gpu | undefined;
|
|
60
|
+
export declare function readGpu(): Promise<Gpu>;
|
|
61
|
+
/** WMI thermal zones are in tenths of a kelvin. */
|
|
62
|
+
export declare function parseThermalZone(output: string): number | undefined;
|
|
63
|
+
/** The CPU temperature in °C, where the system exposes one. */
|
|
64
|
+
export declare function cpuTemperature(thermal?: string): Promise<number>;
|
|
65
|
+
export interface Frame {
|
|
66
|
+
app: string;
|
|
67
|
+
/** Time since the app's previous frame, ms. */
|
|
68
|
+
ms: number;
|
|
69
|
+
}
|
|
70
|
+
/** Reads PresentMon's CSV (1.x and 2.x column names): the header first, then one frame a line. */
|
|
71
|
+
export declare function presentMonParser(): (line: string) => Frame | undefined;
|
|
72
|
+
/**
|
|
73
|
+
* Frames per second of `foreground` among these frames, or else of the app that drew most.
|
|
74
|
+
* `undefined` when nothing drew.
|
|
75
|
+
*/
|
|
76
|
+
export declare function frameRate(frames: readonly Frame[], foreground?: string): number | undefined;
|
|
77
|
+
/** Frames per second once a second, from PresentMon (Windows; it needs administrator rights). */
|
|
78
|
+
export declare function watchFrameRate(command: string, foreground: () => string | undefined, emit: (fps: number | undefined) => void, onError: (error: Error) => void): () => void;
|
|
79
|
+
export {};
|
|
80
|
+
//# sourceMappingURL=monitor.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"monitor.d.ts","sourceRoot":"","sources":["../src/monitor.ts"],"names":[],"mappings":"AAUA,yEAAyE;AACzE,qBAAa,WAAY,SAAQ,KAAK;CAAG;AAEzC,4DAA4D;AAC5D,wBAAgB,OAAO,CACrB,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EAAE,EACd,OAAO,GAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,WAAW,CAAA;CAAO,GACzD,OAAO,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,CAkB3D;AAID,KAAK,KAAK,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAQ7C,sDAAsD;AACtD,wBAAgB,WAAW,CAAC,IAAI,GAAE,MAAM,KAAK,EAAc,GAAG,MAAM,MAAM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,SAAS,CAAC;IAChC,oCAAoC;IACpC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;CAC5B;AAED,eAAO,MAAM,YAAY,UAGxB,CAAC;AAEF,yEAAyE;AACzE,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,GAAG,SAAS,CAkBxD;AAED,wBAAsB,OAAO,IAAI,OAAO,CAAC,GAAG,CAAC,CAK5C;AAKD,mDAAmD;AACnD,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAKnE;AAED,+DAA+D;AAC/D,wBAAsB,cAAc,CAAC,OAAO,SAAuB,GAAG,OAAO,CAAC,MAAM,CAAC,CA+BpF;AAID,MAAM,WAAW,KAAK;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,+CAA+C;IAC/C,EAAE,EAAE,MAAM,CAAC;CACZ;AAED,kGAAkG;AAClG,wBAAgB,gBAAgB,IAAI,CAAC,IAAI,EAAE,MAAM,KAAK,KAAK,GAAG,SAAS,CAgBtE;AAKD;;;GAGG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,SAAS,KAAK,EAAE,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAc3F;AAED,iGAAiG;AACjG,wBAAgB,cAAc,CAC5B,OAAO,EAAE,MAAM,EACf,UAAU,EAAE,MAAM,MAAM,GAAG,SAAS,EACpC,IAAI,EAAE,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,KAAK,IAAI,EACvC,OAAO,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,GAC9B,MAAM,IAAI,CAoCZ"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export { Shared } from "@sdeck/plugin";
|
|
2
|
+
/** What changed between two process lists. */
|
|
3
|
+
export declare function processChanges(before: ReadonlySet<string>, after: ReadonlySet<string>): {
|
|
4
|
+
started: string[];
|
|
5
|
+
stopped: string[];
|
|
6
|
+
};
|
|
7
|
+
/** `*.png`, `report-??.csv` → a case-insensitive RegExp over a file name. Empty = every file. */
|
|
8
|
+
export declare function namePattern(glob: string): RegExp;
|
|
9
|
+
/**
|
|
10
|
+
* Calls `onCreated(name)` for files that appear in `folder` (not ones that only change).
|
|
11
|
+
* Throws when the folder does not exist.
|
|
12
|
+
*/
|
|
13
|
+
export declare function watchFolder(folder: string, onCreated: (name: string) => void): () => void;
|
|
14
|
+
/** Addresses of the non-internal network interfaces, sorted (`"Wi-Fi 192.168.1.4"`). */
|
|
15
|
+
export declare function networkAddresses(): string[];
|
|
16
|
+
/** Whole seconds from a reading in milliseconds (or `undefined` for a bad line). */
|
|
17
|
+
export declare function idleSeconds(line: string, unit?: "ms" | "ns"): number | undefined;
|
|
18
|
+
/**
|
|
19
|
+
* Seconds since the last keyboard or mouse input, every ~2 s. Windows: one PowerShell process
|
|
20
|
+
* reading `GetLastInputInfo`. macOS: `ioreg` HIDIdleTime. Linux: `xprintidle` (X11), if installed.
|
|
21
|
+
*/
|
|
22
|
+
export declare function watchIdle(emit: (seconds: number) => void, onError: (e: Error) => void): () => void;
|
|
23
|
+
/**
|
|
24
|
+
* An executable name as the process list spells it (`javaw.exe`, `firefox`): the last path part,
|
|
25
|
+
* trimmed and lowercased. Empty for nothing in the foreground.
|
|
26
|
+
*/
|
|
27
|
+
export declare function foregroundName(line: string): string;
|
|
28
|
+
/**
|
|
29
|
+
* The executable of the focused window, emitted when it changes (`""` = none, e.g. the desktop
|
|
30
|
+
* has focus). Windows: one PowerShell process reading `GetForegroundWindow`. macOS: System Events
|
|
31
|
+
* via `osascript` (may ask for Automation permission). Linux: `xdotool` (X11), if installed.
|
|
32
|
+
*/
|
|
33
|
+
export declare function watchForeground(emit: (app: string) => void, onError: (e: Error) => void): () => void;
|
|
34
|
+
//# sourceMappingURL=watchers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"watchers.d.ts","sourceRoot":"","sources":["../src/watchers.ts"],"names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|
4
|
+
"description": "Built-in sdeck actions that reach the computer: apps and commands, media keys and shortcuts, power, screenshots and monitoring.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"keywords": [
|
|
9
|
+
"sdeck-plugin"
|
|
10
|
+
],
|
|
11
|
+
"files": [
|
|
12
|
+
"dist",
|
|
13
|
+
"src"
|
|
14
|
+
],
|
|
15
|
+
"main": "./dist/index.js",
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"bun": "./src/index.tsx",
|
|
21
|
+
"import": "./dist/index.js"
|
|
22
|
+
},
|
|
23
|
+
"./package.json": "./package.json"
|
|
24
|
+
},
|
|
25
|
+
"sdeck": {
|
|
26
|
+
"apiVersion": 2,
|
|
27
|
+
"entry": "./dist/index.js"
|
|
28
|
+
},
|
|
29
|
+
"scripts": {
|
|
30
|
+
"build": "bun ../../scripts/build-package.ts --target=bun",
|
|
31
|
+
"clean": "rm -rf dist",
|
|
32
|
+
"test": "bun test"
|
|
33
|
+
},
|
|
34
|
+
"peerDependencies": {
|
|
35
|
+
"@sdeck/plugin": "^0.1.0",
|
|
36
|
+
"@sdeck/schema": "^0.1.0",
|
|
37
|
+
"react": ">=19.3"
|
|
38
|
+
},
|
|
39
|
+
"peerDependenciesMeta": {
|
|
40
|
+
"@sdeck/plugin": {
|
|
41
|
+
"optional": true
|
|
42
|
+
},
|
|
43
|
+
"@sdeck/schema": {
|
|
44
|
+
"optional": true
|
|
45
|
+
},
|
|
46
|
+
"react": {
|
|
47
|
+
"optional": true
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@sdeck/plugin": "0.1.0",
|
|
52
|
+
"@sdeck/schema": "0.1.0"
|
|
53
|
+
},
|
|
54
|
+
"repository": {
|
|
55
|
+
"type": "git",
|
|
56
|
+
"url": "git+https://github.com/ivanoliverfabra/sdeck.git",
|
|
57
|
+
"directory": "packages/plugin-system"
|
|
58
|
+
},
|
|
59
|
+
"publishConfig": {
|
|
60
|
+
"access": "public"
|
|
61
|
+
}
|
|
62
|
+
}
|
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
|
+
}
|