aboutsummaryrefslogtreecommitdiffstats
path: root/desktop/modules/mimeapps
diff options
context:
space:
mode:
Diffstat (limited to 'desktop/modules/mimeapps')
-rw-r--r--desktop/modules/mimeapps/MimeApps.js140
-rw-r--r--desktop/modules/mimeapps/test_mimeapps.js69
2 files changed, 209 insertions, 0 deletions
diff --git a/desktop/modules/mimeapps/MimeApps.js b/desktop/modules/mimeapps/MimeApps.js
new file mode 100644
index 0000000..9e3c670
--- /dev/null
+++ b/desktop/modules/mimeapps/MimeApps.js
@@ -0,0 +1,140 @@
+.pragma library
+// Copyright (C) 2026 Danilo M. <danix@danix.xyz>
+//
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License version 2 as
+// published by the Free Software Foundation.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// Pure helpers for the default apps page, tested by test_mimeapps.js under
+// node. Every edit works on the text of mimeapps.list and touches only the
+// one line it means: other sections ([Added Associations] included),
+// comments and blank lines survive byte for byte. The file is walked line by
+// line, never cut "up to the next [" (AGENTS.md, the INI note).
+
+const SECTION = "[Default Applications]";
+
+// The role rows, each setting its whole group of types at once.
+const ROLES = [
+ { label: "Browser", mimes: ["text/html", "application/xhtml+xml", "x-scheme-handler/http", "x-scheme-handler/https"] },
+ { label: "Mail", mimes: ["x-scheme-handler/mailto"] },
+ { label: "Text", mimes: ["text/plain"] },
+ { label: "PDF", mimes: ["application/pdf"] },
+ { label: "Image", mimes: ["image/png", "image/jpeg", "image/gif", "image/webp", "image/svg+xml"] },
+ { label: "Video", mimes: ["video/mp4", "video/x-matroska", "video/webm"] },
+ { label: "Audio", mimes: ["audio/mpeg", "audio/flac", "audio/ogg", "audio/x-wav"] },
+ { label: "Files", mimes: ["inode/directory"] },
+ { label: "Archive", mimes: ["application/zip", "application/x-tar", "application/x-7z-compressed", "application/gzip"] },
+];
+
+// The trailing newline is dropped on split and always put back on join.
+function lines(text) { return text === "" ? [] : text.replace(/\n$/, "").split("\n"); }
+function join(ls) { return ls.join("\n") + "\n"; }
+
+// The key of a "key=value" line, null for a comment, header or blank.
+function keyOf(line) {
+ const m = /^\s*([^#=\s[][^=]*?)\s*=/.exec(line);
+ return m ? m[1] : null;
+}
+
+// [header index, end index (exclusive)] of the section, or null.
+function section(ls) {
+ const start = ls.findIndex(l => l.trim() === SECTION);
+ if (start < 0) return null;
+ let end = start + 1;
+ while (end < ls.length && !/^\s*\[/.test(ls[end])) end++;
+ return [start, end];
+}
+
+// { mime: desktopId } from [Default Applications]. A value is a ;-list and
+// its first item is the default.
+function parse(text) {
+ const ls = lines(text), s = section(ls), out = {};
+ if (!s) return out;
+ for (let i = s[0] + 1; i < s[1]; i++) {
+ const k = keyOf(ls[i]);
+ if (k === null) continue;
+ const id = ls[i].slice(ls[i].indexOf("=") + 1).split(";").map(x => x.trim()).find(x => x);
+ if (id) out[k] = id;
+ }
+ return out;
+}
+
+function set(text, mime, id) {
+ const ls = lines(text);
+ let s = section(ls);
+ if (!s) {
+ if (ls.length > 0 && ls[ls.length - 1].trim() !== "") ls.push("");
+ ls.push(SECTION);
+ s = [ls.length - 1, ls.length];
+ }
+ const line = mime + "=" + id + ";";
+ for (let i = s[0] + 1; i < s[1]; i++)
+ if (keyOf(ls[i]) === mime) { ls[i] = line; return join(ls); }
+ // After the last non-blank line, so a blank line before the next header stays.
+ let at = s[1];
+ while (at > s[0] + 1 && ls[at - 1].trim() === "") at--;
+ ls.splice(at, 0, line);
+ return join(ls);
+}
+
+// The header stays even when its last entry goes, so the text written is
+// never empty (FileView.setText("") writes nothing, AGENTS.md).
+function remove(text, mime) {
+ const ls = lines(text), s = section(ls);
+ if (!s) return text;
+ for (let i = s[0] + 1; i < s[1]; i++)
+ if (keyOf(ls[i]) === mime) { ls.splice(i, 1); return join(ls); }
+ return text;
+}
+
+// The applications directories in XDG order, the user's first.
+function dirs(home, dataHome, dataDirs) {
+ return [dataHome || home + "/.local/share"]
+ .concat((dataDirs || "/usr/local/share:/usr/share").split(":"))
+ .filter(d => d)
+ .map(d => d.replace(/\/+$/, "") + "/applications");
+}
+
+// grep -rH '^MimeType=' output -> { desktopId: [mimes] }. The id is the path
+// under applications/ with "/" as "-" (desktop entry spec); the first
+// directory to list an id wins, which is the user's when it has one.
+function scan(out, appDirs) {
+ const apps = {};
+ for (const line of out.split("\n")) {
+ const i = line.indexOf(":MimeType=");
+ if (i < 0) continue;
+ const path = line.slice(0, i);
+ const dir = appDirs.find(d => path.startsWith(d + "/"));
+ if (!dir) continue;
+ const id = path.slice(dir.length + 1).replace(/\//g, "-");
+ if (id in apps) continue;
+ apps[id] = line.slice(i + ":MimeType=".length).split(";").filter(m => m);
+ }
+ return apps;
+}
+
+// The app most of a role's types point at ("" when none is set), and how
+// many distinct apps they point at.
+function role(defaults, mimes) {
+ const n = {};
+ for (const m of mimes) if (defaults[m]) n[defaults[m]] = (n[defaults[m]] || 0) + 1;
+ const ids = Object.keys(n).sort((a, b) => n[b] - n[a]);
+ return { id: ids[0] || "", apps: ids.length };
+}
+
+// The ids declaring at least one of the types.
+function handlers(apps, mimes) {
+ return Object.keys(apps).filter(id => apps[id].some(m => mimes.includes(m)));
+}
+
+// Every type any installed app declares, sorted.
+function allMimes(apps) {
+ const seen = {};
+ for (const id in apps) for (const m of apps[id]) seen[m] = true;
+ return Object.keys(seen).sort();
+}
diff --git a/desktop/modules/mimeapps/test_mimeapps.js b/desktop/modules/mimeapps/test_mimeapps.js
new file mode 100644
index 0000000..469c9a4
--- /dev/null
+++ b/desktop/modules/mimeapps/test_mimeapps.js
@@ -0,0 +1,69 @@
+// Copyright (C) 2026 Danilo M. <danix@danix.xyz>
+//
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License version 2 as
+// published by the Free Software Foundation.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// Run: node desktop/modules/mimeapps/test_mimeapps.js
+// MimeApps.js is a QML library, so its .pragma line is stripped before node
+// evaluates it.
+
+const fs = require("fs");
+const assert = require("assert");
+
+const src = fs.readFileSync(__dirname + "/MimeApps.js", "utf8").replace(/^\.pragma library$/m, "");
+const M = new Function(src + "\nreturn { ROLES, parse, set, remove, scan, dirs, role, handlers, allMimes };")();
+
+// Added Associations is not read as defaults; comments, blank lines and
+// other sections survive every edit byte for byte.
+const file = "[Added Associations]\ntext/plain=qpdfview.desktop;\n\n"
+ + "[Default Applications]\n# browser\ntext/html=firefox.desktop\ntext/plain=featherpad.desktop;okular.desktop;\n\n"
+ + "[Other]\nk=v\n";
+assert.deepStrictEqual(M.parse(file), { "text/html": "firefox.desktop", "text/plain": "featherpad.desktop" });
+assert.deepStrictEqual(M.parse(""), {});
+
+// set: in place, or after the section's last entry (before its blank line),
+// or a new section at the end, or the section alone in an empty file.
+assert.strictEqual(M.set(file, "text/html", "chromium.desktop"),
+ file.replace("text/html=firefox.desktop", "text/html=chromium.desktop;"));
+assert.strictEqual(M.set(file, "image/png", "lximage-qt.desktop"),
+ file.replace("okular.desktop;\n", "okular.desktop;\nimage/png=lximage-qt.desktop;\n"));
+assert.strictEqual(M.set("[Added Associations]\na/b=x.desktop;\n", "a/b", "y.desktop"),
+ "[Added Associations]\na/b=x.desktop;\n\n[Default Applications]\na/b=y.desktop;\n");
+assert.strictEqual(M.set("", "a/b", "y.desktop"), "[Default Applications]\na/b=y.desktop;\n");
+// A key that only starts with the type is a different key.
+assert.strictEqual(M.set("[Default Applications]\ntext/plainx=a.desktop;\n", "text/plain", "b.desktop"),
+ "[Default Applications]\ntext/plainx=a.desktop;\ntext/plain=b.desktop;\n");
+
+// remove: only that line; the header stays, so the text is never empty.
+assert.strictEqual(M.remove(file, "text/html"), file.replace("text/html=firefox.desktop\n", ""));
+assert.strictEqual(M.remove(file, "nope/x"), file);
+assert.strictEqual(M.remove("[Default Applications]\na/b=y.desktop;\n", "a/b"), "[Default Applications]\n");
+
+// dirs: the user's first, trailing slashes dropped.
+const dirs = M.dirs("/home/you", "", "/usr/local/share/:/usr/share");
+assert.deepStrictEqual(dirs, ["/home/you/.local/share/applications", "/usr/local/share/applications", "/usr/share/applications"]);
+assert.deepStrictEqual(M.dirs("/home/you", "/x", ""), ["/x/applications", "/usr/local/share/applications", "/usr/share/applications"]);
+
+// scan: the first dir wins for one id; a subdirectory joins with "-".
+const out = "/home/you/.local/share/applications/firefox.desktop:MimeType=text/html;\n"
+ + "/usr/share/applications/firefox.desktop:MimeType=text/html;image/png;\n"
+ + "/usr/share/applications/kde4/okular.desktop:MimeType=application/pdf;\n";
+assert.deepStrictEqual(M.scan(out, dirs), { "firefox.desktop": ["text/html"], "kde4-okular.desktop": ["application/pdf"] });
+assert.deepStrictEqual(M.scan("", dirs), {});
+
+// role: the app most types point at, and how many distinct apps.
+assert.deepStrictEqual(M.role({ a: "x.desktop", b: "y.desktop", c: "x.desktop" }, ["a", "b", "c", "d"]), { id: "x.desktop", apps: 2 });
+assert.deepStrictEqual(M.role({}, ["a"]), { id: "", apps: 0 });
+
+assert.deepStrictEqual(M.handlers({ "f.desktop": ["text/html"], "o.desktop": ["application/pdf"] }, ["text/html", "x/y"]), ["f.desktop"]);
+assert.deepStrictEqual(M.allMimes({ f: ["b", "a"], g: ["a"] }), ["a", "b"]);
+
+for (const r of M.ROLES) assert.ok(r.label && r.mimes.length > 0, r.label);
+
+console.log("ok");