Open History to see the last commit
1import type { NativeAppIconReference, ToolActivityNativeAppReference } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Path from "effect/Path";
5import * as HostProcess from "@t3tools/shared/HostProcess";
6
7import { existingFile, type NativeAppIconSource } from "./source.ts";
8
9/** Sizes worth serving for a 64px icon, best first; the client scales down. */
10const PREFERRED_SIZES = [64, 128, 96, 72, 256, 48, 512, 32] as const;
11const ICON_EXTENSIONS = [".png", ".svg"] as const;
12const MAX_DESKTOP_FILE_BYTES = 64 * 1024;
13
14export interface DesktopEntry {
15 readonly name: string;
16 readonly icon: string;
17 readonly wmClass: string | undefined;
18 readonly fileStem: string;
19}
20
21/**
22 * Reads the `[Desktop Entry]` group of a freedesktop launcher. Only the keys
23 * the icon lookup needs are kept; localized `Name[xx]` variants are ignored
24 * because agents see the unlocalized window class.
25 */
26export function parseDesktopEntry(contents: string, fileStem: string): DesktopEntry | undefined {
27 let inEntry = false;
28 let name: string | undefined;
29 let icon: string | undefined;
30 let wmClass: string | undefined;
31 let hidden = false;
32 for (const rawLine of contents.split(/\r?\n/u)) {
33 const line = rawLine.trim();
34 if (line.startsWith("[")) {
35 inEntry = line === "[Desktop Entry]";
36 continue;
37 }
38 if (!inEntry || line.startsWith("#")) continue;
39 const separator = line.indexOf("=");
40 if (separator === -1) continue;
41 const key = line.slice(0, separator).trim();
42 const value = line.slice(separator + 1).trim();
43 if (key === "Name") name = value;
44 else if (key === "Icon") icon = value;
45 else if (key === "StartupWMClass") wmClass = value;
46 else if ((key === "NoDisplay" || key === "Hidden") && value === "true") hidden = true;
47 }
48 if (hidden || !name || !icon) return undefined;
49 return { name, icon, wmClass, fileStem };
50}
51
52const normalize = (value: string) => value.trim().toLocaleLowerCase();
53
54/**
55 * Window classes rarely match launcher names (Chromium reports `Chromium-browser` for
56 * `chromium.desktop`), so the strictest match ranks first and `StartupWMClass` wins.
57 */
58export function rankDesktopEntry(entry: DesktopEntry, app: ToolActivityNativeAppReference): number {
59 const wanted = normalize(app._tag === "app-id" ? app.appId : app.displayName);
60 const wmClass = entry.wmClass ? normalize(entry.wmClass) : undefined;
61 const name = normalize(entry.name);
62 const stem = normalize(entry.fileStem);
63 if (wmClass === wanted) return 5;
64 if (app._tag === "app-id" && stem === wanted) return 4;
65 if (name === wanted || stem === wanted) return 3;
66 if (wanted.startsWith(`${stem}-`) || wanted.startsWith(`${name}-`)) return 2;
67 if (name.length >= 3 && wanted.startsWith(name)) return 1;
68 return 0;
69}
70
71const applicationDirectories = Effect.fn("NativeAppIconResolver.linux.applicationDirectories")(
72 function* () {
73 const path = yield* Path.Path;
74 const environment = yield* HostProcess.Environment;
75 const dataHome =
76 environment.XDG_DATA_HOME?.trim() ||
77 (environment.HOME ? path.join(environment.HOME, ".local", "share") : undefined);
78 const dataDirs = (environment.XDG_DATA_DIRS?.trim() || "/usr/local/share:/usr/share")
79 .split(":")
80 .map((entry) => entry.trim())
81 .filter((entry) => entry.length > 0 && path.isAbsolute(entry));
82 const roots = [...(dataHome ? [dataHome] : []), ...dataDirs];
83 return {
84 applications: roots.map((root) => path.join(root, "applications")),
85 icons: roots.flatMap((root) => [
86 path.join(root, "icons", "hicolor"),
87 path.join(root, "pixmaps"),
88 ]),
89 };
90 },
91);
92
93const readDesktopEntries = Effect.fn("NativeAppIconResolver.linux.readDesktopEntries")(function* (
94 directories: ReadonlyArray<string>,
95) {
96 const fileSystem = yield* FileSystem.FileSystem;
97 const path = yield* Path.Path;
98 const entries: DesktopEntry[] = [];
99 for (const directory of directories) {
100 const fileNames = yield* fileSystem
101 .readDirectory(directory)
102 .pipe(Effect.orElseSucceed((): string[] => []));
103 for (const fileName of fileNames) {
104 if (!fileName.endsWith(".desktop")) continue;
105 const filePath = path.join(directory, fileName);
106 const info = yield* fileSystem.stat(filePath).pipe(Effect.option);
107 if (info._tag === "None" || info.value.type !== "File") continue;
108 if (info.value.size > MAX_DESKTOP_FILE_BYTES) continue;
109 const contents = yield* fileSystem.readFileString(filePath).pipe(Effect.option);
110 if (contents._tag === "None") continue;
111 const entry = parseDesktopEntry(contents.value, path.basename(fileName, ".desktop"));
112 if (entry) entries.push(entry);
113 }
114 }
115 return entries;
116});
117
118/**
119 * `Icon=` is either an absolute path or a theme name looked up in hicolor by
120 * size, then in pixmaps. A relative path with separators is rejected rather
121 * than joined, since the entry could point anywhere.
122 */
123const resolveIconFile = Effect.fn("NativeAppIconResolver.linux.resolveIconFile")(function* (
124 icon: string,
125 iconDirectories: ReadonlyArray<string>,
126) {
127 const path = yield* Path.Path;
128 if (path.isAbsolute(icon)) {
129 const extension = path.extname(icon).toLowerCase();
130 return (ICON_EXTENSIONS as ReadonlyArray<string>).includes(extension)
131 ? yield* existingFile(icon)
132 : null;
133 }
134 if (icon.includes("/") || icon.includes("\\") || icon.includes("..")) return null;
135 const baseName = path.extname(icon) ? icon.slice(0, -path.extname(icon).length) : icon;
136 for (const directory of iconDirectories) {
137 const candidates = directory.endsWith("hicolor")
138 ? [
139 ...PREFERRED_SIZES.flatMap((size) =>
140 ICON_EXTENSIONS.map((extension) =>
141 path.join(directory, `${size}x${size}`, "apps", `${baseName}${extension}`),
142 ),
143 ),
144 path.join(directory, "scalable", "apps", `${baseName}.svg`),
145 ]
146 : ICON_EXTENSIONS.map((extension) => path.join(directory, `${baseName}${extension}`));
147 for (const candidate of candidates) {
148 const found = yield* existingFile(candidate);
149 if (found) return found;
150 }
151 }
152 return null;
153});
154
155const resolveIcon = Effect.fn("NativeAppIconResolver.linux.resolve")(function* (
156 app: NativeAppIconReference,
157) {
158 if (app._tag === "app-path") return null;
159 const directories = yield* applicationDirectories();
160 const entries = yield* readDesktopEntries(directories.applications);
161 let best: { readonly entry: DesktopEntry; readonly rank: number } | undefined;
162 for (const entry of entries) {
163 const rank = rankDesktopEntry(entry, app);
164 if (rank > 0 && (!best || rank > best.rank)) best = { entry, rank };
165 }
166 if (!best) return null;
167 return yield* resolveIconFile(best.entry.icon, directories.icons);
168});
169
170/**
171 * Cua reports a Linux app by its X11 window class, with no bundle id. The
172 * launcher database is the only place that maps a class back to an icon, so
173 * `.desktop` entries are matched by class, name, or file name and their
174 * `Icon=` resolved through the hicolor theme. PNG and SVG both serve as-is.
175 */
176export const linuxSource: NativeAppIconSource = {
177 platform: "linux",
178 resolve: resolveIcon,
179};