Repository navigation
Expand file tree
/
Copy pathplugin.js
More file actions
298 lines (272 loc) · 13.3 KB
/
Copy pathplugin.js
File metadata and controls
298 lines (272 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
// Audio Switcher: OpenDeck keys that switch the default audio output / input.
//
// press -> mute / unmute the active device
// hold -> next *connected* device in the key's list (wraps around; after HOLD_MS)
//
// Each key's settings: { devices: [{ name, label, icon }] }
// name = PipeWire/PulseAudio node name (stable across reboots)
// label = description at the time it was picked (shown in the settings only)
// icon = icon-theme name (e.g. "audio-headphones") or a PNG/SVG path
// The key shows the active device's icon; muted = dimmed with a red slash.
//
// Talks to the sound server with pactl (works on PipeWire via pipewire-pulse)
// and follows changes made elsewhere through `pactl subscribe`.
// Runs on the host (see start.sh). No dependencies: Node 22 built-in WebSocket.
"use strict";
const fs = require("fs");
const path = require("path");
const os = require("os");
const { spawn, execFile } = require("child_process");
const HOME = os.homedir();
const HOLD_MS = 500;
const log = (...a) => console.error("[audioswitch]", ...a);
// ---------- args / websocket ----------
const arg = (k) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : undefined; };
const port = arg("-port"), pluginUUID = arg("-pluginUUID"), registerEvent = arg("-registerEvent");
if (!port || !pluginUUID || !registerEvent) { log("missing OpenDeck arguments"); process.exit(1); }
const ws = new WebSocket(`ws://127.0.0.1:${port}`);
const send = (o) => { try { ws.send(JSON.stringify(o)); } catch (e) { log("send failed", e.message); } };
ws.onopen = () => send({ event: registerEvent, uuid: pluginUUID });
ws.onclose = () => process.exit(0);
ws.onerror = (e) => log("websocket error", e.message || e);
// ---------- pactl ----------
function pactl(args) {
return new Promise((resolve) => {
execFile("pactl", args, { timeout: 4000, maxBuffer: 16 << 20 }, (err, out) => {
if (err) log("pactl", args.join(" "), "failed:", err.message.split("\n")[0]);
resolve(err ? null : out);
});
});
}
// kind: "output" (sinks) or "input" (sources, without speaker monitors)
const K = {
output: { list: "sinks", getDefault: "get-default-sink", setDefault: "set-default-sink", mute: "set-sink-mute", fallbackIcon: "audio-speakers" },
input: { list: "sources", getDefault: "get-default-source", setDefault: "set-default-source", mute: "set-source-mute", fallbackIcon: "audio-input-microphone" },
};
const state = { output: { devices: [], def: null }, input: { devices: [], def: null } };
async function refresh(kind) {
const k = K[kind];
const [json, def] = await Promise.all([pactl(["-f", "json", "list", k.list]), pactl([k.getDefault])]);
if (json === null) return;
let list = [];
try { list = JSON.parse(json); } catch (e) { log("bad pactl json", e.message); return; }
// speaker "Monitor of …" sources aren't real inputs (pipewire-pulse marks them
// with monitor_source = the sink name; device.class = "monitor")
if (kind === "input") list = list.filter((d) => !d.monitor_source && (d.properties || {})["device.class"] !== "monitor" && !/\.monitor$/.test(d.name));
state[kind].devices = list.map((d) => ({ name: d.name, label: d.description || d.name, mute: !!d.mute }));
state[kind].def = def ? def.trim() : null;
}
async function refreshAll() {
await Promise.all([refresh("output"), refresh("input")]);
for (const ctx of keys.keys()) render(ctx);
}
// follow changes made anywhere (volume applet, other apps, our own commands)
let refreshTimer = null;
function scheduleRefresh() { clearTimeout(refreshTimer); refreshTimer = setTimeout(refreshAll, 120); }
function startSubscribe() {
const sub = spawn("pactl", ["subscribe"]);
let buf = "";
sub.stdout.on("data", (c) => {
buf += c;
const lines = buf.split("\n"); buf = lines.pop();
if (lines.some((l) => / on (sink|source|server|card) /.test(l) && !/ on (sink|source)-output /.test(l))) scheduleRefresh();
});
sub.on("exit", (code) => { log("pactl subscribe exited", code, "- restarting in 3 s"); setTimeout(() => { startSubscribe(); refreshAll(); }, 3000); });
process.on("exit", () => sub.kill());
}
// ---------- icons (theme name or file) ----------
const DATA_DIRS = [path.join(HOME, ".local/share"), path.join(HOME, ".local/share/flatpak/exports/share"),
"/var/lib/flatpak/exports/share", "/usr/local/share", "/usr/share"];
const ICON_ROOTS = [path.join(HOME, ".local/share/icons"), path.join(HOME, ".icons"), ...DATA_DIRS.map((d) => path.join(d, "icons"))];
function themeFromKde() {
try { const m = fs.readFileSync(path.join(HOME, ".config/kdeglobals"), "utf8").match(/^\[Icons\][^[]*?^Theme=(.+)$/m); return m ? m[1].trim() : null; }
catch { return null; }
}
function themeFromGsettings() {
try {
const out = require("child_process").execFileSync("gsettings", ["get", "org.gnome.desktop.interface", "icon-theme"],
{ encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] });
return out.trim().replace(/^'(.*)'$/, "$1") || null;
} catch { return null; }
}
function themeFromGtkIni() {
for (const v of ["gtk-4.0", "gtk-3.0"]) {
try { const m = fs.readFileSync(path.join(HOME, ".config", v, "settings.ini"), "utf8").match(/^gtk-icon-theme-name\s*=\s*(.+)$/m); if (m) return m[1].trim().replace(/^"(.*)"$/, "$1"); }
catch { /* next */ }
}
return null;
}
let themeCache = null, themeTime = 0;
function iconTheme() {
if (themeCache && Date.now() - themeTime < 60000) return themeCache;
const kde = /KDE/i.test(process.env.XDG_CURRENT_DESKTOP || "");
const order = kde ? [themeFromKde, themeFromGsettings, themeFromGtkIni] : [themeFromGsettings, themeFromGtkIni, themeFromKde];
themeCache = "hicolor";
for (const f of order) { const t = f(); if (t) { themeCache = t; break; } }
themeTime = Date.now();
return themeCache;
}
// theme + its Inherits= chain, then hicolor
function themeChain(name, seen = new Set()) {
if (seen.has(name)) return [];
seen.add(name);
const out = [name];
for (const r of ICON_ROOTS) {
try {
const m = fs.readFileSync(path.join(r, name, "index.theme"), "utf8").match(/^Inherits\s*=\s*(.+)$/m);
if (m) for (const p of m[1].split(",")) out.push(...themeChain(p.trim(), seen));
break;
} catch { /* next root */ }
}
return out;
}
const CATEGORIES = ["devices", "status", "apps", "actions", "places", "categories", "mimetypes", "emblems", "panel"];
const SIZES = ["scalable", "512x512", "256x256", "128x128", "96x96", "64x64", "48x48", "32", "32x32", "24", "24x24", "22", "22x22", "symbolic"];
const iconPathCache = new Map();
function findIcon(name) {
if (!name) return null;
if (name.startsWith("/") || name.startsWith("~/")) {
const p = name.startsWith("~/") ? path.join(HOME, name.slice(2)) : name;
return fs.existsSync(p) ? p : null;
}
const theme = iconTheme(), key = theme + "\0" + name;
if (iconPathCache.has(key)) return iconPathCache.get(key);
let found = null;
const themes = [...new Set([...themeChain(theme), "hicolor"])];
search: for (const t of themes) for (const r of ICON_ROOTS) {
const base = path.join(r, t);
if (!fs.existsSync(base)) continue;
for (const s of SIZES) for (const c of CATEGORIES) for (const sub of [`${c}/${s}`, `${s}/${c}`]) for (const ext of [".svg", ".png"]) {
const p = path.join(base, sub, name + ext);
if (fs.existsSync(p)) { found = p; break search; }
}
}
if (!found) for (const d of DATA_DIRS) for (const ext of [".svg", ".png"]) {
const p = path.join(d, "pixmaps", name + ext);
if (!found && fs.existsSync(p)) found = p;
}
iconPathCache.set(key, found);
return found;
}
const dataCache = new Map();
function iconDataUrl(p) {
if (!p) return null;
if (!dataCache.has(p)) {
try {
const mime = p.endsWith(".svg") ? "image/svg+xml" : "image/png";
dataCache.set(p, `data:${mime};base64,${fs.readFileSync(fs.realpathSync(p)).toString("base64")}`);
} catch (e) { log("icon read failed", p, e.message); dataCache.set(p, null); }
}
return dataCache.get(p);
}
// ---------- keys ----------
const keys = new Map(); // context -> { kind, settings, timer, held, last }
const kindOf = (action) => (action && action.endsWith(".input") ? "input" : "output");
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
function render(ctx) {
const k = keys.get(ctx);
if (!k) return;
const st = state[k.kind];
const list = (k.settings.devices || []).filter((d) => d && d.name);
const active = st.devices.find((d) => d.name === st.def);
const entry = list.find((d) => d.name === st.def);
const muted = !!(active && active.mute);
const icon = iconDataUrl(findIcon((entry && entry.icon) || K[k.kind].fallbackIcon));
// optional per-device caption under the icon; the icon shrinks to make room
const caption = entry && entry.caption ? String(entry.caption).trim() : "";
const box = caption ? { x: 26, y: 6, s: 92 } : { x: 16, y: 16, s: 112 };
let svg = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="144" height="144" viewBox="0 0 144 144">`;
const op = muted ? ' opacity="0.4"' : "";
svg += icon
? `<image x="${box.x}" y="${box.y}" width="${box.s}" height="${box.s}" href="${icon}" xlink:href="${icon}" preserveAspectRatio="xMidYMid meet"${op}/>`
: `<rect x="${box.x}" y="${box.y}" width="${box.s}" height="${box.s}" rx="22" fill="#3a3a44"${op}/>`;
if (muted) {
const a = box.x + 8, b = box.x + box.s - 8, c = box.y + 8, d = box.y + box.s - 8;
svg += `<line x1="${a}" y1="${c}" x2="${b}" y2="${d}" stroke="#1b1b1f" stroke-width="20" stroke-linecap="round"/>`;
svg += `<line x1="${a}" y1="${c}" x2="${b}" y2="${d}" stroke="#e5383b" stroke-width="12" stroke-linecap="round"/>`;
}
const font = `font-family="Inter, 'Noto Sans', sans-serif" text-anchor="middle"`;
if (caption) {
const t = esc(caption.slice(0, 14));
// fit the width: bold sans glyphs average ~0.62 em; max 30 px, min 16 px
const n = Math.min(caption.length, 14);
const size = Math.max(16, Math.min(30, Math.floor(132 / (n * 0.62))));
// still too wide at the minimum size: squeeze to the key width
const fit = n * 0.62 * size > 136 ? ` textLength="136" lengthAdjust="spacingAndGlyphs"` : "";
// dark outline under white text so it reads over any background
svg += `<text x="72" y="134" ${font} font-weight="700" font-size="${size}" fill="#fff" stroke="#000" stroke-width="5" stroke-linejoin="round" paint-order="stroke"${fit}>${t}</text>`;
} else if (!entry && active) {
// device not in this key's list: show its name small at the bottom
svg += `<text x="72" y="136" ${font} font-size="15" fill="#ddd">${esc(active.label.slice(0, 18))}</text>`;
}
svg += "</svg>";
if (svg === k.last) return;
k.last = svg;
send({ event: "setImage", context: ctx, payload: { image: "data:image/svg+xml;base64," + Buffer.from(svg).toString("base64"), target: 0 } });
}
async function switchNext(k) {
const kc = K[k.kind], st = state[k.kind];
const present = new Set(st.devices.map((d) => d.name));
const list = (k.settings.devices || []).filter((d) => d && d.name);
const connected = list.filter((d) => present.has(d.name));
if (!connected.length) { log(k.kind, "none of the key's devices is connected"); return; }
const i = list.findIndex((d) => d.name === st.def);
// next connected entry after the current one, in list order (wraps)
let next = connected[0];
if (i >= 0) for (let j = 1; j <= list.length; j++) {
const c = list[(i + j) % list.length];
if (present.has(c.name)) { next = c; break; }
}
if (next.name !== st.def) await pactl([kc.setDefault, next.name]);
}
async function toggleMute(k) {
const kc = K[k.kind], st = state[k.kind];
if (st.def) await pactl([kc.mute, st.def, "toggle"]);
}
function setKey(ctx, action, settings) {
const old = keys.get(ctx);
keys.set(ctx, { kind: kindOf(action), settings: settings || {}, timer: old ? old.timer : null, held: false, last: null });
}
function deviceListFor(kind) {
return state[kind].devices.map(({ name, label }) => ({ name, label }));
}
ws.onmessage = async (ev) => {
let msg;
try { msg = JSON.parse(ev.data); } catch { return; }
const { event, context, action, payload } = msg;
const k = keys.get(context);
switch (event) {
case "willAppear":
case "didReceiveSettings":
setKey(context, action, payload && payload.settings);
render(context);
break;
case "willDisappear":
if (k) clearTimeout(k.timer);
keys.delete(context);
break;
case "keyDown":
if (!k) break;
k.held = false;
clearTimeout(k.timer);
k.timer = setTimeout(() => { k.held = true; switchNext(k).then(() => refresh(k.kind)).then(() => render(context)); }, HOLD_MS);
break;
case "keyUp":
if (!k) break;
clearTimeout(k.timer);
if (!k.held) { await toggleMute(k); await refresh(k.kind); render(context); }
k.held = false;
break;
case "propertyInspectorDidAppear":
case "sendToPlugin":
await refresh(kindOf(action));
send({ event: "sendToPropertyInspector", context, action, payload: { kind: kindOf(action), devices: deviceListFor(kindOf(action)), current: state[kindOf(action)].def } });
break;
}
};
// redraw when the icon theme changes
let lastTheme = iconTheme();
setInterval(() => { const t = iconTheme(); if (t !== lastTheme) { lastTheme = t; for (const [ctx, k] of keys) { k.last = null; render(ctx); } } }, 60000);
startSubscribe();
refreshAll();
log("started");