@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/dist/index.js
ADDED
|
@@ -0,0 +1,1731 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/index.tsx
|
|
3
|
+
import { execFile as execFile3, spawn as spawn3 } from "child_process";
|
|
4
|
+
import { cpus as cpus2, freemem, homedir as homedir3, totalmem } from "os";
|
|
5
|
+
import { basename, join as join3 } from "path";
|
|
6
|
+
import {
|
|
7
|
+
defineAction,
|
|
8
|
+
definePlugin,
|
|
9
|
+
defineTrigger,
|
|
10
|
+
Shared as Shared2
|
|
11
|
+
} from "@sdeck/plugin";
|
|
12
|
+
import {
|
|
13
|
+
formatAccelerator,
|
|
14
|
+
iconLayer,
|
|
15
|
+
iconLook,
|
|
16
|
+
parseAccelerator as parseAccelerator2,
|
|
17
|
+
textLayer
|
|
18
|
+
} from "@sdeck/schema";
|
|
19
|
+
|
|
20
|
+
// src/controls.ts
|
|
21
|
+
import { execFile } from "child_process";
|
|
22
|
+
import { mkdir } from "fs/promises";
|
|
23
|
+
import { dirname } from "path";
|
|
24
|
+
import { MODIFIER_CODES, parseAccelerator } from "@sdeck/schema";
|
|
25
|
+
var MEDIA_KEYS = {
|
|
26
|
+
"play-pause": "playpause",
|
|
27
|
+
next: "medianext",
|
|
28
|
+
previous: "mediaprevious",
|
|
29
|
+
stop: "mediastop",
|
|
30
|
+
mute: "volumemute",
|
|
31
|
+
"volume-up": "volumeup",
|
|
32
|
+
"volume-down": "volumedown"
|
|
33
|
+
};
|
|
34
|
+
var EXTENDED = 1;
|
|
35
|
+
var KEY_UP = 2;
|
|
36
|
+
var UNICODE = 4;
|
|
37
|
+
var EXTENDED_KEYS = new Set([
|
|
38
|
+
33,
|
|
39
|
+
34,
|
|
40
|
+
35,
|
|
41
|
+
36,
|
|
42
|
+
37,
|
|
43
|
+
38,
|
|
44
|
+
39,
|
|
45
|
+
40,
|
|
46
|
+
44,
|
|
47
|
+
45,
|
|
48
|
+
46,
|
|
49
|
+
91,
|
|
50
|
+
93,
|
|
51
|
+
111,
|
|
52
|
+
144,
|
|
53
|
+
173,
|
|
54
|
+
174,
|
|
55
|
+
175,
|
|
56
|
+
176,
|
|
57
|
+
177,
|
|
58
|
+
178,
|
|
59
|
+
179
|
|
60
|
+
]);
|
|
61
|
+
function hotkeyEvents(accelerator) {
|
|
62
|
+
const codes = [...accelerator.modifiers.map((m) => MODIFIER_CODES[m]), accelerator.code];
|
|
63
|
+
const event = (vk, up) => ({
|
|
64
|
+
vk,
|
|
65
|
+
scan: 0,
|
|
66
|
+
flags: (EXTENDED_KEYS.has(vk) ? EXTENDED : 0) | (up ? KEY_UP : 0)
|
|
67
|
+
});
|
|
68
|
+
return [...codes.map((c) => event(c, false)), ...codes.reverse().map((c) => event(c, true))];
|
|
69
|
+
}
|
|
70
|
+
function textEvents(text) {
|
|
71
|
+
const events = [];
|
|
72
|
+
const normalized = text.replace(/\r\n?/g, `
|
|
73
|
+
`);
|
|
74
|
+
for (let i = 0;i < normalized.length; i++) {
|
|
75
|
+
const unit = normalized.charCodeAt(i);
|
|
76
|
+
if (unit === 10 || unit === 9) {
|
|
77
|
+
const vk = unit === 10 ? 13 : 9;
|
|
78
|
+
events.push({ vk, scan: 0, flags: 0 }, { vk, scan: 0, flags: KEY_UP });
|
|
79
|
+
} else {
|
|
80
|
+
events.push({ vk: 0, scan: unit, flags: UNICODE }, { vk: 0, scan: unit, flags: UNICODE | KEY_UP });
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return events;
|
|
84
|
+
}
|
|
85
|
+
var INPUT_SIZE = 40;
|
|
86
|
+
function encodeInputs(events) {
|
|
87
|
+
const buffer = new Uint8Array(events.length * INPUT_SIZE);
|
|
88
|
+
const view = new DataView(buffer.buffer);
|
|
89
|
+
events.forEach((event, i) => {
|
|
90
|
+
const at = i * INPUT_SIZE;
|
|
91
|
+
view.setUint32(at, 1, true);
|
|
92
|
+
view.setUint16(at + 8, event.vk, true);
|
|
93
|
+
view.setUint16(at + 10, event.scan, true);
|
|
94
|
+
view.setUint32(at + 12, event.flags, true);
|
|
95
|
+
});
|
|
96
|
+
return buffer;
|
|
97
|
+
}
|
|
98
|
+
function run(file, args, env) {
|
|
99
|
+
return new Promise((resolve, reject) => {
|
|
100
|
+
execFile(file, args, { windowsHide: true, timeout: 30000, ...env && { env: { ...process.env, ...env } } }, (error, _stdout, stderr) => {
|
|
101
|
+
if (!error)
|
|
102
|
+
return resolve();
|
|
103
|
+
if (error.code === "ENOENT") {
|
|
104
|
+
return reject(new Error(`this needs "${file}", which is not installed`));
|
|
105
|
+
}
|
|
106
|
+
reject(new Error(stderr.trim() || error.message));
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
var WINDOWS_SCREENSHOT = `
|
|
111
|
+
$ErrorActionPreference = "Stop"
|
|
112
|
+
Add-Type -AssemblyName System.Windows.Forms, System.Drawing
|
|
113
|
+
Add-Type -Name Dpi -Namespace Sdeck -MemberDefinition '[System.Runtime.InteropServices.DllImport("user32.dll")] public static extern bool SetProcessDPIAware();'
|
|
114
|
+
[void][Sdeck.Dpi]::SetProcessDPIAware()
|
|
115
|
+
$area = [System.Windows.Forms.SystemInformation]::VirtualScreen
|
|
116
|
+
$image = New-Object System.Drawing.Bitmap $area.Width, $area.Height
|
|
117
|
+
$graphics = [System.Drawing.Graphics]::FromImage($image)
|
|
118
|
+
$graphics.CopyFromScreen($area.Location, [System.Drawing.Point]::Empty, $area.Size)
|
|
119
|
+
$image.Save($env:SDECK_SCREENSHOT, [System.Drawing.Imaging.ImageFormat]::Png)
|
|
120
|
+
$graphics.Dispose(); $image.Dispose()
|
|
121
|
+
`;
|
|
122
|
+
async function windowsControls() {
|
|
123
|
+
const { dlopen, FFIType, ptr } = await import("bun:ffi");
|
|
124
|
+
const user32 = dlopen("user32.dll", {
|
|
125
|
+
SendInput: { args: [FFIType.u32, FFIType.ptr, FFIType.i32], returns: FFIType.u32 },
|
|
126
|
+
LockWorkStation: { args: [], returns: FFIType.i32 }
|
|
127
|
+
});
|
|
128
|
+
const power = dlopen("powrprof.dll", {
|
|
129
|
+
SetSuspendState: { args: [FFIType.u8, FFIType.u8, FFIType.u8], returns: FFIType.u8 }
|
|
130
|
+
});
|
|
131
|
+
const send = (events) => {
|
|
132
|
+
for (let i = 0;i < events.length; i += 200) {
|
|
133
|
+
const batch = events.slice(i, i + 200);
|
|
134
|
+
const sent = user32.symbols.SendInput(batch.length, ptr(encodeInputs(batch)), INPUT_SIZE);
|
|
135
|
+
if (sent !== batch.length) {
|
|
136
|
+
throw new Error("Windows blocked the input (is the focused app running as administrator?)");
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
return {
|
|
141
|
+
media: async (key) => send(hotkeyEvents(parseAccelerator(MEDIA_KEYS[key]))),
|
|
142
|
+
hotkey: async (accelerator) => send(hotkeyEvents(accelerator)),
|
|
143
|
+
type: async (text) => send(textEvents(text)),
|
|
144
|
+
lock: async () => {
|
|
145
|
+
if (!user32.symbols.LockWorkStation())
|
|
146
|
+
throw new Error("Windows refused to lock");
|
|
147
|
+
},
|
|
148
|
+
sleep: async () => {
|
|
149
|
+
if (!power.symbols.SetSuspendState(0, 0, 0))
|
|
150
|
+
throw new Error("Windows refused to sleep");
|
|
151
|
+
},
|
|
152
|
+
screenshot: async (file) => {
|
|
153
|
+
await mkdir(dirname(file), { recursive: true });
|
|
154
|
+
const encoded = Buffer.from(WINDOWS_SCREENSHOT, "utf16le").toString("base64");
|
|
155
|
+
await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], {
|
|
156
|
+
SDECK_SCREENSHOT: file
|
|
157
|
+
});
|
|
158
|
+
},
|
|
159
|
+
snip: async () => send(hotkeyEvents(parseAccelerator("win+shift+s")))
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
var appleString = (text) => `"${text.replace(/[\\"]/g, "\\$&")}"`;
|
|
163
|
+
var MAC_KEY_CODES = {
|
|
164
|
+
enter: 36,
|
|
165
|
+
tab: 48,
|
|
166
|
+
space: 49,
|
|
167
|
+
backspace: 51,
|
|
168
|
+
escape: 53,
|
|
169
|
+
left: 123,
|
|
170
|
+
right: 124,
|
|
171
|
+
down: 125,
|
|
172
|
+
up: 126
|
|
173
|
+
};
|
|
174
|
+
var MAC_MODIFIERS = {
|
|
175
|
+
ctrl: "control down",
|
|
176
|
+
alt: "option down",
|
|
177
|
+
shift: "shift down",
|
|
178
|
+
win: "command down"
|
|
179
|
+
};
|
|
180
|
+
function macHotkey(accelerator) {
|
|
181
|
+
const { key, modifiers } = accelerator;
|
|
182
|
+
const code = MAC_KEY_CODES[key];
|
|
183
|
+
if (code === undefined && key.length !== 1) {
|
|
184
|
+
throw new Error(`"${key}" cannot be sent on macOS`);
|
|
185
|
+
}
|
|
186
|
+
const press = code === undefined ? `keystroke ${appleString(key)}` : `key code ${code}`;
|
|
187
|
+
const using = modifiers.length > 0 ? ` using {${modifiers.map((m) => MAC_MODIFIERS[m]).join(", ")}}` : "";
|
|
188
|
+
return `tell application "System Events" to ${press}${using}`;
|
|
189
|
+
}
|
|
190
|
+
function macControls() {
|
|
191
|
+
const script = (source) => run("osascript", ["-e", source]);
|
|
192
|
+
const volume = (change) => script(`set volume output volume ((output volume of (get volume settings)) ${change})`);
|
|
193
|
+
return {
|
|
194
|
+
media: async (key) => {
|
|
195
|
+
if (key === "volume-up")
|
|
196
|
+
return volume("+ 6");
|
|
197
|
+
if (key === "volume-down")
|
|
198
|
+
return volume("- 6");
|
|
199
|
+
if (key === "mute") {
|
|
200
|
+
return script("set volume output muted not (output muted of (get volume settings))");
|
|
201
|
+
}
|
|
202
|
+
throw new Error("playback keys are not available on macOS");
|
|
203
|
+
},
|
|
204
|
+
hotkey: async (accelerator) => script(macHotkey(accelerator)),
|
|
205
|
+
type: (text) => script(`tell application "System Events" to keystroke ${appleString(text)}`),
|
|
206
|
+
lock: () => run("pmset", ["displaysleepnow"]),
|
|
207
|
+
sleep: () => run("pmset", ["sleepnow"]),
|
|
208
|
+
screenshot: async (file) => {
|
|
209
|
+
await mkdir(dirname(file), { recursive: true });
|
|
210
|
+
await run("screencapture", ["-x", file]);
|
|
211
|
+
},
|
|
212
|
+
snip: () => run("screencapture", ["-i", "-c"])
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
var X_KEYS = {
|
|
216
|
+
enter: "Return",
|
|
217
|
+
escape: "Escape",
|
|
218
|
+
backspace: "BackSpace",
|
|
219
|
+
tab: "Tab",
|
|
220
|
+
space: "space",
|
|
221
|
+
delete: "Delete",
|
|
222
|
+
insert: "Insert",
|
|
223
|
+
home: "Home",
|
|
224
|
+
end: "End",
|
|
225
|
+
pageup: "Prior",
|
|
226
|
+
pagedown: "Next",
|
|
227
|
+
left: "Left",
|
|
228
|
+
right: "Right",
|
|
229
|
+
up: "Up",
|
|
230
|
+
down: "Down",
|
|
231
|
+
printscreen: "Print",
|
|
232
|
+
playpause: "XF86AudioPlay",
|
|
233
|
+
medianext: "XF86AudioNext",
|
|
234
|
+
mediaprevious: "XF86AudioPrev",
|
|
235
|
+
mediastop: "XF86AudioStop",
|
|
236
|
+
volumemute: "XF86AudioMute",
|
|
237
|
+
volumeup: "XF86AudioRaiseVolume",
|
|
238
|
+
volumedown: "XF86AudioLowerVolume"
|
|
239
|
+
};
|
|
240
|
+
var X_MODIFIERS = { ctrl: "ctrl", alt: "alt", shift: "shift", win: "super" };
|
|
241
|
+
function xHotkey(accelerator) {
|
|
242
|
+
const { key, modifiers } = accelerator;
|
|
243
|
+
const name = X_KEYS[key] ?? (/^f\d+$/.test(key) ? key.toUpperCase() : key);
|
|
244
|
+
return [...modifiers.map((m) => X_MODIFIERS[m]), name].join("+");
|
|
245
|
+
}
|
|
246
|
+
function linuxControls() {
|
|
247
|
+
const hotkey = (accelerator) => run("xdotool", ["key", xHotkey(accelerator)]);
|
|
248
|
+
return {
|
|
249
|
+
media: (key) => hotkey(parseAccelerator(MEDIA_KEYS[key])),
|
|
250
|
+
hotkey,
|
|
251
|
+
type: (text) => run("xdotool", ["type", "--clearmodifiers", "--", text]),
|
|
252
|
+
lock: () => run("loginctl", ["lock-session"]),
|
|
253
|
+
sleep: () => run("systemctl", ["suspend"]),
|
|
254
|
+
screenshot: async (file) => {
|
|
255
|
+
await mkdir(dirname(file), { recursive: true });
|
|
256
|
+
await run("gnome-screenshot", ["-f", file]);
|
|
257
|
+
},
|
|
258
|
+
snip: () => run("gnome-screenshot", ["-a", "-c"])
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
var controls;
|
|
262
|
+
function systemControls() {
|
|
263
|
+
controls ??= process.platform === "win32" ? windowsControls() : Promise.resolve(process.platform === "darwin" ? macControls() : linuxControls());
|
|
264
|
+
return controls;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// src/monitor.ts
|
|
268
|
+
import { execFile as execFile2, spawn } from "child_process";
|
|
269
|
+
import { readdir, readFile, statfs } from "fs/promises";
|
|
270
|
+
import { cpus, homedir } from "os";
|
|
271
|
+
import { join } from "path";
|
|
272
|
+
|
|
273
|
+
class Unavailable extends Error {
|
|
274
|
+
}
|
|
275
|
+
function capture(file, args, options = {}) {
|
|
276
|
+
return new Promise((resolve, reject) => {
|
|
277
|
+
execFile2(file, args, {
|
|
278
|
+
windowsHide: true,
|
|
279
|
+
timeout: options.timeoutMs ?? 1e4,
|
|
280
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
281
|
+
...options.signal && { signal: options.signal }
|
|
282
|
+
}, (error, stdout, stderr) => {
|
|
283
|
+
const code = error ? error.code : 0;
|
|
284
|
+
if (code === "ENOENT")
|
|
285
|
+
return reject(new Unavailable(`"${file}" is not installed`));
|
|
286
|
+
resolve({ code: typeof code === "number" ? code : -1, stdout, stderr });
|
|
287
|
+
});
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
var coreTimes = () => cpus().map(({ times: t }) => ({
|
|
291
|
+
idle: t.idle,
|
|
292
|
+
total: t.user + t.nice + t.sys + t.irq + t.idle
|
|
293
|
+
}));
|
|
294
|
+
function coreSampler(read = coreTimes) {
|
|
295
|
+
let last = read();
|
|
296
|
+
return () => {
|
|
297
|
+
const now = read();
|
|
298
|
+
const out = now.map((core, i) => {
|
|
299
|
+
const total = core.total - (last[i]?.total ?? 0);
|
|
300
|
+
const idle = core.idle - (last[i]?.idle ?? 0);
|
|
301
|
+
return total > 0 ? Math.round(100 * (1 - idle / total)) : 0;
|
|
302
|
+
});
|
|
303
|
+
last = now;
|
|
304
|
+
return out;
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
async function diskUsage(path) {
|
|
308
|
+
const s = await statfs(path);
|
|
309
|
+
const total = s.blocks * s.bsize;
|
|
310
|
+
const free = s.bavail * s.bsize;
|
|
311
|
+
if (total <= 0)
|
|
312
|
+
throw new Unavailable(`no size for ${path}`);
|
|
313
|
+
return { percent: Math.round(100 * (1 - free / total)), free, total };
|
|
314
|
+
}
|
|
315
|
+
var VIRTUAL = /^(lo|docker|veth|br-|virbr|vmnet|utun|awdl|llw|bridge)/;
|
|
316
|
+
function parseProcNetDev(text) {
|
|
317
|
+
const total = { received: 0, sent: 0 };
|
|
318
|
+
for (const line of text.split(`
|
|
319
|
+
`)) {
|
|
320
|
+
const match = /^\s*([^:]+):\s*(.*)$/.exec(line);
|
|
321
|
+
if (!match?.[1] || VIRTUAL.test(match[1].trim()))
|
|
322
|
+
continue;
|
|
323
|
+
const fields = (match[2] ?? "").trim().split(/\s+/).map(Number);
|
|
324
|
+
total.received += fields[0] || 0;
|
|
325
|
+
total.sent += fields[8] || 0;
|
|
326
|
+
}
|
|
327
|
+
return total;
|
|
328
|
+
}
|
|
329
|
+
function parseNetstat(text) {
|
|
330
|
+
const total = { received: 0, sent: 0 };
|
|
331
|
+
const lines = text.split(`
|
|
332
|
+
`);
|
|
333
|
+
const header = (lines[0] ?? "").trim().split(/\s+/);
|
|
334
|
+
const fromEnd = (name) => header.length - header.indexOf(name);
|
|
335
|
+
for (const line of lines.slice(1)) {
|
|
336
|
+
const fields = line.trim().split(/\s+/);
|
|
337
|
+
if (!fields[0] || VIRTUAL.test(fields[0]) || !fields[2]?.startsWith("<Link"))
|
|
338
|
+
continue;
|
|
339
|
+
total.received += Number(fields[fields.length - fromEnd("Ibytes")]) || 0;
|
|
340
|
+
total.sent += Number(fields[fields.length - fromEnd("Obytes")]) || 0;
|
|
341
|
+
}
|
|
342
|
+
return total;
|
|
343
|
+
}
|
|
344
|
+
function throughput(before, after, seconds) {
|
|
345
|
+
const rate = (a, b) => seconds > 0 ? Math.max(0, Math.round((b - a) / seconds)) : 0;
|
|
346
|
+
return {
|
|
347
|
+
received: rate(before.received, after.received),
|
|
348
|
+
sent: rate(before.sent, after.sent)
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
var WINDOWS_NETWORK = `
|
|
352
|
+
while ($true) {
|
|
353
|
+
$rx = 0; $tx = 0
|
|
354
|
+
foreach ($n in [System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()) {
|
|
355
|
+
if ($n.OperationalStatus -ne 'Up' -or $n.NetworkInterfaceType -eq 'Loopback' -or $n.NetworkInterfaceType -eq 'Tunnel') { continue }
|
|
356
|
+
if ($n.Description -match 'Virtual|Hyper-V|vEthernet|Filter|VirtualBox|VMware') { continue }
|
|
357
|
+
$s = $n.GetIPStatistics(); $rx += $s.BytesReceived; $tx += $s.BytesSent
|
|
358
|
+
}
|
|
359
|
+
[Console]::Out.WriteLine("$rx $tx"); [Console]::Out.Flush()
|
|
360
|
+
Start-Sleep -Seconds 1
|
|
361
|
+
}
|
|
362
|
+
`;
|
|
363
|
+
function lines(child, read, onError) {
|
|
364
|
+
let buffer = "";
|
|
365
|
+
let stopped = false;
|
|
366
|
+
child.stdout?.setEncoding("utf8");
|
|
367
|
+
child.stdout?.on("data", (chunk) => {
|
|
368
|
+
buffer += chunk;
|
|
369
|
+
const parts = buffer.split(/\r?\n/);
|
|
370
|
+
buffer = parts.pop() ?? "";
|
|
371
|
+
for (const line of parts)
|
|
372
|
+
read(line);
|
|
373
|
+
});
|
|
374
|
+
child.once("error", (error) => {
|
|
375
|
+
stopped = true;
|
|
376
|
+
const missing = error.code === "ENOENT";
|
|
377
|
+
onError(missing ? new Unavailable(`"${child.spawnfile}" is not installed`) : error);
|
|
378
|
+
});
|
|
379
|
+
child.once("close", (code) => {
|
|
380
|
+
if (!stopped && code !== 0)
|
|
381
|
+
onError(new Unavailable(`"${child.spawnfile}" exited (${code})`));
|
|
382
|
+
});
|
|
383
|
+
return () => {
|
|
384
|
+
stopped = true;
|
|
385
|
+
child.kill();
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
function watchNetwork(emit, onError) {
|
|
389
|
+
let last;
|
|
390
|
+
const sample = (counters) => {
|
|
391
|
+
const at = performance.now();
|
|
392
|
+
if (last)
|
|
393
|
+
emit(throughput(last.counters, counters, (at - last.at) / 1000));
|
|
394
|
+
last = { counters, at };
|
|
395
|
+
};
|
|
396
|
+
if (process.platform === "win32") {
|
|
397
|
+
const encoded = Buffer.from(WINDOWS_NETWORK, "utf16le").toString("base64");
|
|
398
|
+
const child = spawn("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], { cwd: homedir(), stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
|
|
399
|
+
return lines(child, (line) => {
|
|
400
|
+
const [received, sent] = line.trim().split(" ").map(Number);
|
|
401
|
+
if (Number.isFinite(received) && Number.isFinite(sent)) {
|
|
402
|
+
sample({ received, sent });
|
|
403
|
+
}
|
|
404
|
+
}, onError);
|
|
405
|
+
}
|
|
406
|
+
const read = async () => {
|
|
407
|
+
try {
|
|
408
|
+
sample(process.platform === "darwin" ? parseNetstat((await capture("netstat", ["-ibn"])).stdout) : parseProcNetDev(await readFile("/proc/net/dev", "utf8")));
|
|
409
|
+
} catch (error) {
|
|
410
|
+
onError(error);
|
|
411
|
+
}
|
|
412
|
+
};
|
|
413
|
+
read();
|
|
414
|
+
const timer = setInterval(read, 1000);
|
|
415
|
+
return () => clearInterval(timer);
|
|
416
|
+
}
|
|
417
|
+
function isHost(host) {
|
|
418
|
+
return /^[A-Za-z0-9_[][A-Za-z0-9_.:%[\]-]{0,252}$/.test(host);
|
|
419
|
+
}
|
|
420
|
+
function parsePing(output) {
|
|
421
|
+
for (const line of output.split(/\r?\n/)) {
|
|
422
|
+
if (!/ttl/i.test(line) && !/time[=<]/i.test(line))
|
|
423
|
+
continue;
|
|
424
|
+
const match = /[=<]\s*([\d.,]+)\s*ms/i.exec(line);
|
|
425
|
+
if (match?.[1])
|
|
426
|
+
return Number(match[1].replace(",", "."));
|
|
427
|
+
}
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
async function ping(host, signal) {
|
|
431
|
+
const target = host.trim();
|
|
432
|
+
if (!isHost(target))
|
|
433
|
+
throw new Error(`"${host}" is not a host name or address`);
|
|
434
|
+
const args = process.platform === "win32" ? ["-n", "1", "-w", "2000", target] : ["-c", "1", "-W", process.platform === "darwin" ? "2000" : "2", target];
|
|
435
|
+
const { stdout } = await capture("ping", args, { timeoutMs: 5000, ...signal && { signal } });
|
|
436
|
+
const ms = parsePing(stdout);
|
|
437
|
+
if (ms === undefined)
|
|
438
|
+
throw new Error(`${target} did not answer`);
|
|
439
|
+
return ms;
|
|
440
|
+
}
|
|
441
|
+
var NVIDIA_QUERY = [
|
|
442
|
+
"--query-gpu=name,utilization.gpu,temperature.gpu,memory.used,memory.total",
|
|
443
|
+
"--format=csv,noheader,nounits"
|
|
444
|
+
];
|
|
445
|
+
function parseNvidia(csv) {
|
|
446
|
+
const fields = csv.split(/\r?\n/)[0]?.split(",").map((f) => f.trim());
|
|
447
|
+
if (!fields || fields.length < 5 || !fields[0])
|
|
448
|
+
return;
|
|
449
|
+
const number = (text) => {
|
|
450
|
+
const n = Number(text);
|
|
451
|
+
return text && Number.isFinite(n) ? n : undefined;
|
|
452
|
+
};
|
|
453
|
+
const used = number(fields[3]);
|
|
454
|
+
const total = number(fields[4]);
|
|
455
|
+
return {
|
|
456
|
+
name: fields[0],
|
|
457
|
+
load: number(fields[1]),
|
|
458
|
+
temperature: number(fields[2]),
|
|
459
|
+
memory: used !== undefined && total ? Math.round(100 * used / total) : undefined
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
async function readGpu() {
|
|
463
|
+
const { code, stdout, stderr } = await capture("nvidia-smi", NVIDIA_QUERY);
|
|
464
|
+
const gpu = code === 0 ? parseNvidia(stdout) : undefined;
|
|
465
|
+
if (!gpu)
|
|
466
|
+
throw new Unavailable(stderr.trim() || "nvidia-smi reported no GPU");
|
|
467
|
+
return gpu;
|
|
468
|
+
}
|
|
469
|
+
var WINDOWS_TEMPERATURE = "(Get-CimInstance -Namespace root/wmi -ClassName MSAcpi_ThermalZoneTemperature -ErrorAction Stop | Measure-Object -Property CurrentTemperature -Maximum).Maximum";
|
|
470
|
+
function parseThermalZone(output) {
|
|
471
|
+
const raw = Number(output.trim());
|
|
472
|
+
return output.trim() && Number.isFinite(raw) && raw > 0 ? Math.round(raw / 10 - 273.15) : undefined;
|
|
473
|
+
}
|
|
474
|
+
async function cpuTemperature(thermal = "/sys/class/thermal") {
|
|
475
|
+
if (process.platform === "win32") {
|
|
476
|
+
const { code, stdout } = await capture("powershell.exe", [
|
|
477
|
+
"-NoProfile",
|
|
478
|
+
"-NonInteractive",
|
|
479
|
+
"-Command",
|
|
480
|
+
WINDOWS_TEMPERATURE
|
|
481
|
+
]);
|
|
482
|
+
const value = code === 0 ? parseThermalZone(stdout) : undefined;
|
|
483
|
+
if (value === undefined) {
|
|
484
|
+
throw new Unavailable("Windows exposes no thermal zone (common on desktops; it may need administrator rights)");
|
|
485
|
+
}
|
|
486
|
+
return value;
|
|
487
|
+
}
|
|
488
|
+
const readings = [];
|
|
489
|
+
for (const zone of await readdir(thermal).catch(() => [])) {
|
|
490
|
+
if (!zone.startsWith("thermal_zone"))
|
|
491
|
+
continue;
|
|
492
|
+
try {
|
|
493
|
+
const type = (await readFile(join(thermal, zone, "type"), "utf8")).trim();
|
|
494
|
+
const value = Number(await readFile(join(thermal, zone, "temp"), "utf8")) / 1000;
|
|
495
|
+
if (Number.isFinite(value))
|
|
496
|
+
readings.push({ type, value });
|
|
497
|
+
} catch {}
|
|
498
|
+
}
|
|
499
|
+
const cpu = readings.filter((r) => /pkg|cpu|k10|core/i.test(r.type));
|
|
500
|
+
const pool = cpu.length > 0 ? cpu : readings;
|
|
501
|
+
if (pool.length === 0)
|
|
502
|
+
throw new Unavailable("no temperature sensor is exposed");
|
|
503
|
+
return Math.round(Math.max(...pool.map((r) => r.value)));
|
|
504
|
+
}
|
|
505
|
+
function presentMonParser() {
|
|
506
|
+
let app = -1;
|
|
507
|
+
let time = -1;
|
|
508
|
+
return (line) => {
|
|
509
|
+
const fields = line.split(",");
|
|
510
|
+
if (time < 0) {
|
|
511
|
+
const names = fields.map((f) => f.trim().toLowerCase());
|
|
512
|
+
app = names.indexOf("application");
|
|
513
|
+
time = ["msbetweenpresents", "frametime"].map((n) => names.indexOf(n)).find((i) => i >= 0) ?? -1;
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
const ms = Number(fields[time]);
|
|
517
|
+
const name = fields[app]?.trim().toLowerCase();
|
|
518
|
+
return name && Number.isFinite(ms) && ms > 0 ? { app: name, ms } : undefined;
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
var COMPOSITORS = new Set(["dwm.exe"]);
|
|
522
|
+
function frameRate(frames, foreground) {
|
|
523
|
+
const byApp = new Map;
|
|
524
|
+
for (const frame of frames) {
|
|
525
|
+
if (COMPOSITORS.has(frame.app))
|
|
526
|
+
continue;
|
|
527
|
+
const list = byApp.get(frame.app);
|
|
528
|
+
if (list)
|
|
529
|
+
list.push(frame);
|
|
530
|
+
else
|
|
531
|
+
byApp.set(frame.app, [frame]);
|
|
532
|
+
}
|
|
533
|
+
const chosen = (foreground ? byApp.get(foreground.toLowerCase()) : undefined) ?? [...byApp.values()].sort((a, b) => b.length - a.length)[0];
|
|
534
|
+
if (!chosen)
|
|
535
|
+
return;
|
|
536
|
+
const total = chosen.reduce((sum, f) => sum + f.ms, 0);
|
|
537
|
+
return Math.round(1000 * chosen.length / total);
|
|
538
|
+
}
|
|
539
|
+
function watchFrameRate(command, foreground, emit, onError) {
|
|
540
|
+
if (process.platform !== "win32") {
|
|
541
|
+
onError(new Unavailable("frame rates need PresentMon, which is Windows only"));
|
|
542
|
+
return () => {};
|
|
543
|
+
}
|
|
544
|
+
const parse = presentMonParser();
|
|
545
|
+
let frames = [];
|
|
546
|
+
const child = spawn(command, ["--output_stdout", "--stop_existing_session"], {
|
|
547
|
+
cwd: homedir(),
|
|
548
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
549
|
+
windowsHide: true
|
|
550
|
+
});
|
|
551
|
+
const stop = lines(child, (line) => {
|
|
552
|
+
const frame = parse(line);
|
|
553
|
+
if (frame)
|
|
554
|
+
frames.push(frame);
|
|
555
|
+
}, (error) => {
|
|
556
|
+
clearInterval(timer);
|
|
557
|
+
emit(undefined);
|
|
558
|
+
onError(new Unavailable(`${error.message}. Install PresentMon and run sdeck as administrator (or add your user to "Performance Log Users")`));
|
|
559
|
+
});
|
|
560
|
+
const timer = setInterval(() => {
|
|
561
|
+
emit(frameRate(frames, foreground()));
|
|
562
|
+
frames = [];
|
|
563
|
+
}, 1000);
|
|
564
|
+
return () => {
|
|
565
|
+
clearInterval(timer);
|
|
566
|
+
stop();
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
// src/watchers.ts
|
|
571
|
+
import { spawn as spawn2 } from "child_process";
|
|
572
|
+
import { existsSync, readdirSync, watch } from "fs";
|
|
573
|
+
import { homedir as homedir2, networkInterfaces } from "os";
|
|
574
|
+
import { join as join2 } from "path";
|
|
575
|
+
import { Shared } from "@sdeck/plugin";
|
|
576
|
+
function processChanges(before, after) {
|
|
577
|
+
return {
|
|
578
|
+
started: [...after].filter((p) => !before.has(p)),
|
|
579
|
+
stopped: [...before].filter((p) => !after.has(p))
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
function namePattern(glob) {
|
|
583
|
+
const trimmed = glob.trim();
|
|
584
|
+
if (!trimmed)
|
|
585
|
+
return /^/;
|
|
586
|
+
const escaped = trimmed.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
587
|
+
return new RegExp(`^${escaped.replace(/\*/g, ".*").replace(/\?/g, ".")}$`, "i");
|
|
588
|
+
}
|
|
589
|
+
function watchFolder(folder, onCreated) {
|
|
590
|
+
if (!existsSync(folder))
|
|
591
|
+
throw new Error(`folder "${folder}" does not exist`);
|
|
592
|
+
const known = new Set(readdirSync(folder));
|
|
593
|
+
let watcher = watch(folder, (_event, name) => {
|
|
594
|
+
if (!name)
|
|
595
|
+
return;
|
|
596
|
+
const file = String(name);
|
|
597
|
+
const exists = existsSync(join2(folder, file));
|
|
598
|
+
if (exists && !known.has(file)) {
|
|
599
|
+
known.add(file);
|
|
600
|
+
onCreated(file);
|
|
601
|
+
} else if (!exists)
|
|
602
|
+
known.delete(file);
|
|
603
|
+
});
|
|
604
|
+
watcher.on("error", () => {
|
|
605
|
+
watcher?.close();
|
|
606
|
+
watcher = undefined;
|
|
607
|
+
});
|
|
608
|
+
return () => watcher?.close();
|
|
609
|
+
}
|
|
610
|
+
function networkAddresses() {
|
|
611
|
+
const out = [];
|
|
612
|
+
for (const [name, addresses] of Object.entries(networkInterfaces())) {
|
|
613
|
+
for (const a of addresses ?? [])
|
|
614
|
+
if (!a.internal)
|
|
615
|
+
out.push(`${name} ${a.address}`);
|
|
616
|
+
}
|
|
617
|
+
return out.sort();
|
|
618
|
+
}
|
|
619
|
+
var WINDOWS_IDLE = `
|
|
620
|
+
Add-Type @'
|
|
621
|
+
using System;
|
|
622
|
+
using System.Runtime.InteropServices;
|
|
623
|
+
public static class SdeckIdle {
|
|
624
|
+
[StructLayout(LayoutKind.Sequential)] struct Info { public uint Size; public uint Time; }
|
|
625
|
+
[DllImport("user32.dll")] static extern bool GetLastInputInfo(ref Info info);
|
|
626
|
+
public static long Ms() {
|
|
627
|
+
var info = new Info(); info.Size = (uint)Marshal.SizeOf(info);
|
|
628
|
+
if (!GetLastInputInfo(ref info)) return -1;
|
|
629
|
+
return (long)(uint)((uint)Environment.TickCount - info.Time);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
'@
|
|
633
|
+
while ($true) { [Console]::Out.WriteLine([SdeckIdle]::Ms()); [Console]::Out.Flush(); Start-Sleep -Seconds 2 }
|
|
634
|
+
`;
|
|
635
|
+
function idleSeconds(line, unit = "ms") {
|
|
636
|
+
const n = Number(line.trim());
|
|
637
|
+
if (!Number.isFinite(n) || n < 0)
|
|
638
|
+
return;
|
|
639
|
+
return Math.floor(unit === "ns" ? n / 1e9 : n / 1000);
|
|
640
|
+
}
|
|
641
|
+
function watchIdle(emit, onError) {
|
|
642
|
+
if (process.platform === "win32") {
|
|
643
|
+
const encoded = Buffer.from(WINDOWS_IDLE, "utf16le").toString("base64");
|
|
644
|
+
const child = spawn2("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded], { cwd: homedir2(), stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
|
|
645
|
+
let buffer = "";
|
|
646
|
+
child.stdout?.setEncoding("utf8");
|
|
647
|
+
child.stdout?.on("data", (chunk) => {
|
|
648
|
+
buffer += chunk;
|
|
649
|
+
const lines = buffer.split(/\r?\n/);
|
|
650
|
+
buffer = lines.pop() ?? "";
|
|
651
|
+
for (const line of lines) {
|
|
652
|
+
const s = idleSeconds(line);
|
|
653
|
+
if (s !== undefined)
|
|
654
|
+
emit(s);
|
|
655
|
+
}
|
|
656
|
+
});
|
|
657
|
+
child.once("error", (error) => onError(error));
|
|
658
|
+
return () => child.kill();
|
|
659
|
+
}
|
|
660
|
+
const [file, args, parse] = process.platform === "darwin" ? [
|
|
661
|
+
"ioreg",
|
|
662
|
+
["-c", "IOHIDSystem", "-d", "4"],
|
|
663
|
+
(out) => idleSeconds(/"HIDIdleTime" = (\d+)/.exec(out)?.[1] ?? "", "ns")
|
|
664
|
+
] : ["xprintidle", [], (out) => idleSeconds(out)];
|
|
665
|
+
let stopped = false;
|
|
666
|
+
let timer;
|
|
667
|
+
const tick = () => {
|
|
668
|
+
const child = spawn2(file, [...args], { stdio: ["ignore", "pipe", "ignore"] });
|
|
669
|
+
let out = "";
|
|
670
|
+
child.stdout?.setEncoding("utf8");
|
|
671
|
+
child.stdout?.on("data", (c) => {
|
|
672
|
+
out += c;
|
|
673
|
+
});
|
|
674
|
+
child.once("error", () => {
|
|
675
|
+
stopped = true;
|
|
676
|
+
onError(new Error(`idle time is unavailable: "${file}" could not run`));
|
|
677
|
+
});
|
|
678
|
+
child.once("close", () => {
|
|
679
|
+
const s = parse(out);
|
|
680
|
+
if (s !== undefined)
|
|
681
|
+
emit(s);
|
|
682
|
+
if (!stopped)
|
|
683
|
+
timer = setTimeout(tick, 2000);
|
|
684
|
+
});
|
|
685
|
+
};
|
|
686
|
+
tick();
|
|
687
|
+
return () => {
|
|
688
|
+
stopped = true;
|
|
689
|
+
clearTimeout(timer);
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
var WINDOWS_FOREGROUND = `
|
|
693
|
+
Add-Type @'
|
|
694
|
+
using System;
|
|
695
|
+
using System.Runtime.InteropServices;
|
|
696
|
+
public static class SdeckFg {
|
|
697
|
+
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
|
698
|
+
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
|
|
699
|
+
public static uint Pid() { uint pid; GetWindowThreadProcessId(GetForegroundWindow(), out pid); return pid; }
|
|
700
|
+
}
|
|
701
|
+
'@
|
|
702
|
+
$last = $null
|
|
703
|
+
while ($true) {
|
|
704
|
+
$name = ""
|
|
705
|
+
$id = [SdeckFg]::Pid()
|
|
706
|
+
if ($id -ne 0) { $p = Get-Process -Id $id -ErrorAction SilentlyContinue; if ($p) { $name = $p.ProcessName + ".exe" } }
|
|
707
|
+
if ($name -ne $last) { [Console]::Out.WriteLine($name); [Console]::Out.Flush(); $last = $name }
|
|
708
|
+
Start-Sleep -Milliseconds 700
|
|
709
|
+
}
|
|
710
|
+
`;
|
|
711
|
+
function foregroundName(line) {
|
|
712
|
+
const trimmed = line.trim();
|
|
713
|
+
return (trimmed.split(/[\\/]/).pop() ?? "").toLowerCase();
|
|
714
|
+
}
|
|
715
|
+
function watchForeground(emit, onError) {
|
|
716
|
+
if (process.platform === "win32") {
|
|
717
|
+
const encoded = Buffer.from(WINDOWS_FOREGROUND, "utf16le").toString("base64");
|
|
718
|
+
const child = spawn2("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded], { cwd: homedir2(), stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
|
|
719
|
+
let buffer = "";
|
|
720
|
+
child.stdout?.setEncoding("utf8");
|
|
721
|
+
child.stdout?.on("data", (chunk) => {
|
|
722
|
+
buffer += chunk;
|
|
723
|
+
const lines = buffer.split(/\r?\n/);
|
|
724
|
+
buffer = lines.pop() ?? "";
|
|
725
|
+
for (const line of lines)
|
|
726
|
+
emit(foregroundName(line));
|
|
727
|
+
});
|
|
728
|
+
child.once("error", (error) => onError(error));
|
|
729
|
+
return () => child.kill();
|
|
730
|
+
}
|
|
731
|
+
const script = process.platform === "darwin" ? `ps -p "$(osascript -e 'tell application "System Events" to get unix id of first application process whose frontmost is true')" -o comm=` : `cat "/proc/$(xdotool getactivewindow getwindowpid)/comm"`;
|
|
732
|
+
const tool = process.platform === "darwin" ? "osascript" : "xdotool";
|
|
733
|
+
let stopped = false;
|
|
734
|
+
let last;
|
|
735
|
+
let failures = 0;
|
|
736
|
+
let timer;
|
|
737
|
+
const tick = () => {
|
|
738
|
+
const child = spawn2("sh", ["-c", script], { stdio: ["ignore", "pipe", "ignore"] });
|
|
739
|
+
let out = "";
|
|
740
|
+
child.stdout?.setEncoding("utf8");
|
|
741
|
+
child.stdout?.on("data", (c) => {
|
|
742
|
+
out += c;
|
|
743
|
+
});
|
|
744
|
+
child.once("error", (error) => {
|
|
745
|
+
stopped = true;
|
|
746
|
+
onError(error);
|
|
747
|
+
});
|
|
748
|
+
child.once("close", (code) => {
|
|
749
|
+
if (stopped)
|
|
750
|
+
return;
|
|
751
|
+
if (code === 0) {
|
|
752
|
+
failures = 0;
|
|
753
|
+
const app = foregroundName(out);
|
|
754
|
+
if (app !== last) {
|
|
755
|
+
last = app;
|
|
756
|
+
emit(app);
|
|
757
|
+
}
|
|
758
|
+
} else if (++failures === 3) {
|
|
759
|
+
onError(new Error(`the foreground app is unavailable: "${tool}" did not answer`));
|
|
760
|
+
}
|
|
761
|
+
timer = setTimeout(tick, 1000);
|
|
762
|
+
});
|
|
763
|
+
};
|
|
764
|
+
tick();
|
|
765
|
+
return () => {
|
|
766
|
+
stopped = true;
|
|
767
|
+
clearTimeout(timer);
|
|
768
|
+
};
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
// src/index.tsx
|
|
772
|
+
function openWithSystem(target) {
|
|
773
|
+
const [command, args] = process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", target]] : process.platform === "darwin" ? ["open", [target]] : ["xdg-open", [target]];
|
|
774
|
+
spawn3(command, args, {
|
|
775
|
+
cwd: homedir3(),
|
|
776
|
+
detached: true,
|
|
777
|
+
stdio: "ignore",
|
|
778
|
+
windowsHide: true
|
|
779
|
+
}).unref();
|
|
780
|
+
}
|
|
781
|
+
var OUTPUT_LIMIT = 64 * 1024;
|
|
782
|
+
function runShell(command, cwd, signal) {
|
|
783
|
+
return new Promise((resolve) => {
|
|
784
|
+
let output = "";
|
|
785
|
+
const child = spawn3(command, {
|
|
786
|
+
shell: true,
|
|
787
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
788
|
+
windowsHide: true,
|
|
789
|
+
...cwd && { cwd },
|
|
790
|
+
...signal && { signal }
|
|
791
|
+
});
|
|
792
|
+
child.stdout?.setEncoding("utf8");
|
|
793
|
+
child.stdout?.on("data", (chunk) => {
|
|
794
|
+
if (output.length < OUTPUT_LIMIT)
|
|
795
|
+
output += chunk;
|
|
796
|
+
});
|
|
797
|
+
const done = (code) => resolve({ code, output: output.slice(0, OUTPUT_LIMIT).trim() });
|
|
798
|
+
child.once("error", () => done(-1));
|
|
799
|
+
child.once("close", (code) => done(code ?? -1));
|
|
800
|
+
});
|
|
801
|
+
}
|
|
802
|
+
var buttonLook = (icon, caption, image, background) => iconLook({ icon: image || icon, caption, background });
|
|
803
|
+
var open = defineAction({
|
|
804
|
+
id: "open",
|
|
805
|
+
permissions: ["process"],
|
|
806
|
+
name: "Open",
|
|
807
|
+
description: "Opens a website, file, folder or app.",
|
|
808
|
+
category: "System",
|
|
809
|
+
icon: "external-link",
|
|
810
|
+
settings: {
|
|
811
|
+
target: {
|
|
812
|
+
type: "text",
|
|
813
|
+
label: "URL or path",
|
|
814
|
+
placeholder: "https://example.com or C:\\Tools\\app.exe"
|
|
815
|
+
},
|
|
816
|
+
text: {
|
|
817
|
+
type: "text",
|
|
818
|
+
label: "Text",
|
|
819
|
+
placeholder: "Optional, under the icon",
|
|
820
|
+
appearance: true
|
|
821
|
+
},
|
|
822
|
+
image: { type: "image", label: "Image", appearance: true },
|
|
823
|
+
background: { type: "color", label: "Background", default: "#0969da", appearance: true }
|
|
824
|
+
},
|
|
825
|
+
run: ({ settings, plugin }) => {
|
|
826
|
+
if (!settings.target)
|
|
827
|
+
throw new Error("nothing to open");
|
|
828
|
+
plugin.log("open", settings.target);
|
|
829
|
+
openWithSystem(settings.target);
|
|
830
|
+
return { label: `Open ${settings.target}` };
|
|
831
|
+
},
|
|
832
|
+
look: (s) => buttonLook("lucide/external-link", s.text, s.image, s.background)
|
|
833
|
+
});
|
|
834
|
+
var command = defineAction({
|
|
835
|
+
id: "command",
|
|
836
|
+
permissions: ["shell"],
|
|
837
|
+
name: "Run command",
|
|
838
|
+
description: "Runs a shell command. Fails when it exits with an error; its output is the result.",
|
|
839
|
+
category: "System",
|
|
840
|
+
icon: "terminal",
|
|
841
|
+
settings: {
|
|
842
|
+
command: { type: "text", label: "Command", placeholder: "echo hello", multiline: true },
|
|
843
|
+
cwd: { type: "text", label: "Working directory", placeholder: "Defaults to your home folder" },
|
|
844
|
+
undo: {
|
|
845
|
+
type: "text",
|
|
846
|
+
label: "Undo command",
|
|
847
|
+
description: "Run to revert it (from the history, or a toggle's second press).",
|
|
848
|
+
multiline: true
|
|
849
|
+
},
|
|
850
|
+
text: {
|
|
851
|
+
type: "text",
|
|
852
|
+
label: "Text",
|
|
853
|
+
placeholder: "Optional, under the icon",
|
|
854
|
+
appearance: true
|
|
855
|
+
},
|
|
856
|
+
image: { type: "image", label: "Image", appearance: true },
|
|
857
|
+
background: { type: "color", label: "Background", default: "#24292f", appearance: true }
|
|
858
|
+
},
|
|
859
|
+
run: async ({ settings, plugin, signal }) => {
|
|
860
|
+
if (!settings.command)
|
|
861
|
+
throw new Error("no command");
|
|
862
|
+
const cwd = settings.cwd || homedir3();
|
|
863
|
+
plugin.log("run", settings.command);
|
|
864
|
+
const { code, output } = await runShell(settings.command, cwd, signal);
|
|
865
|
+
if (code !== 0)
|
|
866
|
+
throw new Error(`"${settings.command}" exited with ${code}`);
|
|
867
|
+
const undo = settings.undo;
|
|
868
|
+
return {
|
|
869
|
+
result: output,
|
|
870
|
+
label: settings.command,
|
|
871
|
+
...undo && {
|
|
872
|
+
undo: async () => {
|
|
873
|
+
const r = await runShell(undo, cwd);
|
|
874
|
+
if (r.code !== 0)
|
|
875
|
+
throw new Error(`"${undo}" exited with ${r.code}`);
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
};
|
|
879
|
+
},
|
|
880
|
+
look: (s) => buttonLook("lucide/terminal", s.text, s.image, s.background)
|
|
881
|
+
});
|
|
882
|
+
function cpuSampler() {
|
|
883
|
+
const read = () => cpus2().reduce((acc, cpu) => {
|
|
884
|
+
const t = cpu.times;
|
|
885
|
+
acc.idle += t.idle;
|
|
886
|
+
acc.total += t.user + t.nice + t.sys + t.irq + t.idle;
|
|
887
|
+
return acc;
|
|
888
|
+
}, { idle: 0, total: 0 });
|
|
889
|
+
let last = read();
|
|
890
|
+
return () => {
|
|
891
|
+
const now = read();
|
|
892
|
+
const total = now.total - last.total;
|
|
893
|
+
const idle = now.idle - last.idle;
|
|
894
|
+
last = now;
|
|
895
|
+
return total > 0 ? Math.round(100 * (1 - idle / total)) : 0;
|
|
896
|
+
};
|
|
897
|
+
}
|
|
898
|
+
function listProcesses() {
|
|
899
|
+
const [file, args] = process.platform === "win32" ? ["tasklist", ["/fo", "csv", "/nh"]] : ["ps", ["-A", "-o", "comm="]];
|
|
900
|
+
return new Promise((resolve, reject) => {
|
|
901
|
+
execFile3(file, args, { windowsHide: true, maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => {
|
|
902
|
+
if (error)
|
|
903
|
+
return reject(error);
|
|
904
|
+
const names = new Set;
|
|
905
|
+
for (const line of stdout.split(/\r?\n/)) {
|
|
906
|
+
const name = process.platform === "win32" ? /^"([^"]+)"/.exec(line)?.[1] : basename(line.trim());
|
|
907
|
+
if (name)
|
|
908
|
+
names.add(name.toLowerCase());
|
|
909
|
+
}
|
|
910
|
+
resolve([...names].sort());
|
|
911
|
+
});
|
|
912
|
+
});
|
|
913
|
+
}
|
|
914
|
+
var reading = (key, unit) => `{{system.${key} == null ? "N/A" : round(system.${key}) + "${unit}"}}`;
|
|
915
|
+
var METRICS = {
|
|
916
|
+
cpu: { icon: "lucide/cpu", text: reading("cpu", "%"), bar: "system.cpu" },
|
|
917
|
+
memory: { icon: "lucide/memory-stick", text: reading("memory", "%"), bar: "system.memory" },
|
|
918
|
+
disk: { icon: "lucide/hard-drive", text: reading("disk", "%"), bar: "system.disk" },
|
|
919
|
+
gpu: { icon: "lucide/gpu", text: reading("gpu", "%"), bar: "system.gpu" },
|
|
920
|
+
"gpu-temp": { icon: "lucide/thermometer", text: reading("gpuTemp", "\xB0C"), bar: "system.gpuTemp" },
|
|
921
|
+
"cpu-temp": { icon: "lucide/thermometer", text: reading("cpuTemp", "\xB0C"), bar: "system.cpuTemp" },
|
|
922
|
+
core: {
|
|
923
|
+
icon: "lucide/zap",
|
|
924
|
+
text: "{{max(system.cpuCores ?? 0)}}%",
|
|
925
|
+
bar: "max(system.cpuCores ?? 0)"
|
|
926
|
+
},
|
|
927
|
+
ping: { icon: "lucide/activity", text: reading("ping", " ms"), bar: undefined },
|
|
928
|
+
fps: { icon: "lucide/gauge", text: reading("fps", ""), bar: undefined }
|
|
929
|
+
};
|
|
930
|
+
var stats = defineAction({
|
|
931
|
+
id: "stats",
|
|
932
|
+
permissions: [],
|
|
933
|
+
name: "System stats",
|
|
934
|
+
description: "Live CPU, memory, disk, network, GPU, ping and FPS (also usable anywhere as {{system.cpu}}).",
|
|
935
|
+
category: "Monitoring",
|
|
936
|
+
icon: "activity",
|
|
937
|
+
slots: ["key", "sensor", "window"],
|
|
938
|
+
settings: {
|
|
939
|
+
show: {
|
|
940
|
+
type: "select",
|
|
941
|
+
label: "Show",
|
|
942
|
+
default: "both",
|
|
943
|
+
options: [
|
|
944
|
+
{ value: "both", label: "CPU and memory" },
|
|
945
|
+
{ value: "cpu", label: "CPU" },
|
|
946
|
+
{ value: "core", label: "Busiest CPU core" },
|
|
947
|
+
{ value: "memory", label: "Memory" },
|
|
948
|
+
{ value: "disk", label: "Disk space used" },
|
|
949
|
+
{ value: "network", label: "Network speed" },
|
|
950
|
+
{ value: "ping", label: "Ping" },
|
|
951
|
+
{ value: "gpu", label: "GPU load (NVIDIA)" },
|
|
952
|
+
{ value: "gpu-temp", label: "GPU temperature (NVIDIA)" },
|
|
953
|
+
{ value: "cpu-temp", label: "CPU temperature" },
|
|
954
|
+
{ value: "fps", label: "Frame rate (PresentMon)" }
|
|
955
|
+
]
|
|
956
|
+
},
|
|
957
|
+
color: { type: "color", label: "Colour", default: "#58a6ff" },
|
|
958
|
+
background: { type: "color", label: "Background", default: "#0d1117" }
|
|
959
|
+
},
|
|
960
|
+
display: true,
|
|
961
|
+
look: (s) => {
|
|
962
|
+
const bar = (id, value) => ({
|
|
963
|
+
id,
|
|
964
|
+
type: "bar",
|
|
965
|
+
value,
|
|
966
|
+
color: s.color,
|
|
967
|
+
track: "#30363d",
|
|
968
|
+
position: "bottom",
|
|
969
|
+
thickness: 6
|
|
970
|
+
});
|
|
971
|
+
const row = (id, icon, value, size) => [
|
|
972
|
+
iconLayer(`${id}-icon`, icon, { color: s.color, size: 22, row: id }),
|
|
973
|
+
textLayer(id, value, { color: s.color, size, row: id })
|
|
974
|
+
];
|
|
975
|
+
if (s.show === "both") {
|
|
976
|
+
return {
|
|
977
|
+
background: s.background,
|
|
978
|
+
layers: [
|
|
979
|
+
...row("cpu", "lucide/cpu", "{{system.cpu}}%", 18),
|
|
980
|
+
...row("memory", "lucide/memory-stick", "{{system.memory}}%", 18)
|
|
981
|
+
]
|
|
982
|
+
};
|
|
983
|
+
}
|
|
984
|
+
if (s.show === "network") {
|
|
985
|
+
return {
|
|
986
|
+
background: s.background,
|
|
987
|
+
layers: [
|
|
988
|
+
...row("down", "lucide/arrow-down", "{{bytes(system.netDown ?? 0)}}", 13),
|
|
989
|
+
...row("up", "lucide/arrow-up", "{{bytes(system.netUp ?? 0)}}", 13)
|
|
990
|
+
]
|
|
991
|
+
};
|
|
992
|
+
}
|
|
993
|
+
const metric = METRICS[s.show];
|
|
994
|
+
const id = s.show;
|
|
995
|
+
return {
|
|
996
|
+
background: s.background,
|
|
997
|
+
layers: [
|
|
998
|
+
iconLayer(`${id}-icon`, metric.icon, { color: s.color, size: 40, position: "top" }),
|
|
999
|
+
textLayer(id, metric.text, { color: s.color, size: 20, position: "bottom" }),
|
|
1000
|
+
...metric.bar ? [bar(`${id}-bar`, metric.bar)] : []
|
|
1001
|
+
]
|
|
1002
|
+
};
|
|
1003
|
+
}
|
|
1004
|
+
});
|
|
1005
|
+
var MEDIA = {
|
|
1006
|
+
"play-pause": { label: "Play / Pause", icons: ["play", "pause"], undo: "play-pause" },
|
|
1007
|
+
next: { label: "Next track", icons: ["skip-forward"], undo: "previous" },
|
|
1008
|
+
previous: { label: "Previous track", icons: ["skip-back"], undo: "next" },
|
|
1009
|
+
stop: { label: "Stop playback", icons: ["square"], undo: undefined },
|
|
1010
|
+
"volume-up": { label: "Volume up", icons: ["volume-2", "plus"], undo: "volume-down" },
|
|
1011
|
+
"volume-down": { label: "Volume down", icons: ["volume-1", "minus"], undo: "volume-up" },
|
|
1012
|
+
mute: { label: "Mute", icons: ["volume-x"], undo: "mute" }
|
|
1013
|
+
};
|
|
1014
|
+
var media = defineAction({
|
|
1015
|
+
id: "media",
|
|
1016
|
+
permissions: ["input"],
|
|
1017
|
+
name: "Media and volume",
|
|
1018
|
+
description: "Presses a media or volume key, as a keyboard would.",
|
|
1019
|
+
category: "Controls",
|
|
1020
|
+
icon: "play",
|
|
1021
|
+
slots: ["key", "sensor"],
|
|
1022
|
+
settings: {
|
|
1023
|
+
key: {
|
|
1024
|
+
type: "select",
|
|
1025
|
+
label: "Key",
|
|
1026
|
+
default: "play-pause",
|
|
1027
|
+
options: Object.entries(MEDIA).map(([value, m]) => ({ value, label: m.label }))
|
|
1028
|
+
},
|
|
1029
|
+
steps: {
|
|
1030
|
+
type: "number",
|
|
1031
|
+
label: "Presses",
|
|
1032
|
+
description: "Each volume press is about 2%.",
|
|
1033
|
+
default: 1,
|
|
1034
|
+
min: 1,
|
|
1035
|
+
max: 50,
|
|
1036
|
+
visibleIf: { key: ["volume-up", "volume-down"] }
|
|
1037
|
+
},
|
|
1038
|
+
background: { type: "color", label: "Background", default: "#1f2937", appearance: true }
|
|
1039
|
+
},
|
|
1040
|
+
run: async ({ settings }) => {
|
|
1041
|
+
const controls = await systemControls();
|
|
1042
|
+
const { key } = settings;
|
|
1043
|
+
const times = key === "volume-up" || key === "volume-down" ? settings.steps : 1;
|
|
1044
|
+
const press = async (which) => {
|
|
1045
|
+
for (let i = 0;i < times; i++)
|
|
1046
|
+
await controls.media(which);
|
|
1047
|
+
};
|
|
1048
|
+
await press(key);
|
|
1049
|
+
const undo = MEDIA[key].undo;
|
|
1050
|
+
return { label: MEDIA[key].label, ...undo && { undo: () => press(undo) } };
|
|
1051
|
+
},
|
|
1052
|
+
look: (s) => {
|
|
1053
|
+
const { icons } = MEDIA[s.key];
|
|
1054
|
+
return {
|
|
1055
|
+
background: s.background,
|
|
1056
|
+
layers: icons.map((name, i) => iconLayer(i === 0 ? "icon" : `icon-${i + 1}`, `lucide/${name}`, {
|
|
1057
|
+
size: icons.length === 1 ? 58 : s.key === "play-pause" ? 36 : i === 0 ? 46 : 26,
|
|
1058
|
+
row: "icons"
|
|
1059
|
+
}))
|
|
1060
|
+
};
|
|
1061
|
+
}
|
|
1062
|
+
});
|
|
1063
|
+
var hotkey = defineAction({
|
|
1064
|
+
id: "hotkey",
|
|
1065
|
+
permissions: ["input"],
|
|
1066
|
+
name: "Press a shortcut",
|
|
1067
|
+
description: "Sends a keyboard shortcut to the focused app.",
|
|
1068
|
+
category: "Controls",
|
|
1069
|
+
icon: "keyboard",
|
|
1070
|
+
slots: ["key", "sensor"],
|
|
1071
|
+
settings: {
|
|
1072
|
+
keys: { type: "text", label: "Shortcut", placeholder: "ctrl+shift+m" },
|
|
1073
|
+
text: {
|
|
1074
|
+
type: "text",
|
|
1075
|
+
label: "Text",
|
|
1076
|
+
placeholder: "Defaults to the shortcut",
|
|
1077
|
+
appearance: true
|
|
1078
|
+
},
|
|
1079
|
+
background: { type: "color", label: "Background", default: "#374151", appearance: true }
|
|
1080
|
+
},
|
|
1081
|
+
run: async ({ settings }) => {
|
|
1082
|
+
const accelerator = parseAccelerator2(settings.keys);
|
|
1083
|
+
await (await systemControls()).hotkey(accelerator);
|
|
1084
|
+
return { label: `Press ${formatAccelerator(accelerator)}` };
|
|
1085
|
+
},
|
|
1086
|
+
look: (s) => iconLook({ icon: "lucide/keyboard", caption: s.text || s.keys, background: s.background })
|
|
1087
|
+
});
|
|
1088
|
+
var type = defineAction({
|
|
1089
|
+
id: "type",
|
|
1090
|
+
permissions: ["input"],
|
|
1091
|
+
name: "Type text",
|
|
1092
|
+
description: "Types text into the focused app. The text can use {{templates}}.",
|
|
1093
|
+
category: "Controls",
|
|
1094
|
+
icon: "text-cursor-input",
|
|
1095
|
+
slots: ["key", "sensor"],
|
|
1096
|
+
settings: {
|
|
1097
|
+
content: { type: "text", label: "Text to type", multiline: true },
|
|
1098
|
+
text: {
|
|
1099
|
+
type: "text",
|
|
1100
|
+
label: "Key text",
|
|
1101
|
+
placeholder: "Optional, under the icon",
|
|
1102
|
+
appearance: true
|
|
1103
|
+
},
|
|
1104
|
+
background: { type: "color", label: "Background", default: "#374151", appearance: true }
|
|
1105
|
+
},
|
|
1106
|
+
run: async ({ settings }) => {
|
|
1107
|
+
if (!settings.content)
|
|
1108
|
+
throw new Error("nothing to type");
|
|
1109
|
+
await (await systemControls()).type(settings.content);
|
|
1110
|
+
return { label: `Type ${settings.content.length} character(s)` };
|
|
1111
|
+
},
|
|
1112
|
+
look: (s) => iconLook({ icon: "lucide/text-cursor-input", caption: s.text, background: s.background })
|
|
1113
|
+
});
|
|
1114
|
+
var lock = defineAction({
|
|
1115
|
+
id: "lock",
|
|
1116
|
+
permissions: ["process"],
|
|
1117
|
+
name: "Lock the screen",
|
|
1118
|
+
category: "Controls",
|
|
1119
|
+
icon: "lock",
|
|
1120
|
+
slots: ["key", "sensor"],
|
|
1121
|
+
settings: {
|
|
1122
|
+
text: {
|
|
1123
|
+
type: "text",
|
|
1124
|
+
label: "Text",
|
|
1125
|
+
placeholder: "Optional, under the icon",
|
|
1126
|
+
appearance: true
|
|
1127
|
+
},
|
|
1128
|
+
background: { type: "color", label: "Background", default: "#7c2d12", appearance: true }
|
|
1129
|
+
},
|
|
1130
|
+
run: async () => {
|
|
1131
|
+
await (await systemControls()).lock();
|
|
1132
|
+
return { label: "Lock the screen" };
|
|
1133
|
+
},
|
|
1134
|
+
look: (s) => iconLook({ icon: "lucide/lock", caption: s.text, background: s.background })
|
|
1135
|
+
});
|
|
1136
|
+
var sleep = defineAction({
|
|
1137
|
+
id: "sleep",
|
|
1138
|
+
permissions: ["process"],
|
|
1139
|
+
name: "Sleep",
|
|
1140
|
+
description: "Puts the computer to sleep.",
|
|
1141
|
+
category: "Controls",
|
|
1142
|
+
icon: "moon",
|
|
1143
|
+
slots: ["key", "sensor"],
|
|
1144
|
+
settings: {
|
|
1145
|
+
text: {
|
|
1146
|
+
type: "text",
|
|
1147
|
+
label: "Text",
|
|
1148
|
+
placeholder: "Optional, under the icon",
|
|
1149
|
+
appearance: true
|
|
1150
|
+
},
|
|
1151
|
+
background: { type: "color", label: "Background", default: "#1e1b4b", appearance: true }
|
|
1152
|
+
},
|
|
1153
|
+
run: async () => {
|
|
1154
|
+
await (await systemControls()).sleep();
|
|
1155
|
+
return { label: "Sleep" };
|
|
1156
|
+
},
|
|
1157
|
+
look: (s) => iconLook({ icon: "lucide/moon", caption: s.text, background: s.background })
|
|
1158
|
+
});
|
|
1159
|
+
function screenshotName(at) {
|
|
1160
|
+
const two = (n) => String(n).padStart(2, "0");
|
|
1161
|
+
const day = `${at.getFullYear()}${two(at.getMonth() + 1)}${two(at.getDate())}`;
|
|
1162
|
+
const time = `${two(at.getHours())}${two(at.getMinutes())}${two(at.getSeconds())}`;
|
|
1163
|
+
return `screenshot-${day}-${time}.png`;
|
|
1164
|
+
}
|
|
1165
|
+
var screenshot = defineAction({
|
|
1166
|
+
id: "screenshot",
|
|
1167
|
+
permissions: ["process", "filesystem"],
|
|
1168
|
+
name: "Screenshot",
|
|
1169
|
+
description: "Saves the screen to a file (the result), or opens the region picker.",
|
|
1170
|
+
category: "Controls",
|
|
1171
|
+
icon: "camera",
|
|
1172
|
+
slots: ["key", "sensor"],
|
|
1173
|
+
settings: {
|
|
1174
|
+
mode: {
|
|
1175
|
+
type: "select",
|
|
1176
|
+
label: "Capture",
|
|
1177
|
+
default: "file",
|
|
1178
|
+
options: [
|
|
1179
|
+
{ value: "file", label: "Whole screen, to a file" },
|
|
1180
|
+
{ value: "snip", label: "A region I choose" }
|
|
1181
|
+
]
|
|
1182
|
+
},
|
|
1183
|
+
folder: {
|
|
1184
|
+
type: "text",
|
|
1185
|
+
label: "Folder",
|
|
1186
|
+
placeholder: "Pictures/sdeck",
|
|
1187
|
+
visibleIf: { mode: "file" }
|
|
1188
|
+
},
|
|
1189
|
+
text: {
|
|
1190
|
+
type: "text",
|
|
1191
|
+
label: "Text",
|
|
1192
|
+
placeholder: "Optional, under the icon",
|
|
1193
|
+
appearance: true
|
|
1194
|
+
},
|
|
1195
|
+
background: { type: "color", label: "Background", default: "#065f46", appearance: true }
|
|
1196
|
+
},
|
|
1197
|
+
run: async ({ settings }) => {
|
|
1198
|
+
const controls = await systemControls();
|
|
1199
|
+
if (settings.mode === "snip") {
|
|
1200
|
+
await controls.snip();
|
|
1201
|
+
return { label: "Screenshot a region" };
|
|
1202
|
+
}
|
|
1203
|
+
const folder = settings.folder || join3(homedir3(), "Pictures", "sdeck");
|
|
1204
|
+
const file = join3(folder, screenshotName(new Date));
|
|
1205
|
+
await controls.screenshot(file);
|
|
1206
|
+
return { result: file, label: `Screenshot ${file}` };
|
|
1207
|
+
},
|
|
1208
|
+
look: (s) => iconLook({
|
|
1209
|
+
icon: s.mode === "snip" ? "lucide/scissors" : "lucide/camera",
|
|
1210
|
+
caption: s.text,
|
|
1211
|
+
background: s.background
|
|
1212
|
+
})
|
|
1213
|
+
});
|
|
1214
|
+
var pingAction = defineAction({
|
|
1215
|
+
id: "ping",
|
|
1216
|
+
permissions: ["network"],
|
|
1217
|
+
name: "Ping",
|
|
1218
|
+
description: "Pings a host; the result is the round trip in ms. Fails when it does not answer.",
|
|
1219
|
+
category: "Monitoring",
|
|
1220
|
+
icon: "radio",
|
|
1221
|
+
settings: {
|
|
1222
|
+
host: { type: "text", label: "Host", default: "1.1.1.1" },
|
|
1223
|
+
background: { type: "color", label: "Background", default: "#0d1117", appearance: true }
|
|
1224
|
+
},
|
|
1225
|
+
run: async ({ settings, signal }) => {
|
|
1226
|
+
const ms = await ping(settings.host, signal);
|
|
1227
|
+
return { result: ms, label: `Ping ${settings.host}: ${ms} ms` };
|
|
1228
|
+
},
|
|
1229
|
+
look: (s) => iconLook({ icon: "lucide/activity", caption: s.host, background: s.background })
|
|
1230
|
+
});
|
|
1231
|
+
var processes = new Shared2((emit) => {
|
|
1232
|
+
let stopped = false;
|
|
1233
|
+
let timer;
|
|
1234
|
+
const tick = async () => {
|
|
1235
|
+
try {
|
|
1236
|
+
emit(new Set(await listProcesses()));
|
|
1237
|
+
} catch {}
|
|
1238
|
+
if (!stopped)
|
|
1239
|
+
timer = setTimeout(tick, 3000);
|
|
1240
|
+
};
|
|
1241
|
+
tick();
|
|
1242
|
+
return () => {
|
|
1243
|
+
stopped = true;
|
|
1244
|
+
clearTimeout(timer);
|
|
1245
|
+
};
|
|
1246
|
+
});
|
|
1247
|
+
var network = new Shared2((emit) => {
|
|
1248
|
+
emit(networkAddresses());
|
|
1249
|
+
const timer = setInterval(() => emit(networkAddresses()), 5000);
|
|
1250
|
+
return () => clearInterval(timer);
|
|
1251
|
+
});
|
|
1252
|
+
var idleError;
|
|
1253
|
+
var idle = new Shared2((emit) => {
|
|
1254
|
+
idleError = undefined;
|
|
1255
|
+
return watchIdle(emit, (error) => {
|
|
1256
|
+
idleError = error;
|
|
1257
|
+
});
|
|
1258
|
+
});
|
|
1259
|
+
var foregroundError;
|
|
1260
|
+
var foreground = new Shared2((emit) => {
|
|
1261
|
+
foregroundError = undefined;
|
|
1262
|
+
return watchForeground(emit, (error) => {
|
|
1263
|
+
foregroundError = error;
|
|
1264
|
+
});
|
|
1265
|
+
});
|
|
1266
|
+
var RETRY_MS = 60000;
|
|
1267
|
+
var unavailable = new Map;
|
|
1268
|
+
function report(context) {
|
|
1269
|
+
const reasons = [...unavailable].map(([what, u]) => `${what}: ${u.reason}`);
|
|
1270
|
+
context.status(reasons.length > 0 ? `Unavailable here. ${reasons.join(". ")}` : undefined, "info");
|
|
1271
|
+
}
|
|
1272
|
+
function markUnavailable(context, what, error) {
|
|
1273
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
1274
|
+
if (unavailable.get(what)?.reason !== reason)
|
|
1275
|
+
context.log(`${what} is unavailable:`, reason);
|
|
1276
|
+
unavailable.set(what, { reason, retryAt: Date.now() + RETRY_MS });
|
|
1277
|
+
report(context);
|
|
1278
|
+
}
|
|
1279
|
+
async function measured(context, what, read) {
|
|
1280
|
+
const failed = unavailable.get(what);
|
|
1281
|
+
if (failed && Date.now() < failed.retryAt)
|
|
1282
|
+
return;
|
|
1283
|
+
try {
|
|
1284
|
+
const value = await read();
|
|
1285
|
+
if (unavailable.delete(what))
|
|
1286
|
+
report(context);
|
|
1287
|
+
return value;
|
|
1288
|
+
} catch (error) {
|
|
1289
|
+
markUnavailable(context, what, error);
|
|
1290
|
+
return;
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
var gpuReading;
|
|
1294
|
+
function gpu(context) {
|
|
1295
|
+
if (!gpuReading || Date.now() - gpuReading.at > 1500) {
|
|
1296
|
+
gpuReading = { at: Date.now(), value: measured(context, "GPU", readGpu) };
|
|
1297
|
+
}
|
|
1298
|
+
return gpuReading.value;
|
|
1299
|
+
}
|
|
1300
|
+
var defaultDisk = () => process.platform === "win32" ? `${process.env.SystemDrive ?? "C:"}\\` : "/";
|
|
1301
|
+
async function disks(context) {
|
|
1302
|
+
const list = String(context.settings().disks || defaultDisk()).split(",").map((d) => d.trim()).filter(Boolean);
|
|
1303
|
+
const out = {};
|
|
1304
|
+
for (const path of list) {
|
|
1305
|
+
const name = /^[a-z]:/i.test(path) ? path[0].toLowerCase() : path;
|
|
1306
|
+
const full = /^[a-z]:$/i.test(path) ? `${path}\\` : path;
|
|
1307
|
+
const usage = await measured(context, `disk ${path}`, () => diskUsage(full));
|
|
1308
|
+
if (usage)
|
|
1309
|
+
out[name] = usage;
|
|
1310
|
+
}
|
|
1311
|
+
return out;
|
|
1312
|
+
}
|
|
1313
|
+
var throughputSource = new Shared2((emit) => watchNetwork(emit, (error) => networkError?.(error)));
|
|
1314
|
+
var networkError;
|
|
1315
|
+
var netState = (id, name, pick) => ({
|
|
1316
|
+
id,
|
|
1317
|
+
name,
|
|
1318
|
+
type: "number",
|
|
1319
|
+
unit: "B/s",
|
|
1320
|
+
permissions: ["process"],
|
|
1321
|
+
start: (set, context) => {
|
|
1322
|
+
networkError = (error) => markUnavailable(context, "network speed", error);
|
|
1323
|
+
return throughputSource.listen((rate) => set(pick(rate)));
|
|
1324
|
+
}
|
|
1325
|
+
});
|
|
1326
|
+
var gpuState = (id, name, type, pick, unit) => ({
|
|
1327
|
+
id,
|
|
1328
|
+
name,
|
|
1329
|
+
type,
|
|
1330
|
+
...unit && { unit },
|
|
1331
|
+
permissions: ["process"],
|
|
1332
|
+
poll: {
|
|
1333
|
+
everyMs: 2000,
|
|
1334
|
+
read: async (context) => {
|
|
1335
|
+
const g = await gpu(context);
|
|
1336
|
+
return g && pick(g);
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
});
|
|
1340
|
+
var monitoring = [
|
|
1341
|
+
(() => {
|
|
1342
|
+
let sample;
|
|
1343
|
+
return {
|
|
1344
|
+
id: "cpuCores",
|
|
1345
|
+
permissions: [],
|
|
1346
|
+
name: "CPU use per core",
|
|
1347
|
+
type: "json",
|
|
1348
|
+
description: "system.cpuCores[0] is the first core.",
|
|
1349
|
+
poll: {
|
|
1350
|
+
everyMs: 2000,
|
|
1351
|
+
read: () => {
|
|
1352
|
+
sample ??= coreSampler();
|
|
1353
|
+
return sample();
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
};
|
|
1357
|
+
})(),
|
|
1358
|
+
{
|
|
1359
|
+
id: "disks",
|
|
1360
|
+
permissions: ["filesystem"],
|
|
1361
|
+
name: "Disks",
|
|
1362
|
+
type: "json",
|
|
1363
|
+
description: "system.disks.c.percent, .free, .total (choose them in the plugin's settings).",
|
|
1364
|
+
poll: { everyMs: 15000, read: disks }
|
|
1365
|
+
},
|
|
1366
|
+
{
|
|
1367
|
+
id: "disk",
|
|
1368
|
+
permissions: ["filesystem"],
|
|
1369
|
+
name: "Disk space used",
|
|
1370
|
+
type: "number",
|
|
1371
|
+
unit: "%",
|
|
1372
|
+
description: "The first disk in the plugin's settings.",
|
|
1373
|
+
poll: {
|
|
1374
|
+
everyMs: 15000,
|
|
1375
|
+
read: async (context) => Object.values(await disks(context))[0]?.percent
|
|
1376
|
+
}
|
|
1377
|
+
},
|
|
1378
|
+
netState("netDown", "Download speed", (c) => c.received),
|
|
1379
|
+
netState("netUp", "Upload speed", (c) => c.sent),
|
|
1380
|
+
{
|
|
1381
|
+
id: "ping",
|
|
1382
|
+
permissions: ["network"],
|
|
1383
|
+
name: "Ping",
|
|
1384
|
+
type: "number",
|
|
1385
|
+
unit: "ms",
|
|
1386
|
+
description: "To the host in the plugin's settings.",
|
|
1387
|
+
poll: {
|
|
1388
|
+
everyMs: 5000,
|
|
1389
|
+
read: (context) => measured(context, "ping", () => ping(String(context.settings().pingHost)))
|
|
1390
|
+
}
|
|
1391
|
+
},
|
|
1392
|
+
gpuState("gpu", "GPU load", "number", (g) => g.load, "%"),
|
|
1393
|
+
gpuState("gpuTemp", "GPU temperature", "number", (g) => g.temperature, "\xB0C"),
|
|
1394
|
+
gpuState("gpuMemory", "GPU memory used", "number", (g) => g.memory, "%"),
|
|
1395
|
+
gpuState("gpuName", "GPU name", "string", (g) => g.name),
|
|
1396
|
+
{
|
|
1397
|
+
id: "cpuTemp",
|
|
1398
|
+
permissions: ["process"],
|
|
1399
|
+
name: "CPU temperature",
|
|
1400
|
+
type: "number",
|
|
1401
|
+
unit: "\xB0C",
|
|
1402
|
+
poll: {
|
|
1403
|
+
everyMs: 5000,
|
|
1404
|
+
read: (context) => measured(context, "CPU temperature", () => cpuTemperature())
|
|
1405
|
+
}
|
|
1406
|
+
},
|
|
1407
|
+
{
|
|
1408
|
+
id: "fps",
|
|
1409
|
+
permissions: ["process"],
|
|
1410
|
+
name: "Frame rate",
|
|
1411
|
+
type: "number",
|
|
1412
|
+
description: "Of the app in front, measured by PresentMon.",
|
|
1413
|
+
start: (set, context) => {
|
|
1414
|
+
let front;
|
|
1415
|
+
const stopFront = foreground.listen((app) => {
|
|
1416
|
+
front = app;
|
|
1417
|
+
});
|
|
1418
|
+
let stop = () => {};
|
|
1419
|
+
const begin = () => {
|
|
1420
|
+
stop();
|
|
1421
|
+
stop = watchFrameRate(String(context.settings().presentMon), () => front, set, (error) => markUnavailable(context, "frame rate", error));
|
|
1422
|
+
};
|
|
1423
|
+
begin();
|
|
1424
|
+
let command = context.settings().presentMon;
|
|
1425
|
+
const off = context.onSettings(() => {
|
|
1426
|
+
if (context.settings().presentMon === command)
|
|
1427
|
+
return;
|
|
1428
|
+
command = context.settings().presentMon;
|
|
1429
|
+
unavailable.delete("frame rate");
|
|
1430
|
+
begin();
|
|
1431
|
+
});
|
|
1432
|
+
return () => {
|
|
1433
|
+
off();
|
|
1434
|
+
stop();
|
|
1435
|
+
stopFront();
|
|
1436
|
+
};
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
];
|
|
1440
|
+
var processSetting = {
|
|
1441
|
+
process: {
|
|
1442
|
+
type: "text",
|
|
1443
|
+
label: "Process",
|
|
1444
|
+
placeholder: "javaw.exe",
|
|
1445
|
+
description: "The executable name, as in the task manager (case does not matter)."
|
|
1446
|
+
}
|
|
1447
|
+
};
|
|
1448
|
+
function onProcess(name, want, fire) {
|
|
1449
|
+
const target = name.trim().toLowerCase();
|
|
1450
|
+
if (!target)
|
|
1451
|
+
throw new Error("no process name");
|
|
1452
|
+
let before;
|
|
1453
|
+
return processes.listen((now) => {
|
|
1454
|
+
if (before) {
|
|
1455
|
+
const changes = processChanges(before, now);
|
|
1456
|
+
if (changes[want].includes(target))
|
|
1457
|
+
fire({ process: target });
|
|
1458
|
+
}
|
|
1459
|
+
before = now;
|
|
1460
|
+
});
|
|
1461
|
+
}
|
|
1462
|
+
var appOpen = defineTrigger({
|
|
1463
|
+
id: "app-open",
|
|
1464
|
+
permissions: ["process"],
|
|
1465
|
+
name: "When an app opens",
|
|
1466
|
+
description: "Runs when a process starts (checked every 3 s).",
|
|
1467
|
+
settings: processSetting,
|
|
1468
|
+
subscribe: ({ settings, fire }) => onProcess(settings.process, "started", fire)
|
|
1469
|
+
});
|
|
1470
|
+
var appClose = defineTrigger({
|
|
1471
|
+
id: "app-close",
|
|
1472
|
+
permissions: ["process"],
|
|
1473
|
+
name: "When an app closes",
|
|
1474
|
+
description: "Runs when a process exits (checked every 3 s).",
|
|
1475
|
+
settings: processSetting,
|
|
1476
|
+
subscribe: ({ settings, fire }) => onProcess(settings.process, "stopped", fire)
|
|
1477
|
+
});
|
|
1478
|
+
var fileCreated = defineTrigger({
|
|
1479
|
+
id: "file-created",
|
|
1480
|
+
permissions: ["filesystem"],
|
|
1481
|
+
name: "When a file appears",
|
|
1482
|
+
description: "Runs when a new file shows up in a folder (event.name, event.path).",
|
|
1483
|
+
settings: {
|
|
1484
|
+
folder: { type: "text", label: "Folder", placeholder: "C:\\Users\\me\\Downloads" },
|
|
1485
|
+
pattern: {
|
|
1486
|
+
type: "text",
|
|
1487
|
+
label: "Name pattern",
|
|
1488
|
+
placeholder: "*.png",
|
|
1489
|
+
description: "Empty means any file."
|
|
1490
|
+
}
|
|
1491
|
+
},
|
|
1492
|
+
subscribe: ({ settings, fire }) => {
|
|
1493
|
+
if (!settings.folder)
|
|
1494
|
+
throw new Error("no folder");
|
|
1495
|
+
const pattern = namePattern(settings.pattern);
|
|
1496
|
+
return watchFolder(settings.folder, (name) => {
|
|
1497
|
+
if (pattern.test(name))
|
|
1498
|
+
fire({ name, path: join3(settings.folder, name) });
|
|
1499
|
+
});
|
|
1500
|
+
}
|
|
1501
|
+
});
|
|
1502
|
+
var networkChange = defineTrigger({
|
|
1503
|
+
id: "network-change",
|
|
1504
|
+
permissions: [],
|
|
1505
|
+
name: "When the network changes",
|
|
1506
|
+
description: "Runs when network addresses change (event.online, event.addresses).",
|
|
1507
|
+
settings: {},
|
|
1508
|
+
subscribe: ({ fire }) => {
|
|
1509
|
+
let before;
|
|
1510
|
+
return network.listen((addresses) => {
|
|
1511
|
+
const key = addresses.join(`
|
|
1512
|
+
`);
|
|
1513
|
+
if (before !== undefined && key !== before) {
|
|
1514
|
+
fire({ online: addresses.length > 0, addresses });
|
|
1515
|
+
}
|
|
1516
|
+
before = key;
|
|
1517
|
+
});
|
|
1518
|
+
}
|
|
1519
|
+
});
|
|
1520
|
+
var idleTrigger = defineTrigger({
|
|
1521
|
+
id: "idle",
|
|
1522
|
+
permissions: ["process"],
|
|
1523
|
+
name: "When the computer is idle",
|
|
1524
|
+
description: "Runs after no keyboard or mouse input for a while, or when input comes back.",
|
|
1525
|
+
settings: {
|
|
1526
|
+
minutes: { type: "number", label: "Idle for (minutes)", default: 5, min: 1, max: 600 },
|
|
1527
|
+
when: {
|
|
1528
|
+
type: "select",
|
|
1529
|
+
label: "Run",
|
|
1530
|
+
default: "idle",
|
|
1531
|
+
options: [
|
|
1532
|
+
{ value: "idle", label: "When it becomes idle" },
|
|
1533
|
+
{ value: "back", label: "When input comes back" }
|
|
1534
|
+
]
|
|
1535
|
+
}
|
|
1536
|
+
},
|
|
1537
|
+
subscribe: ({ settings, fire, plugin }) => {
|
|
1538
|
+
const limit = settings.minutes * 60;
|
|
1539
|
+
let isIdle = false;
|
|
1540
|
+
const stop = idle.listen((seconds) => {
|
|
1541
|
+
if (!isIdle && seconds >= limit) {
|
|
1542
|
+
isIdle = true;
|
|
1543
|
+
if (settings.when === "idle")
|
|
1544
|
+
fire({ seconds });
|
|
1545
|
+
} else if (isIdle && seconds < limit) {
|
|
1546
|
+
isIdle = false;
|
|
1547
|
+
if (settings.when === "back")
|
|
1548
|
+
fire({ seconds });
|
|
1549
|
+
}
|
|
1550
|
+
});
|
|
1551
|
+
const check = setTimeout(() => {
|
|
1552
|
+
if (idleError)
|
|
1553
|
+
plugin.log("idle trigger:", idleError.message);
|
|
1554
|
+
}, 5000);
|
|
1555
|
+
return () => {
|
|
1556
|
+
clearTimeout(check);
|
|
1557
|
+
stop();
|
|
1558
|
+
};
|
|
1559
|
+
}
|
|
1560
|
+
});
|
|
1561
|
+
var appFocus = defineTrigger({
|
|
1562
|
+
id: "app-focus",
|
|
1563
|
+
permissions: ["process"],
|
|
1564
|
+
name: "When an app comes to the front",
|
|
1565
|
+
description: "Runs when a window of this app gets focus (event.app), or of any app if empty.",
|
|
1566
|
+
settings: {
|
|
1567
|
+
process: {
|
|
1568
|
+
...processSetting.process,
|
|
1569
|
+
description: "The executable name; empty means any app."
|
|
1570
|
+
}
|
|
1571
|
+
},
|
|
1572
|
+
subscribe: ({ settings, fire, plugin }) => {
|
|
1573
|
+
const target = settings.process.trim().toLowerCase();
|
|
1574
|
+
let first = true;
|
|
1575
|
+
const stop = foreground.listen((app) => {
|
|
1576
|
+
if (!first && app && (!target || app === target))
|
|
1577
|
+
fire({ app });
|
|
1578
|
+
first = false;
|
|
1579
|
+
});
|
|
1580
|
+
const check = setTimeout(() => {
|
|
1581
|
+
if (foregroundError)
|
|
1582
|
+
plugin.log("app focus trigger:", foregroundError.message);
|
|
1583
|
+
}, 5000);
|
|
1584
|
+
return () => {
|
|
1585
|
+
clearTimeout(check);
|
|
1586
|
+
stop();
|
|
1587
|
+
};
|
|
1588
|
+
}
|
|
1589
|
+
});
|
|
1590
|
+
var src_default = definePlugin({
|
|
1591
|
+
id: "@sdeck/plugin-system",
|
|
1592
|
+
name: "System",
|
|
1593
|
+
version: "0.3.0",
|
|
1594
|
+
description: "Open apps and run commands, press media keys and shortcuts, lock and sleep, take screenshots, and monitor the computer.",
|
|
1595
|
+
author: "sdeck",
|
|
1596
|
+
permissions: ["shell", "process", "input", "network", "filesystem"],
|
|
1597
|
+
settings: {
|
|
1598
|
+
pingHost: { type: "text", label: "Ping host", default: "1.1.1.1" },
|
|
1599
|
+
disks: {
|
|
1600
|
+
type: "text",
|
|
1601
|
+
label: "Disks",
|
|
1602
|
+
placeholder: process.platform === "win32" ? "C:, D:" : "/, /home",
|
|
1603
|
+
description: "Comma separated. Empty means the system disk."
|
|
1604
|
+
},
|
|
1605
|
+
presentMon: {
|
|
1606
|
+
type: "text",
|
|
1607
|
+
label: "PresentMon",
|
|
1608
|
+
default: "PresentMon",
|
|
1609
|
+
description: "Command or full path, for the frame rate (Windows)."
|
|
1610
|
+
}
|
|
1611
|
+
},
|
|
1612
|
+
actions: [open, command, media, hotkey, type, screenshot, lock, sleep, stats, pingAction],
|
|
1613
|
+
triggers: [appOpen, appClose, appFocus, fileCreated, networkChange, idleTrigger],
|
|
1614
|
+
state: [
|
|
1615
|
+
...monitoring,
|
|
1616
|
+
(() => {
|
|
1617
|
+
let sample;
|
|
1618
|
+
return {
|
|
1619
|
+
id: "cpu",
|
|
1620
|
+
permissions: [],
|
|
1621
|
+
name: "CPU use",
|
|
1622
|
+
type: "number",
|
|
1623
|
+
unit: "%",
|
|
1624
|
+
poll: {
|
|
1625
|
+
everyMs: 2000,
|
|
1626
|
+
read: () => {
|
|
1627
|
+
sample ??= cpuSampler();
|
|
1628
|
+
return sample();
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
};
|
|
1632
|
+
})(),
|
|
1633
|
+
{
|
|
1634
|
+
id: "memory",
|
|
1635
|
+
permissions: [],
|
|
1636
|
+
name: "Memory use",
|
|
1637
|
+
type: "number",
|
|
1638
|
+
unit: "%",
|
|
1639
|
+
poll: { everyMs: 2000, read: () => Math.round(100 * (1 - freemem() / totalmem())) }
|
|
1640
|
+
},
|
|
1641
|
+
{
|
|
1642
|
+
id: "memoryFree",
|
|
1643
|
+
permissions: [],
|
|
1644
|
+
name: "Free memory",
|
|
1645
|
+
type: "number",
|
|
1646
|
+
unit: "bytes",
|
|
1647
|
+
poll: { everyMs: 2000, read: () => freemem() }
|
|
1648
|
+
},
|
|
1649
|
+
{
|
|
1650
|
+
id: "processes",
|
|
1651
|
+
permissions: ["process"],
|
|
1652
|
+
name: "Running processes",
|
|
1653
|
+
type: "json",
|
|
1654
|
+
description: 'Lowercased names; e.g. contains(system.processes, "javaw.exe").',
|
|
1655
|
+
start: (set) => processes.listen((names) => set([...names]))
|
|
1656
|
+
},
|
|
1657
|
+
{
|
|
1658
|
+
id: "idle",
|
|
1659
|
+
permissions: ["process"],
|
|
1660
|
+
name: "Idle time",
|
|
1661
|
+
type: "number",
|
|
1662
|
+
unit: "s",
|
|
1663
|
+
description: "Seconds since the last keyboard or mouse input.",
|
|
1664
|
+
start: (set) => idle.listen(set)
|
|
1665
|
+
},
|
|
1666
|
+
{
|
|
1667
|
+
id: "foreground",
|
|
1668
|
+
permissions: ["process"],
|
|
1669
|
+
name: "App in front",
|
|
1670
|
+
type: "string",
|
|
1671
|
+
description: `The focused window's executable, lowercased ("javaw.exe"); empty when none. Profiles switch on it.`,
|
|
1672
|
+
start: (set) => foreground.listen(set)
|
|
1673
|
+
},
|
|
1674
|
+
{
|
|
1675
|
+
id: "online",
|
|
1676
|
+
permissions: [],
|
|
1677
|
+
name: "Online",
|
|
1678
|
+
type: "boolean",
|
|
1679
|
+
description: "Whether any network interface has an address.",
|
|
1680
|
+
start: (set) => network.listen((addresses) => set(addresses.length > 0))
|
|
1681
|
+
}
|
|
1682
|
+
],
|
|
1683
|
+
activate(context) {
|
|
1684
|
+
context.log("ready on", process.platform);
|
|
1685
|
+
}
|
|
1686
|
+
});
|
|
1687
|
+
export {
|
|
1688
|
+
INPUT_SIZE,
|
|
1689
|
+
NVIDIA_QUERY,
|
|
1690
|
+
Shared,
|
|
1691
|
+
Unavailable,
|
|
1692
|
+
capture,
|
|
1693
|
+
coreSampler,
|
|
1694
|
+
cpuSampler,
|
|
1695
|
+
cpuTemperature,
|
|
1696
|
+
src_default as default,
|
|
1697
|
+
diskUsage,
|
|
1698
|
+
encodeInputs,
|
|
1699
|
+
foregroundName,
|
|
1700
|
+
frameRate,
|
|
1701
|
+
hotkeyEvents,
|
|
1702
|
+
idleSeconds,
|
|
1703
|
+
isHost,
|
|
1704
|
+
listProcesses,
|
|
1705
|
+
macHotkey,
|
|
1706
|
+
namePattern,
|
|
1707
|
+
networkAddresses,
|
|
1708
|
+
openWithSystem,
|
|
1709
|
+
parseNetstat,
|
|
1710
|
+
parseNvidia,
|
|
1711
|
+
parsePing,
|
|
1712
|
+
parseProcNetDev,
|
|
1713
|
+
parseThermalZone,
|
|
1714
|
+
ping,
|
|
1715
|
+
presentMonParser,
|
|
1716
|
+
processChanges,
|
|
1717
|
+
readGpu,
|
|
1718
|
+
runShell,
|
|
1719
|
+
screenshotName,
|
|
1720
|
+
systemControls,
|
|
1721
|
+
textEvents,
|
|
1722
|
+
throughput,
|
|
1723
|
+
watchFolder,
|
|
1724
|
+
watchForeground,
|
|
1725
|
+
watchFrameRate,
|
|
1726
|
+
watchIdle,
|
|
1727
|
+
watchNetwork,
|
|
1728
|
+
xHotkey
|
|
1729
|
+
};
|
|
1730
|
+
|
|
1731
|
+
//# debugId=3CD66B15B6C2A72664756E2164756E21
|