Repository navigation
Expand file tree
/
Copy pathplugin.js
More file actions
392 lines (361 loc) · 16.9 KB
/
Copy pathplugin.js
File metadata and controls
392 lines (361 loc) · 16.9 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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
// App Badges: an OpenDeck key that launches an app and shows its unread count
// as a red badge in the top-right corner.
//
// Counts come from com.canonical.Unity.LauncherEntry "Update" signals on the
// session bus (Telegram, Discord and most Electron/Qt apps send them; KDE's
// taskbar badges use the same thing). Apps only send on change, so the last
// known counts are saved to ~/.cache/opendeck-appbadges.json.
//
// 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 } = require("child_process");
const HOME = os.homedir();
const CACHE = path.join(HOME, ".cache", "opendeck-appbadges.json");
const log = (...a) => console.error("[appbadges]", ...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);
// ---------- desktop entries & icons ----------
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",
];
function parseDesktop(file) {
const out = {};
let inMain = false;
for (const line of fs.readFileSync(file, "utf8").split("\n")) {
if (line.startsWith("[")) { inMain = line.trim() === "[Desktop Entry]"; continue; }
if (!inMain) continue;
const m = line.match(/^([A-Za-z-]+)=(.*)$/);
if (m && !(m[1] in out)) out[m[1]] = m[2];
}
return out;
}
function listApps() {
const seen = new Map();
for (const d of DATA_DIRS) {
let files = [];
try { files = fs.readdirSync(path.join(d, "applications")); } catch { continue; }
for (const f of files) {
if (!f.endsWith(".desktop")) continue;
const id = f.slice(0, -8);
if (seen.has(id)) continue;
try {
const e = parseDesktop(path.join(d, "applications", f));
if (e.Type !== "Application" || e.NoDisplay === "true" || e.Hidden === "true") continue;
seen.set(id, { id, name: e.Name || id, icon: e.Icon || "", file: path.join(d, "applications", f) });
} catch { /* unreadable */ }
}
}
return [...seen.values()].sort((a, b) => a.name.localeCompare(b.name));
}
// The desktop's icon theme: KDE (kdeglobals), GNOME & co. (gsettings), or the
// GTK settings files. Tried in the order that fits XDG_CURRENT_DESKTOP; falls
// back to "hicolor", which every system has. Re-read at most once a minute.
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;
}
function findIcon(name) {
if (!name) return null;
if (name.startsWith("/")) return fs.existsSync(name) ? name : null;
const themes = [iconTheme(), "hicolor"];
const roots = [path.join(HOME, ".local/share/icons"), path.join(HOME, ".icons"), ...DATA_DIRS.map((d) => path.join(d, "icons"))];
// prefer scalable SVG, then the biggest PNG
const sizes = ["scalable", "512x512", "256x256", "192x192", "128x128", "96x96", "64x64", "48x48"];
for (const t of themes) for (const r of roots) {
const base = path.join(r, t);
if (!fs.existsSync(base)) continue;
for (const s of sizes) for (const sub of [`${s}/apps`, `apps/${s}`]) for (const ext of [".svg", ".png"]) {
const p = path.join(base, sub, name + ext);
if (fs.existsSync(p)) return p;
}
}
for (const d of DATA_DIRS) for (const ext of [".svg", ".png"]) {
const p = path.join(d, "pixmaps", name + ext);
if (fs.existsSync(p)) return p;
}
return null;
}
const iconCache = new Map(); // path -> data URL
function iconDataUrl(p) {
if (!p) return null;
if (!iconCache.has(p)) {
try {
const mime = p.endsWith(".svg") ? "image/svg+xml" : "image/png";
iconCache.set(p, `data:${mime};base64,${fs.readFileSync(fs.realpathSync(p)).toString("base64")}`);
} catch (e) { log("icon read failed", p, e.message); iconCache.set(p, null); }
}
return iconCache.get(p);
}
// ---------- counts ----------
let counts = {};
try { counts = JSON.parse(fs.readFileSync(CACHE, "utf8")); } catch { /* first run */ }
let saveTimer = null;
function saveCounts() {
clearTimeout(saveTimer);
saveTimer = setTimeout(() => {
try { fs.mkdirSync(path.dirname(CACHE), { recursive: true }); fs.writeFileSync(CACHE, JSON.stringify(counts)); }
catch (e) { log("cache write failed", e.message); }
}, 500);
}
function setCount(appId, props) {
const before = JSON.stringify(counts[appId]);
const cur = { count: 0, visible: false, ...counts[appId] }; // copy: compare old vs new
if ("count" in props) cur.count = props.count;
if ("visible" in props) cur.visible = props.visible;
counts[appId] = cur;
if (JSON.stringify(cur) === before) return;
saveCounts();
for (const [ctx, k] of keys) if (k.settings.app === appId) render(ctx);
}
// dbus-monitor output, one signal at a time:
// signal ... member=Update
// string "application://org.telegram.desktop.desktop"
// ... string "count" / variant int64 44 / string "count-visible" / variant boolean true
function startMonitor() {
const mon = spawn("dbus-monitor", ["--session", "type='signal',interface='com.canonical.Unity.LauncherEntry',member='Update'"]);
let buf = "", app = null, expect = null;
mon.stdout.on("data", (chunk) => {
buf += chunk;
let nl;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl).trim();
buf = buf.slice(nl + 1);
let m;
if (line.startsWith("signal ")) { app = null; expect = null; }
else if (!app && (m = line.match(/^string "application:\/\/(.+?)(?:\.desktop)?"$/))) app = m[1];
else if (app && line === 'string "count"') expect = "count";
else if (app && line === 'string "count-visible"') expect = "visible";
else if (app && expect === "count" && (m = line.match(/^variant\s+u?int(?:64|32)\s+(-?\d+)/))) { setCount(app, { count: Number(m[1]) }); expect = null; }
else if (app && expect === "visible" && (m = line.match(/^variant\s+boolean\s+(true|false)/))) { setCount(app, { visible: m[1] === "true" }); expect = null; }
}
});
mon.on("exit", (code) => { log("dbus-monitor exited", code, "- restarting in 5 s"); setTimeout(startMonitor, 5000); });
process.on("exit", () => mon.kill());
}
startMonitor();
// ---------- keys ----------
const keys = new Map(); // context -> { settings }
function esc(s) { return String(s).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]); }
function render(ctx) {
const k = keys.get(ctx);
if (!k) return;
const appId = k.settings.app;
const app = appId ? listApps().find((a) => a.id === appId) : null;
const icon = iconDataUrl(k.settings.icon || findIcon(app && app.icon));
const c = counts[appId];
const n = c && c.visible ? c.count : 0;
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">`;
svg += icon
? `<image x="16" y="16" width="112" height="112" href="${icon}" xlink:href="${icon}" preserveAspectRatio="xMidYMid meet"/>`
: `<rect x="16" y="16" width="112" height="112" rx="24" fill="#3a3a44"/><text x="72" y="84" font-family="sans-serif" font-size="22" fill="#ddd" text-anchor="middle">${esc(app ? app.name : "pick app")}</text>`;
if (n > 0) {
const label = n > 99 ? "99+" : String(n);
const w = label.length === 1 ? 46 : label.length === 2 ? 56 : 70; // pill grows with digits
const x = 140 - w, h = 46;
svg += `<rect x="${x}" y="4" width="${w}" height="${h}" rx="${h / 2}" fill="#e5383b" stroke="#1b1b1f" stroke-width="3"/>`;
svg += `<text x="${x + w / 2}" y="${4 + h / 2 + 11}" font-family="Inter, 'Noto Sans', sans-serif" font-weight="700" font-size="31" fill="#fff" text-anchor="middle">${label}</text>`;
}
svg += "</svg>";
send({ event: "setImage", context: ctx, payload: { image: "data:image/svg+xml;base64," + Buffer.from(svg).toString("base64"), target: 0 } });
}
function launch(appId) {
if (!appId) return;
const p = spawn("gtk-launch", [appId], { detached: true, stdio: "ignore" });
p.on("error", (e) => log("launch failed", appId, e.message));
p.unref();
}
// ---------- press / hold ----------
// press -> bring the app's window to the front; repeated presses cycle
// through its windows. Not running -> launch it.
// hold -> (HOLD_MS) open a new window. Not running -> launch it.
// Window handling uses KWin's D-Bus API (KDE Plasma). Elsewhere, or if KWin
// can't be reached, both just launch the app as before.
const { execFile } = require("child_process");
function gdbus(args) {
return new Promise((resolve) => {
execFile("gdbus", ["call", "--session", ...args], { timeout: 3000 }, (err, out) => resolve(err ? null : out));
});
}
// All normal windows of the app: [{ id, uuid }] in a stable order.
async function appWindows(app, entry) {
const all = await gdbus(["--dest", "org.kde.KWin", "--object-path", "/WindowsRunner", "--method", "org.kde.krunner1.Match", "window"]);
if (all === null) return null; // no KWin
const uuids = [...new Set([...all.matchAll(/'0_(\{[0-9a-f-]+\})'/g)].map((m) => m[1]))];
// what this app's windows can be called: desktop id, StartupWMClass, binary
// name, a Flatpak's --command, and the distinctive parts of a reverse-DNS id
// (X11 apps such as com.bitwarden.desktop just say "bitwarden")
const argv = execArgv(entry.Exec || "");
const bin = (argv[0] || "").split("/").pop();
const cmd = (argv.find((a) => a.startsWith("--command=")) || "").slice(10).split("/").pop();
const generic = new Set(["com", "org", "io", "net", "dev", "github", "gitlab", "desktop", "app", "kde", "gnome", "freedesktop", "flatpak"]);
const parts = app.id.split(".").filter((p) => p.length > 2 && !generic.has(p.toLowerCase()));
const names = new Set([app.id, entry.StartupWMClass, bin === "flatpak" ? "" : bin, cmd, ...(app.id.includes(".") ? parts : [])]
.filter(Boolean).map((s) => s.toLowerCase().replace(/\.(sh|appimage|bin|exe)$/, "")));
const infos = await Promise.all(uuids.map((u) =>
gdbus(["--dest", "org.kde.KWin", "--object-path", "/KWin", "--method", "org.kde.KWin.getWindowInfo", u])));
const prop = (s, k) => { const m = s.match(new RegExp(`'${k}': <'?([^'>]*)'?>`)); return m ? m[1] : ""; };
const out = [];
uuids.forEach((u, i) => {
const s = infos[i];
if (!s || prop(s, "skipTaskbar") === "true") return;
const keys = [prop(s, "desktopFile"), prop(s, "resourceClass"), prop(s, "resourceName")].map((x) => x.toLowerCase());
if (keys.some((x) => x && names.has(x))) out.push({ id: "0_" + u, uuid: u });
});
return out.sort((a, b) => a.uuid.localeCompare(b.uuid));
}
const cursor = new Map(); // app id -> uuid of the window we activated last
async function focusOrLaunch(app, entry) {
const wins = await appWindows(app, entry);
if (!wins || wins.length === 0) return launch(app.id);
const last = cursor.get(app.id);
const i = wins.findIndex((w) => w.uuid === last);
const next = wins[(i + 1) % wins.length]; // i = -1 -> first window
cursor.set(app.id, next.uuid);
const r = await gdbus(["--dest", "org.kde.KWin", "--object-path", "/WindowsRunner", "--method", "org.kde.krunner1.Run", next.id, ""]);
if (r === null) launch(app.id);
}
// [Desktop Action …] sections: { id: { Name, Exec } }
function desktopActions(file) {
const out = {};
let cur = null;
for (const line of fs.readFileSync(file, "utf8").split("\n")) {
const h = line.match(/^\[Desktop Action ([^\]]+)\]/);
if (h) { cur = out[h[1]] = {}; continue; }
if (line.startsWith("[")) { cur = null; continue; }
const m = cur && line.match(/^(Name|Exec)=(.*)$/);
if (m) cur[m[1]] = m[2];
}
return out;
}
// Exec= value -> argv, per the desktop entry spec (quotes, escapes, field codes)
function execArgv(exec) {
const args = [];
let cur = "", q = false, any = false;
for (let i = 0; i < exec.length; i++) {
const c = exec[i];
if (q && c === "\\" && i + 1 < exec.length) { cur += exec[++i]; continue; }
if (c === '"') { q = !q; any = true; continue; }
if (!q && /\s/.test(c)) { if (cur || any) args.push(cur); cur = ""; any = false; continue; }
cur += c;
}
if (cur || any) args.push(cur);
return args.map((a) => a.replace(/%%/g, "\0").replace(/%[fFuUdDnNickvm]/g, "").replace(/\0/g, "%")).filter((a) => a !== "");
}
function openNewWindow(app) {
let actions = {};
try { actions = desktopActions(app.file); } catch { /* none */ }
// "new-window", "NewWindow", "new-empty-window" … but not "new-private-window"
// (and not screenshot actions like "ActiveWindowScreenShot")
const id = Object.keys(actions).find((a) => /^new[-_ ]?window$/i.test(a))
|| Object.keys(actions).find((a) => /^new[-_ ]?\w*[-_ ]?window$/i.test(a) && !/private|incognito/i.test(a));
const argv = id && actions[id].Exec ? execArgv(actions[id].Exec) : null;
if (!argv || !argv.length) return launch(app.id); // no such action: a normal launch
const p = spawn(argv[0], argv.slice(1), { detached: true, stdio: "ignore" });
p.on("error", (e) => { log("new window failed", app.id, e.message); launch(app.id); });
p.unref();
}
const HOLD_MS = 500;
async function activate(settings, hold) {
const appId = settings && settings.app;
if (!appId) return;
const app = listApps().find((a) => a.id === appId);
if (!app) return launch(appId);
let entry = {};
try { entry = parseDesktop(app.file); } catch { /* unreadable */ }
if (hold) {
const wins = await appWindows(app, entry);
return wins && wins.length ? openNewWindow(app) : launch(app.id);
}
return focusOrLaunch(app, entry);
}
const holdTimers = new Map(); // context -> { timer, held }
ws.onmessage = (ev) => {
let msg;
try { msg = JSON.parse(ev.data); } catch { return; }
const { event, context, payload } = msg;
switch (event) {
case "willAppear":
keys.set(context, { settings: (payload && payload.settings) || {} });
render(context);
break;
case "willDisappear":
keys.delete(context);
break;
case "didReceiveSettings":
keys.set(context, { settings: (payload && payload.settings) || {} });
render(context);
break;
case "keyDown": {
const st = (keys.get(context) || {}).settings || payload?.settings;
const h = { held: false };
h.timer = setTimeout(() => { h.held = true; activate(st, true).catch((e) => log("hold failed", e.message)); }, HOLD_MS);
clearTimeout((holdTimers.get(context) || {}).timer);
holdTimers.set(context, h);
break;
}
case "keyUp": {
const h = holdTimers.get(context);
holdTimers.delete(context);
if (!h) break;
clearTimeout(h.timer);
if (!h.held) activate((keys.get(context) || {}).settings || payload?.settings, false).catch((e) => log("press failed", e.message));
break;
}
case "propertyInspectorDidAppear":
case "sendToPlugin":
send({
event: "sendToPropertyInspector", context, action: msg.action,
payload: { apps: listApps().map(({ id, name }) => ({ id, name })), counts },
});
break;
}
};
// Redraw all keys when the icon theme changes (checked once a minute).
let lastTheme = iconTheme();
setInterval(() => {
const t = iconTheme();
if (t !== lastTheme) { log("icon theme changed:", lastTheme, "->", t); lastTheme = t; for (const ctx of keys.keys()) render(ctx); }
}, 60000);
log("started");