@sdeck/plugin-system 0.4.0 → 0.5.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/src/index.tsx CHANGED
@@ -1,22 +1,21 @@
1
1
  import { execFile, spawn } from "node:child_process";
2
2
  import { cpus, freemem, homedir, totalmem } from "node:os";
3
3
  import { basename, join } from "node:path";
4
- import {
5
- defineAction,
6
- definePlugin,
7
- defineTrigger,
8
- type PluginContext,
9
- Shared,
10
- type StateDef,
11
- } from "@sdeck/plugin";
4
+ import { createPlugin, Permissions, type PluginContext, Shared, setting } from "@sdeck/plugin";
12
5
  import {
13
6
  formatAccelerator,
14
7
  iconLayer,
15
8
  iconLook,
9
+ iconSize,
10
+ KEY,
16
11
  type Layer,
17
12
  type Look,
13
+ meterLayer,
18
14
  parseAccelerator,
15
+ readable,
16
+ surface,
19
17
  textLayer,
18
+ volumeStepLayers,
20
19
  } from "@sdeck/schema";
21
20
  import { type MediaKey, systemControls } from "./controls.ts";
22
21
  import {
@@ -26,6 +25,7 @@ import {
26
25
  type Disk,
27
26
  diskUsage,
28
27
  type Gpu,
28
+ isHost,
29
29
  ping,
30
30
  readGpu,
31
31
  watchFrameRate,
@@ -44,6 +44,77 @@ export * from "./controls.ts";
44
44
  export * from "./monitor.ts";
45
45
  export * from "./watchers.ts";
46
46
 
47
+ /** Something to ping. */
48
+ const hostField = (label: string) =>
49
+ setting.text(label, {
50
+ default: "1.1.1.1",
51
+ required: true,
52
+ validate: (host) =>
53
+ isHost(host.trim()) ? undefined : "should be a name or an address, like 1.1.1.1",
54
+ });
55
+
56
+ const plugin = createPlugin({
57
+ id: "@sdeck/plugin-system",
58
+ name: "System",
59
+ version: "0.5.0",
60
+ description:
61
+ "Open apps and run commands, press media keys and shortcuts, lock and sleep, take screenshots, and monitor the computer.",
62
+ author: "sdeck",
63
+ permissions: [
64
+ Permissions.shell,
65
+ Permissions.process,
66
+ Permissions.input,
67
+ Permissions.network,
68
+ Permissions.filesystem,
69
+ ],
70
+ settings: {
71
+ pingHost: hostField("Ping host"),
72
+ disks: setting.text("Disks", {
73
+ placeholder: process.platform === "win32" ? "C:, D:" : "/, /home",
74
+ description: "Comma separated. Empty means the system disk.",
75
+ }),
76
+ presentMon: setting.text("PresentMon", {
77
+ default: "PresentMon",
78
+ description: "Command or full path, for the frame rate (Windows).",
79
+ }),
80
+ },
81
+ });
82
+
83
+ const values = {
84
+ memory: plugin.state.number("memory", "Memory use", {
85
+ permissions: [],
86
+ unit: "%",
87
+ poll: { everyMs: 2000, read: () => Math.round(100 * (1 - freemem() / totalmem())) },
88
+ }),
89
+ memoryFree: plugin.state.number("memoryFree", "Free memory", {
90
+ permissions: [],
91
+ unit: "bytes",
92
+ poll: { everyMs: 2000, read: () => freemem() },
93
+ }),
94
+ processes: plugin.state.json("processes", "Running processes", {
95
+ permissions: [Permissions.process],
96
+ description: 'Lowercased names; e.g. contains(system.processes, "javaw.exe").',
97
+ start: (set) => processes.listen((names) => set([...names])),
98
+ }),
99
+ idle: plugin.state.number("idle", "Idle time", {
100
+ permissions: [Permissions.process],
101
+ unit: "s",
102
+ description: "Seconds since the last keyboard or mouse input.",
103
+ start: (set) => idle.listen(set),
104
+ }),
105
+ foreground: plugin.state.string("foreground", "App in front", {
106
+ permissions: [Permissions.process],
107
+ description:
108
+ 'The focused window\'s executable, lowercased ("javaw.exe"); empty when none. Profiles switch on it.',
109
+ start: (set) => foreground.listen(set),
110
+ }),
111
+ online: plugin.state.boolean("online", "Online", {
112
+ permissions: [],
113
+ description: "Whether any network interface has an address.",
114
+ start: (set) => network.listen((addresses) => set(addresses.length > 0)),
115
+ }),
116
+ };
117
+
47
118
  /** Opens a URL, file, folder or app with the system's default handler. */
48
119
  export function openWithSystem(target: string): void {
49
120
  const [command, args] =
@@ -96,68 +167,66 @@ export function runShell(
96
167
  });
97
168
  }
98
169
 
170
+ // What kind of thing a key does, by the colour of its icon.
171
+ const BLUE = "#60a5fa";
172
+ const GREEN = "#4ade80";
173
+ const VIOLET = "#a78bfa";
174
+ const ORANGE = "#fb923c";
175
+
99
176
  /** The user's image, or the action's icon, with their text under it when they gave one. */
100
- const buttonLook = (icon: string, caption: string, image: string, background: string): Look =>
101
- iconLook({ icon: image || icon, caption, background });
177
+ const buttonLook = (
178
+ icon: string,
179
+ color: string,
180
+ s: { text: string; image: string; background: string },
181
+ ): Look => iconLook({ icon: s.image || icon, color, caption: s.text, background: s.background });
102
182
 
103
- const open = defineAction({
183
+ const open = plugin.action({
104
184
  id: "open",
105
- permissions: ["process"],
185
+ permissions: [Permissions.process],
106
186
  name: "Open",
107
187
  description: "Opens a website, file, folder or app.",
108
188
  category: "System",
109
189
  icon: "external-link",
110
190
  settings: {
111
- target: {
112
- type: "text",
113
- label: "URL or path",
191
+ target: setting.text("URL or path", {
192
+ required: true,
114
193
  placeholder: "https://example.com or C:\\Tools\\app.exe",
115
- },
116
- text: {
117
- type: "text",
118
- label: "Text",
119
- placeholder: "Optional, under the icon",
120
- appearance: true,
121
- },
122
- image: { type: "image", label: "Image", appearance: true },
123
- background: { type: "color", label: "Background", default: "#0969da", appearance: true },
194
+ }),
195
+ text: setting.text("Text", { placeholder: "Optional, under the icon", appearance: true }),
196
+ image: setting.image("Image", { appearance: true }),
197
+ background: setting.color("Background", { default: KEY, appearance: true }),
124
198
  },
125
199
  run: ({ settings, plugin }) => {
126
- if (!settings.target) throw new Error("nothing to open");
127
200
  plugin.log("open", settings.target);
128
201
  openWithSystem(settings.target);
129
202
  return { label: `Open ${settings.target}` };
130
203
  },
131
- look: (s) => buttonLook("lucide/external-link", s.text, s.image, s.background),
204
+ look: (s) => buttonLook("lucide/external-link", BLUE, s),
132
205
  });
133
206
 
134
- const command = defineAction({
207
+ const command = plugin.action({
135
208
  id: "command",
136
- permissions: ["shell"],
209
+ permissions: [Permissions.shell],
137
210
  name: "Run command",
138
211
  description: "Runs a shell command. Fails when it exits with an error; its output is the result.",
139
212
  category: "System",
140
213
  icon: "terminal",
141
214
  settings: {
142
- command: { type: "text", label: "Command", placeholder: "echo hello", multiline: true },
143
- cwd: { type: "text", label: "Working directory", placeholder: "Defaults to your home folder" },
144
- undo: {
145
- type: "text",
146
- label: "Undo command",
215
+ command: setting.text("Command", {
216
+ required: true,
217
+ placeholder: "echo hello",
218
+ multiline: true,
219
+ }),
220
+ cwd: setting.text("Working directory", { placeholder: "Defaults to your home folder" }),
221
+ undo: setting.text("Undo command", {
147
222
  description: "Run to revert it (from the history, or a toggle's second press).",
148
223
  multiline: true,
149
- },
150
- text: {
151
- type: "text",
152
- label: "Text",
153
- placeholder: "Optional, under the icon",
154
- appearance: true,
155
- },
156
- image: { type: "image", label: "Image", appearance: true },
157
- background: { type: "color", label: "Background", default: "#24292f", appearance: true },
224
+ }),
225
+ text: setting.text("Text", { placeholder: "Optional, under the icon", appearance: true }),
226
+ image: setting.image("Image", { appearance: true }),
227
+ background: setting.color("Background", { default: KEY, appearance: true }),
158
228
  },
159
229
  run: async ({ settings, plugin, signal }) => {
160
- if (!settings.command) throw new Error("no command");
161
230
  const cwd = settings.cwd || homedir();
162
231
  plugin.log("run", settings.command);
163
232
  const { code, output } = await runShell(settings.command, cwd, signal);
@@ -174,7 +243,7 @@ const command = defineAction({
174
243
  }),
175
244
  };
176
245
  },
177
- look: (s) => buttonLook("lucide/terminal", s.text, s.image, s.background),
246
+ look: (s) => buttonLook("lucide/terminal", GREEN, s),
178
247
  });
179
248
 
180
249
  /** CPU use since the previous call, 0–100. */
@@ -240,7 +309,7 @@ const METRICS = {
240
309
  fps: { icon: "lucide/gauge", text: reading("fps", ""), bar: undefined },
241
310
  } as const;
242
311
 
243
- const stats = defineAction({
312
+ const stats = plugin.action({
244
313
  id: "stats",
245
314
  permissions: [],
246
315
  name: "System stats",
@@ -250,70 +319,72 @@ const stats = defineAction({
250
319
  icon: "activity",
251
320
  slots: ["key", "sensor", "window"],
252
321
  settings: {
253
- show: {
254
- type: "select",
255
- label: "Show",
256
- default: "both",
257
- options: [
258
- { value: "both", label: "CPU and memory" },
259
- { value: "cpu", label: "CPU" },
260
- { value: "core", label: "Busiest CPU core" },
261
- { value: "memory", label: "Memory" },
262
- { value: "disk", label: "Disk space used" },
263
- { value: "network", label: "Network speed" },
264
- { value: "ping", label: "Ping" },
265
- { value: "gpu", label: "GPU load (NVIDIA)" },
266
- { value: "gpu-temp", label: "GPU temperature (NVIDIA)" },
267
- { value: "cpu-temp", label: "CPU temperature" },
268
- { value: "fps", label: "Frame rate (PresentMon)" },
269
- ],
270
- },
271
- color: { type: "color", label: "Colour", default: "#58a6ff" },
272
- background: { type: "color", label: "Background", default: "#0d1117" },
322
+ show: setting.select("Show", {
323
+ both: "CPU and memory",
324
+ cpu: "CPU",
325
+ core: "Busiest CPU core",
326
+ memory: "Memory",
327
+ disk: "Disk space used",
328
+ network: "Network speed",
329
+ ping: "Ping",
330
+ gpu: "GPU load (NVIDIA)",
331
+ "gpu-temp": "GPU temperature (NVIDIA)",
332
+ "cpu-temp": "CPU temperature",
333
+ fps: "Frame rate (PresentMon)",
334
+ }),
335
+ color: setting.color("Colour", { default: BLUE }),
336
+ background: setting.color("Background", { default: KEY }),
273
337
  },
274
338
  display: true,
275
- look: (s): Look => {
276
- const bar = (id: string, value: string): Layer => ({
277
- id,
278
- type: "bar",
279
- value,
280
- color: s.color,
281
- track: "#30363d",
282
- position: "bottom",
283
- thickness: 6,
284
- });
339
+ look: (s, slot): Look => {
340
+ const background = surface(s.background);
285
341
  /** An icon and its value on one line. */
286
342
  const row = (id: string, icon: string, value: string, size: number): Layer[] => [
287
- iconLayer(`${id}-icon`, icon, { color: s.color, size: 22, row: id }),
288
- textLayer(id, value, { color: s.color, size, row: id }),
343
+ iconLayer(`${id}-icon`, icon, { color: s.color, size: 23, row: id }),
344
+ textLayer(id, value, { size, row: id }),
289
345
  ];
346
+ /** Two of them: under each other on a key, side by side in the window. */
347
+ const two = (a: Parameters<typeof row>, b: Parameters<typeof row>): Look => {
348
+ if (slot !== "window") return { background, layers: [...row(...a), ...row(...b)] };
349
+ const half = ([id, icon, value, size]: Parameters<typeof row>, x: number): Layer[] => [
350
+ iconLayer(`${id}-icon`, icon, {
351
+ color: s.color,
352
+ frame: { x, y: 28, width: 11, height: 44 },
353
+ }),
354
+ textLayer(id, value, {
355
+ size: size + 5,
356
+ align: "left",
357
+ frame: { x: x + 13, y: 15, width: 34, height: 70 },
358
+ }),
359
+ ];
360
+ return { background, layers: [...half(a, 6), ...half(b, 54)] };
361
+ };
290
362
  if (s.show === "both") {
291
- return {
292
- background: s.background,
293
- layers: [
294
- ...row("cpu", "lucide/cpu", "{{system.cpu}}%", 18),
295
- ...row("memory", "lucide/memory-stick", "{{system.memory}}%", 18),
296
- ],
297
- };
363
+ return two(
364
+ ["cpu", "lucide/cpu", "{{system.cpu}}%", 19],
365
+ ["memory", "lucide/memory-stick", "{{system.memory}}%", 19],
366
+ );
298
367
  }
299
368
  if (s.show === "network") {
300
- return {
301
- background: s.background,
302
- layers: [
303
- ...row("down", "lucide/arrow-down", "{{bytes(system.netDown ?? 0)}}", 13),
304
- ...row("up", "lucide/arrow-up", "{{bytes(system.netUp ?? 0)}}", 13),
305
- ],
306
- };
369
+ return two(
370
+ ["down", "lucide/arrow-down", "{{bytes(system.netDown ?? 0)}}", 13],
371
+ ["up", "lucide/arrow-up", "{{bytes(system.netUp ?? 0)}}", 13],
372
+ );
307
373
  }
308
374
  const metric = METRICS[s.show];
309
375
  // One line per metric so the layer ids stay stable for style rules.
310
376
  const id = s.show;
377
+ const line = slot === "window" ? { row: "line" } : {};
311
378
  return {
312
- background: s.background,
379
+ background,
313
380
  layers: [
314
- iconLayer(`${id}-icon`, metric.icon, { color: s.color, size: 40, position: "top" }),
315
- textLayer(id, metric.text, { color: s.color, size: 20, position: "bottom" }),
316
- ...(metric.bar ? [bar(`${id}-bar`, metric.bar)] : []),
381
+ iconLayer(`${id}-icon`, metric.icon, {
382
+ color: s.color,
383
+ size: slot === "window" ? 42 : 34,
384
+ ...line,
385
+ }),
386
+ textLayer(id, metric.text, { size: slot === "window" ? 24 : 22, ...line }),
387
+ ...(metric.bar ? [meterLayer(`${id}-bar`, metric.bar, { color: s.color })] : []),
317
388
  ],
318
389
  };
319
390
  },
@@ -322,43 +393,43 @@ const stats = defineAction({
322
393
  // -- Controls -------------------------------------------------------------------------------------
323
394
 
324
395
  const MEDIA = {
325
- "play-pause": { label: "Play / Pause", icons: ["play", "pause"], undo: "play-pause" },
326
- next: { label: "Next track", icons: ["skip-forward"], undo: "previous" },
327
- previous: { label: "Previous track", icons: ["skip-back"], undo: "next" },
328
- stop: { label: "Stop playback", icons: ["square"], undo: undefined },
329
- "volume-up": { label: "Volume up", icons: ["volume-2", "plus"], undo: "volume-down" },
330
- "volume-down": { label: "Volume down", icons: ["volume-1", "minus"], undo: "volume-up" },
396
+ "play-pause": { label: "Play / Pause", icons: ["Play", "Pause"], undo: "play-pause" },
397
+ next: { label: "Next track", icons: ["SkipForward"], undo: "previous" },
398
+ previous: { label: "Previous track", icons: ["SkipBack"], undo: "next" },
399
+ stop: { label: "Stop playback", icons: ["Stop"], undo: undefined },
400
+ "volume-up": { label: "Volume up", icons: ["volume"], undo: "volume-down" },
401
+ "volume-down": { label: "Volume down", icons: ["volume"], undo: "volume-up" },
331
402
  mute: { label: "Mute", icons: ["volume-x"], undo: "mute" },
332
403
  } as const satisfies Record<MediaKey, { label: string; icons: readonly string[]; undo?: MediaKey }>;
333
404
 
334
- const media = defineAction({
405
+ /** An object with the same keys. */
406
+ const mapValues = <K extends string, A, B>(from: Readonly<Record<K, A>>, map: (value: A) => B) =>
407
+ Object.fromEntries(Object.entries<A>(from).map(([key, value]) => [key, map(value)])) as Record<
408
+ K,
409
+ B
410
+ >;
411
+
412
+ const media = plugin.action({
335
413
  id: "media",
336
- permissions: ["input"],
414
+ permissions: [Permissions.input],
337
415
  name: "Media and volume",
338
416
  description: "Presses a media or volume key, as a keyboard would.",
339
417
  category: "Controls",
340
418
  icon: "play",
341
419
  slots: ["key", "sensor"],
342
420
  settings: {
343
- key: {
344
- type: "select",
345
- label: "Key",
346
- default: "play-pause",
347
- options: Object.entries(MEDIA).map(([value, m]) => ({ value, label: m.label })) as {
348
- value: MediaKey;
349
- label: string;
350
- }[],
351
- },
352
- steps: {
353
- type: "number",
354
- label: "Presses",
421
+ key: setting.select(
422
+ "Key",
423
+ mapValues(MEDIA, (m) => m.label),
424
+ ),
425
+ steps: setting.number("Presses", {
355
426
  description: "Each volume press is about 2%.",
356
427
  default: 1,
357
428
  min: 1,
358
429
  max: 50,
359
430
  visibleIf: { key: ["volume-up", "volume-down"] },
360
- },
361
- background: { type: "color", label: "Background", default: "#1f2937", appearance: true },
431
+ }),
432
+ background: setting.color("Background", { default: KEY, appearance: true }),
362
433
  },
363
434
  run: async ({ settings }) => {
364
435
  const controls = await systemControls();
@@ -371,38 +442,51 @@ const media = defineAction({
371
442
  const undo = MEDIA[key].undo;
372
443
  return { label: MEDIA[key].label, ...(undo && { undo: () => press(undo) }) };
373
444
  },
374
- look: (s): Look => {
445
+ look: (s, slot): Look => {
375
446
  const { icons } = MEDIA[s.key];
447
+ if (s.key === "volume-up" || s.key === "volume-down") {
448
+ const step = s.key === "volume-up" ? "plus" : "minus";
449
+ const color = readable("#f4f4f5", s.background);
450
+ return {
451
+ background: surface(s.background),
452
+ layers: volumeStepLayers(step, slot, { color }),
453
+ };
454
+ }
376
455
  return {
377
- background: s.background,
456
+ background: surface(s.background),
378
457
  layers: icons.map((name, i) =>
379
- iconLayer(i === 0 ? "icon" : `icon-${i + 1}`, `lucide/${name}`, {
380
- // The second icon of a pair is a smaller hint (play/pause are equals).
381
- size: icons.length === 1 ? 58 : s.key === "play-pause" ? 36 : i === 0 ? 46 : 26,
382
- row: "icons",
383
- }),
458
+ iconLayer(
459
+ i === 0 ? "icon" : `icon-${i + 1}`,
460
+ // Playback has filled symbols, as on a remote.
461
+ /^[A-Z]/.test(name) ? `tb/TbPlayer${name}Filled` : `lucide/${name}`,
462
+ {
463
+ color: readable("#f4f4f5", s.background),
464
+ size: icons.length === 1 ? iconSize(false) : 36,
465
+ row: "icons",
466
+ },
467
+ ),
384
468
  ),
385
469
  };
386
470
  },
387
471
  });
388
472
 
389
- const hotkey = defineAction({
473
+ const hotkey = plugin.action({
390
474
  id: "hotkey",
391
- permissions: ["input"],
475
+ permissions: [Permissions.input],
392
476
  name: "Press a shortcut",
393
477
  description: "Sends a keyboard shortcut to the focused app.",
394
478
  category: "Controls",
395
479
  icon: "keyboard",
396
480
  slots: ["key", "sensor"],
397
481
  settings: {
398
- keys: { type: "text", label: "Shortcut", placeholder: "ctrl+shift+m" },
399
- text: {
400
- type: "text",
401
- label: "Text",
402
- placeholder: "Defaults to the shortcut",
403
- appearance: true,
404
- },
405
- background: { type: "color", label: "Background", default: "#374151", appearance: true },
482
+ keys: setting.text("Shortcut", {
483
+ required: true,
484
+ placeholder: "ctrl+shift+m",
485
+ // It says what is wrong itself.
486
+ validate: (keys) => void parseAccelerator(keys),
487
+ }),
488
+ text: setting.text("Text", { placeholder: "Defaults to the shortcut", appearance: true }),
489
+ background: setting.color("Background", { default: KEY, appearance: true }),
406
490
  },
407
491
  run: async ({ settings }) => {
408
492
  const accelerator = parseAccelerator(settings.keys);
@@ -410,81 +494,77 @@ const hotkey = defineAction({
410
494
  return { label: `Press ${formatAccelerator(accelerator)}` };
411
495
  },
412
496
  look: (s) =>
413
- iconLook({ icon: "lucide/keyboard", caption: s.text || s.keys, background: s.background }),
497
+ iconLook({
498
+ icon: "lucide/keyboard",
499
+ color: VIOLET,
500
+ caption: s.text || s.keys,
501
+ background: s.background,
502
+ }),
414
503
  });
415
504
 
416
- const type = defineAction({
505
+ const type = plugin.action({
417
506
  id: "type",
418
- permissions: ["input"],
507
+ permissions: [Permissions.input],
419
508
  name: "Type text",
420
509
  description: "Types text into the focused app. The text can use {{templates}}.",
421
510
  category: "Controls",
422
511
  icon: "text-cursor-input",
423
512
  slots: ["key", "sensor"],
424
513
  settings: {
425
- content: { type: "text", label: "Text to type", multiline: true },
426
- text: {
427
- type: "text",
428
- label: "Key text",
429
- placeholder: "Optional, under the icon",
430
- appearance: true,
431
- },
432
- background: { type: "color", label: "Background", default: "#374151", appearance: true },
514
+ content: setting.text("Text to type", { required: true, multiline: true }),
515
+ text: setting.text("Key text", { placeholder: "Optional, under the icon", appearance: true }),
516
+ background: setting.color("Background", { default: KEY, appearance: true }),
433
517
  },
434
518
  run: async ({ settings }) => {
435
- if (!settings.content) throw new Error("nothing to type");
436
519
  await (await systemControls()).type(settings.content);
437
520
  return { label: `Type ${settings.content.length} character(s)` };
438
521
  },
439
522
  look: (s) =>
440
- iconLook({ icon: "lucide/text-cursor-input", caption: s.text, background: s.background }),
523
+ iconLook({
524
+ icon: "lucide/text-cursor-input",
525
+ color: VIOLET,
526
+ caption: s.text,
527
+ background: s.background,
528
+ }),
441
529
  });
442
530
 
443
- const lock = defineAction({
531
+ const lock = plugin.action({
444
532
  id: "lock",
445
- permissions: ["process"],
533
+ permissions: [Permissions.process],
446
534
  name: "Lock the screen",
447
535
  category: "Controls",
448
536
  icon: "lock",
449
537
  slots: ["key", "sensor"],
450
538
  settings: {
451
- text: {
452
- type: "text",
453
- label: "Text",
454
- placeholder: "Optional, under the icon",
455
- appearance: true,
456
- },
457
- background: { type: "color", label: "Background", default: "#7c2d12", appearance: true },
539
+ text: setting.text("Text", { placeholder: "Optional, under the icon", appearance: true }),
540
+ background: setting.color("Background", { default: KEY, appearance: true }),
458
541
  },
459
542
  run: async () => {
460
543
  await (await systemControls()).lock();
461
544
  return { label: "Lock the screen" };
462
545
  },
463
- look: (s) => iconLook({ icon: "lucide/lock", caption: s.text, background: s.background }),
546
+ look: (s) =>
547
+ iconLook({ icon: "lucide/lock", color: ORANGE, caption: s.text, background: s.background }),
464
548
  });
465
549
 
466
- const sleep = defineAction({
550
+ const sleep = plugin.action({
467
551
  id: "sleep",
468
- permissions: ["process"],
552
+ permissions: [Permissions.process],
469
553
  name: "Sleep",
470
554
  description: "Puts the computer to sleep.",
471
555
  category: "Controls",
472
556
  icon: "moon",
473
557
  slots: ["key", "sensor"],
474
558
  settings: {
475
- text: {
476
- type: "text",
477
- label: "Text",
478
- placeholder: "Optional, under the icon",
479
- appearance: true,
480
- },
481
- background: { type: "color", label: "Background", default: "#1e1b4b", appearance: true },
559
+ text: setting.text("Text", { placeholder: "Optional, under the icon", appearance: true }),
560
+ background: setting.color("Background", { default: KEY, appearance: true }),
482
561
  },
483
562
  run: async () => {
484
563
  await (await systemControls()).sleep();
485
564
  return { label: "Sleep" };
486
565
  },
487
- look: (s) => iconLook({ icon: "lucide/moon", caption: s.text, background: s.background }),
566
+ look: (s) =>
567
+ iconLook({ icon: "lucide/moon", color: VIOLET, caption: s.text, background: s.background }),
488
568
  });
489
569
 
490
570
  /** `screenshot-20261130-142501.png`. */
@@ -495,37 +575,19 @@ export function screenshotName(at: Date): string {
495
575
  return `screenshot-${day}-${time}.png`;
496
576
  }
497
577
 
498
- const screenshot = defineAction({
578
+ const screenshot = plugin.action({
499
579
  id: "screenshot",
500
- permissions: ["process", "filesystem"],
580
+ permissions: [Permissions.process, Permissions.filesystem],
501
581
  name: "Screenshot",
502
582
  description: "Saves the screen to a file (the result), or opens the region picker.",
503
583
  category: "Controls",
504
584
  icon: "camera",
505
585
  slots: ["key", "sensor"],
506
586
  settings: {
507
- mode: {
508
- type: "select",
509
- label: "Capture",
510
- default: "file",
511
- options: [
512
- { value: "file", label: "Whole screen, to a file" },
513
- { value: "snip", label: "A region I choose" },
514
- ],
515
- },
516
- folder: {
517
- type: "text",
518
- label: "Folder",
519
- placeholder: "Pictures/sdeck",
520
- visibleIf: { mode: "file" },
521
- },
522
- text: {
523
- type: "text",
524
- label: "Text",
525
- placeholder: "Optional, under the icon",
526
- appearance: true,
527
- },
528
- background: { type: "color", label: "Background", default: "#065f46", appearance: true },
587
+ mode: setting.select("Capture", { file: "Whole screen, to a file", snip: "A region I choose" }),
588
+ folder: setting.text("Folder", { placeholder: "Pictures/sdeck", visibleIf: { mode: "file" } }),
589
+ text: setting.text("Text", { placeholder: "Optional, under the icon", appearance: true }),
590
+ background: setting.color("Background", { default: KEY, appearance: true }),
529
591
  },
530
592
  run: async ({ settings }) => {
531
593
  const controls = await systemControls();
@@ -541,27 +603,29 @@ const screenshot = defineAction({
541
603
  look: (s) =>
542
604
  iconLook({
543
605
  icon: s.mode === "snip" ? "lucide/scissors" : "lucide/camera",
606
+ color: GREEN,
544
607
  caption: s.text,
545
608
  background: s.background,
546
609
  }),
547
610
  });
548
611
 
549
- const pingAction = defineAction({
612
+ const pingAction = plugin.action({
550
613
  id: "ping",
551
- permissions: ["network"],
614
+ permissions: [Permissions.network],
552
615
  name: "Ping",
553
616
  description: "Pings a host; the result is the round trip in ms. Fails when it does not answer.",
554
617
  category: "Monitoring",
555
618
  icon: "radio",
556
619
  settings: {
557
- host: { type: "text", label: "Host", default: "1.1.1.1" },
558
- background: { type: "color", label: "Background", default: "#0d1117", appearance: true },
620
+ host: hostField("Host"),
621
+ background: setting.color("Background", { default: KEY, appearance: true }),
559
622
  },
560
623
  run: async ({ settings, signal }) => {
561
624
  const ms = await ping(settings.host, signal);
562
625
  return { result: ms, label: `Ping ${settings.host}: ${ms} ms` };
563
626
  },
564
- look: (s) => iconLook({ icon: "lucide/activity", caption: s.host, background: s.background }),
627
+ look: (s) =>
628
+ iconLook({ icon: "lucide/activity", color: BLUE, caption: s.host, background: s.background }),
565
629
  });
566
630
 
567
631
  // -- Shared sources ------------------------------------------------------------------------------
@@ -683,111 +747,101 @@ const throughputSource = new Shared<Counters>((emit) =>
683
747
  );
684
748
  let networkError: ((error: Error) => void) | undefined;
685
749
 
686
- const netState = (id: string, name: string, pick: (c: Counters) => number): StateDef => ({
687
- id,
688
- name,
689
- type: "number",
690
- unit: "B/s",
691
- permissions: ["process"],
692
- start: (set, context) => {
750
+ const reportNetwork =
751
+ (pick: (c: Counters) => number) => (set: (value: number) => void, context: PluginContext) => {
693
752
  networkError = (error) => markUnavailable(context, "network speed", error);
694
753
  return throughputSource.listen((rate) => set(pick(rate)));
695
- },
696
- });
754
+ };
697
755
 
698
- const gpuState = (
699
- id: string,
700
- name: string,
701
- type: "number" | "string",
702
- pick: (g: Gpu) => unknown,
703
- unit?: string,
704
- ): StateDef => ({
705
- id,
706
- name,
707
- type,
708
- ...(unit && { unit }),
709
- permissions: ["process"],
756
+ /** One of the graphics card's values. */
757
+ const fromGpu = <T,>(pick: (g: Gpu) => T) => ({
758
+ permissions: [Permissions.process],
710
759
  poll: {
711
760
  everyMs: 2000,
712
- read: async (context) => {
761
+ read: async (context: PluginContext) => {
713
762
  const g = await gpu(context);
714
763
  return g && pick(g);
715
764
  },
716
765
  },
717
766
  });
718
767
 
719
- const monitoring: StateDef[] = [
720
- (() => {
721
- let sample: (() => number[]) | undefined;
722
- return {
723
- id: "cpuCores",
724
- permissions: [],
725
- name: "CPU use per core",
726
- type: "json" as const,
727
- description: "system.cpuCores[0] is the first core.",
728
- poll: {
729
- everyMs: 2000,
730
- read: () => {
731
- sample ??= coreSampler();
732
- return sample();
733
- },
734
- },
735
- };
736
- })(),
737
- {
738
- id: "disks",
739
- permissions: ["filesystem"],
740
- name: "Disks",
741
- type: "json",
768
+ /** A reading against the one before it: the first is against the moment it was first asked for. */
769
+ function sampled<T>(start: () => () => T): () => T {
770
+ let sample: (() => T) | undefined;
771
+ return () => {
772
+ sample ??= start();
773
+ return sample();
774
+ };
775
+ }
776
+
777
+ const monitoring = {
778
+ cpu: plugin.state.number("cpu", "CPU use", {
779
+ permissions: [],
780
+ unit: "%",
781
+ poll: { everyMs: 2000, read: sampled(cpuSampler) },
782
+ }),
783
+ cpuCores: plugin.state.json("cpuCores", "CPU use per core", {
784
+ permissions: [],
785
+ description: "system.cpuCores[0] is the first core.",
786
+ poll: { everyMs: 2000, read: sampled(coreSampler) },
787
+ }),
788
+ disks: plugin.state.json("disks", "Disks", {
789
+ permissions: [Permissions.filesystem],
742
790
  description: "system.disks.c.percent, .free, .total (choose them in the plugin's settings).",
743
791
  poll: { everyMs: 15_000, read: disks },
744
- },
745
- {
746
- id: "disk",
747
- permissions: ["filesystem"],
748
- name: "Disk space used",
749
- type: "number",
792
+ }),
793
+ disk: plugin.state.number("disk", "Disk space used", {
794
+ permissions: [Permissions.filesystem],
750
795
  unit: "%",
751
796
  description: "The first disk in the plugin's settings.",
752
797
  poll: {
753
798
  everyMs: 15_000,
754
799
  read: async (context) => Object.values(await disks(context))[0]?.percent,
755
800
  },
756
- },
757
- netState("netDown", "Download speed", (c) => c.received),
758
- netState("netUp", "Upload speed", (c) => c.sent),
759
- {
760
- id: "ping",
761
- permissions: ["network"],
762
- name: "Ping",
763
- type: "number",
801
+ }),
802
+ netDown: plugin.state.number("netDown", "Download speed", {
803
+ permissions: [Permissions.process],
804
+ unit: "B/s",
805
+ start: reportNetwork((c) => c.received),
806
+ }),
807
+ netUp: plugin.state.number("netUp", "Upload speed", {
808
+ permissions: [Permissions.process],
809
+ unit: "B/s",
810
+ start: reportNetwork((c) => c.sent),
811
+ }),
812
+ ping: plugin.state.number("ping", "Ping", {
813
+ permissions: [Permissions.network],
764
814
  unit: "ms",
765
815
  description: "To the host in the plugin's settings.",
766
816
  poll: {
767
817
  everyMs: 5000,
768
- read: (context) => measured(context, "ping", () => ping(String(context.settings().pingHost))),
818
+ read: (context) => measured(context, "ping", () => ping(context.settings().pingHost)),
769
819
  },
770
- },
771
- gpuState("gpu", "GPU load", "number", (g) => g.load, "%"),
772
- gpuState("gpuTemp", "GPU temperature", "number", (g) => g.temperature, "°C"),
773
- gpuState("gpuMemory", "GPU memory used", "number", (g) => g.memory, "%"),
774
- gpuState("gpuName", "GPU name", "string", (g) => g.name),
775
- {
776
- id: "cpuTemp",
777
- permissions: ["process"],
778
- name: "CPU temperature",
779
- type: "number",
820
+ }),
821
+ gpu: plugin.state.number("gpu", "GPU load", { unit: "%", ...fromGpu((g) => g.load) }),
822
+ gpuTemp: plugin.state.number("gpuTemp", "GPU temperature", {
823
+ unit: "°C",
824
+ ...fromGpu((g) => g.temperature),
825
+ }),
826
+ gpuMemory: plugin.state.number("gpuMemory", "GPU memory used", {
827
+ unit: "%",
828
+ ...fromGpu((g) => g.memory),
829
+ }),
830
+ gpuName: plugin.state.string(
831
+ "gpuName",
832
+ "GPU name",
833
+ fromGpu((g) => g.name),
834
+ ),
835
+ cpuTemp: plugin.state.number("cpuTemp", "CPU temperature", {
836
+ permissions: [Permissions.process],
780
837
  unit: "°C",
781
838
  poll: {
782
839
  everyMs: 5000,
783
840
  read: (context) => measured(context, "CPU temperature", () => cpuTemperature()),
784
841
  },
785
- },
786
- {
787
- id: "fps",
788
- permissions: ["process"],
789
- name: "Frame rate",
790
- type: "number",
842
+ }),
843
+ fps: plugin.state.number("fps", "Frame rate", {
844
+ permissions: [Permissions.process],
791
845
  description: "Of the app in front, measured by PresentMon.",
792
846
  start: (set, context) => {
793
847
  // Kept current so the app in front is the one measured.
@@ -799,7 +853,7 @@ const monitoring: StateDef[] = [
799
853
  const begin = () => {
800
854
  stop();
801
855
  stop = watchFrameRate(
802
- String(context.settings().presentMon),
856
+ context.settings().presentMon,
803
857
  () => front,
804
858
  set,
805
859
  (error) => markUnavailable(context, "frame rate", error),
@@ -819,19 +873,18 @@ const monitoring: StateDef[] = [
819
873
  stopFront();
820
874
  };
821
875
  },
822
- },
823
- ];
876
+ }),
877
+ };
824
878
 
825
879
  // -- Triggers ------------------------------------------------------------------------------------
826
880
 
827
881
  const processSetting = {
828
- process: {
829
- type: "text",
830
- label: "Process",
882
+ process: setting.text("Process", {
883
+ required: true,
831
884
  placeholder: "javaw.exe",
832
885
  description: "The executable name, as in the task manager (case does not matter).",
833
- },
834
- } as const;
886
+ }),
887
+ };
835
888
 
836
889
  /** Fires `fire` when `name` starts (`started`) or stops, ignoring the state it was in at first. */
837
890
  function onProcess(name: string, want: "started" | "stopped", fire: (event: unknown) => void) {
@@ -847,37 +900,38 @@ function onProcess(name: string, want: "started" | "stopped", fire: (event: unkn
847
900
  });
848
901
  }
849
902
 
850
- const appOpen = defineTrigger({
903
+ const appOpen = plugin.trigger({
851
904
  id: "app-open",
852
- permissions: ["process"],
905
+ permissions: [Permissions.process],
853
906
  name: "When an app opens",
854
907
  description: "Runs when a process starts (checked every 3 s).",
855
908
  settings: processSetting,
856
909
  subscribe: ({ settings, fire }) => onProcess(settings.process, "started", fire),
857
910
  });
858
911
 
859
- const appClose = defineTrigger({
912
+ const appClose = plugin.trigger({
860
913
  id: "app-close",
861
- permissions: ["process"],
914
+ permissions: [Permissions.process],
862
915
  name: "When an app closes",
863
916
  description: "Runs when a process exits (checked every 3 s).",
864
917
  settings: processSetting,
865
918
  subscribe: ({ settings, fire }) => onProcess(settings.process, "stopped", fire),
866
919
  });
867
920
 
868
- const fileCreated = defineTrigger({
921
+ const fileCreated = plugin.trigger({
869
922
  id: "file-created",
870
- permissions: ["filesystem"],
923
+ permissions: [Permissions.filesystem],
871
924
  name: "When a file appears",
872
925
  description: "Runs when a new file shows up in a folder (event.name, event.path).",
873
926
  settings: {
874
- folder: { type: "text", label: "Folder", placeholder: "C:\\Users\\me\\Downloads" },
875
- pattern: {
876
- type: "text",
877
- label: "Name pattern",
927
+ folder: setting.text("Folder", {
928
+ required: true,
929
+ placeholder: "C:\\Users\\me\\Downloads",
930
+ }),
931
+ pattern: setting.text("Name pattern", {
878
932
  placeholder: "*.png",
879
933
  description: "Empty means any file.",
880
- },
934
+ }),
881
935
  },
882
936
  subscribe: ({ settings, fire }) => {
883
937
  if (!settings.folder) throw new Error("no folder");
@@ -888,7 +942,7 @@ const fileCreated = defineTrigger({
888
942
  },
889
943
  });
890
944
 
891
- const networkChange = defineTrigger({
945
+ const networkChange = plugin.trigger({
892
946
  id: "network-change",
893
947
  permissions: [],
894
948
  name: "When the network changes",
@@ -906,22 +960,14 @@ const networkChange = defineTrigger({
906
960
  },
907
961
  });
908
962
 
909
- const idleTrigger = defineTrigger({
963
+ const idleTrigger = plugin.trigger({
910
964
  id: "idle",
911
- permissions: ["process"],
965
+ permissions: [Permissions.process],
912
966
  name: "When the computer is idle",
913
967
  description: "Runs after no keyboard or mouse input for a while, or when input comes back.",
914
968
  settings: {
915
- minutes: { type: "number", label: "Idle for (minutes)", default: 5, min: 1, max: 600 },
916
- when: {
917
- type: "select",
918
- label: "Run",
919
- default: "idle",
920
- options: [
921
- { value: "idle", label: "When it becomes idle" },
922
- { value: "back", label: "When input comes back" },
923
- ],
924
- },
969
+ minutes: setting.number("Idle for (minutes)", { default: 5, min: 1, max: 600 }),
970
+ when: setting.select("Run", { idle: "When it becomes idle", back: "When input comes back" }),
925
971
  },
926
972
  subscribe: ({ settings, fire, plugin }) => {
927
973
  const limit = settings.minutes * 60;
@@ -945,14 +991,15 @@ const idleTrigger = defineTrigger({
945
991
  },
946
992
  });
947
993
 
948
- const appFocus = defineTrigger({
994
+ const appFocus = plugin.trigger({
949
995
  id: "app-focus",
950
- permissions: ["process"],
996
+ permissions: [Permissions.process],
951
997
  name: "When an app comes to the front",
952
998
  description: "Runs when a window of this app gets focus (event.app), or of any app if empty.",
953
999
  settings: {
954
1000
  process: {
955
1001
  ...processSetting.process,
1002
+ required: false,
956
1003
  description: "The executable name; empty means any app.",
957
1004
  },
958
1005
  },
@@ -974,102 +1021,11 @@ const appFocus = defineTrigger({
974
1021
  },
975
1022
  });
976
1023
 
977
- export default definePlugin({
978
- id: "@sdeck/plugin-system",
979
- name: "System",
980
- version: "0.4.0",
981
- description:
982
- "Open apps and run commands, press media keys and shortcuts, lock and sleep, take screenshots, and monitor the computer.",
983
- author: "sdeck",
984
- permissions: ["shell", "process", "input", "network", "filesystem"],
985
- settings: {
986
- pingHost: { type: "text", label: "Ping host", default: "1.1.1.1" },
987
- disks: {
988
- type: "text",
989
- label: "Disks",
990
- placeholder: process.platform === "win32" ? "C:, D:" : "/, /home",
991
- description: "Comma separated. Empty means the system disk.",
992
- },
993
- presentMon: {
994
- type: "text",
995
- label: "PresentMon",
996
- default: "PresentMon",
997
- description: "Command or full path, for the frame rate (Windows).",
998
- },
999
- },
1024
+ export default plugin.define({
1000
1025
  actions: [open, command, media, hotkey, type, screenshot, lock, sleep, stats, pingAction],
1001
1026
  triggers: [appOpen, appClose, appFocus, fileCreated, networkChange, idleTrigger],
1002
- state: [
1003
- ...monitoring,
1004
- (() => {
1005
- let sample: (() => number) | undefined;
1006
- return {
1007
- id: "cpu",
1008
- permissions: [],
1009
- name: "CPU use",
1010
- type: "number" as const,
1011
- unit: "%",
1012
- poll: {
1013
- everyMs: 2000,
1014
- read: () => {
1015
- sample ??= cpuSampler();
1016
- return sample();
1017
- },
1018
- },
1019
- };
1020
- })(),
1021
- {
1022
- id: "memory",
1023
- permissions: [],
1024
- name: "Memory use",
1025
- type: "number",
1026
- unit: "%",
1027
- poll: { everyMs: 2000, read: () => Math.round(100 * (1 - freemem() / totalmem())) },
1028
- },
1029
- {
1030
- id: "memoryFree",
1031
- permissions: [],
1032
- name: "Free memory",
1033
- type: "number",
1034
- unit: "bytes",
1035
- poll: { everyMs: 2000, read: () => freemem() },
1036
- },
1037
- {
1038
- id: "processes",
1039
- permissions: ["process"],
1040
- name: "Running processes",
1041
- type: "json",
1042
- description: 'Lowercased names; e.g. contains(system.processes, "javaw.exe").',
1043
- start: (set) => processes.listen((names) => set([...names])),
1044
- },
1045
- {
1046
- id: "idle",
1047
- permissions: ["process"],
1048
- name: "Idle time",
1049
- type: "number",
1050
- unit: "s",
1051
- description: "Seconds since the last keyboard or mouse input.",
1052
- start: (set) => idle.listen(set),
1053
- },
1054
- {
1055
- id: "foreground",
1056
- permissions: ["process"],
1057
- name: "App in front",
1058
- type: "string",
1059
- description:
1060
- 'The focused window\'s executable, lowercased ("javaw.exe"); empty when none. Profiles switch on it.',
1061
- start: (set) => foreground.listen(set),
1062
- },
1063
- {
1064
- id: "online",
1065
- permissions: [],
1066
- name: "Online",
1067
- type: "boolean",
1068
- description: "Whether any network interface has an address.",
1069
- start: (set) => network.listen((addresses) => set(addresses.length > 0)),
1070
- },
1071
- ],
1072
- activate(context: PluginContext) {
1027
+ state: [...Object.values(values), ...Object.values(monitoring)],
1028
+ activate(context) {
1073
1029
  context.log("ready on", process.platform);
1074
1030
  },
1075
1031
  });