Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopLinuxUrlHandler.ts

342 lines12.6 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Schema from "effect/Schema";
7import * as ChildProcess from "effect/process/ChildProcess";
8import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
9​
10import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
11import * as DesktopAssets from "./DesktopAssets.ts";
12import * as DesktopEnvironment from "./DesktopEnvironment.ts";
13import { makeComponentLogger } from "./DesktopObservability.ts";
14​
15// AppImage integrators choose the .desktop filename, so setDesktopName cannot identify it for protocol registration.
16const { logInfo, logWarning } = makeComponentLogger("desktop-linux-url-handler");
17​
18export class DesktopLinuxUrlHandlerRegistrationError extends Schema.TaggedError<DesktopLinuxUrlHandlerRegistrationError>()(
19 "DesktopLinuxUrlHandlerRegistrationError",
20 {
21 step: Schema.Literals(["write-desktop-entry", "set-default-handler"]),
22 scheme: Schema.String,
23 desktopEntryPath: Schema.optionalKey(Schema.String),
24 exitCode: Schema.optionalKey(Schema.Number),
25 cause: Schema.optionalKey(Schema.Defect()),
26 },
27) {
28 override get message(): string {
29 const exitCode = this.exitCode === undefined ? "" : `, xdg-mime exit code ${this.exitCode}`;
30 return `Failed to register the ${this.scheme}:// URL handler (step: ${this.step}${exitCode}).`;
31 }
33​
34const isRegistrationError = Schema.is(DesktopLinuxUrlHandlerRegistrationError);
35​
36export class DesktopLinuxUrlHandlerCacheRefreshError extends Schema.TaggedError<DesktopLinuxUrlHandlerCacheRefreshError>()(
37 "DesktopLinuxUrlHandlerCacheRefreshError",
38 {
39 applicationsDir: Schema.String,
40 exitCode: Schema.optionalKey(Schema.Number),
41 cause: Schema.optionalKey(Schema.Defect()),
42 },
43) {
44 override get message(): string {
45 const exitCode =
46 this.exitCode === undefined ? "" : `, update-desktop-database exit code ${this.exitCode}`;
47 return `Failed to refresh the desktop MIME cache at ${this.applicationsDir}${exitCode}.`;
48 }
50​
51const isCacheRefreshError = Schema.is(DesktopLinuxUrlHandlerCacheRefreshError);
52​
53const escapeDesktopEntryString = (value: string): string =>
54 value
55 .replaceAll("\\", "\\\\")
56 .replaceAll("\n", "\\n")
57 .replaceAll("\r", "\\r")
58 .replaceAll("\t", "\\t");
59​
60// Exec values undergo general unescaping then Exec unquoting; escape in reverse order.
61export function escapeDesktopEntryExecArgument(value: string): string {
62 const quoted = value
63 .replaceAll("\\", () => "\\\\")
64 .replaceAll("`", () => "\\`")
65 .replaceAll("$", () => "\\$")
66 .replaceAll('"', () => '\\"')
67 .replaceAll("%", () => "%%");
68 return escapeDesktopEntryString(`"${quoted}"`);
70​
71// Legacy xdg-open looks up the first Exec word without unquoting it.
72const escapeUrlHandlerExecTarget = (value: string): string =>
73 /[ \t\n"'\\><~|&;$*?#()`]/.test(value)
74 ? escapeDesktopEntryExecArgument(value)
75 : escapeDesktopEntryString(value.replaceAll("%", "%%"));
76​
77// The AppImage integration entry owns the window identity. This
78// hidden URL-only entry must not compete with it for StartupWMClass matching.
79export function renderUrlHandlerDesktopEntry(input: {
80 readonly displayName: string;
81 readonly execTarget: string;
82 readonly scheme: string;
83 readonly iconPath?: string;
84}): string {
85 return [
86 "[Desktop Entry]",
87 "Type=Application",
88 `Name=${escapeDesktopEntryString(input.displayName)}`,
89 `Exec=${escapeUrlHandlerExecTarget(input.execTarget)} %U`,
90 ...(input.iconPath === undefined ? [] : [`Icon=${escapeDesktopEntryString(input.iconPath)}`]),
91 "Terminal=false",
92 "NoDisplay=true",
93 "StartupNotify=false",
94 `MimeType=x-scheme-handler/${input.scheme};`,
95 "",
96 ].join("\n");
98​
99// Docks may look up the Wayland app id without a desktop entry; icon theme lookups are case-sensitive.
100const LINUX_THEME_ICON_SIZE = "256x256";
101​
102function linuxThemeIconNames(desktopEntryName: string): readonly string[] {
103 const appId = desktopEntryName.replace(/\.desktop$/u, "");
104 return [...new Set([appId.toLowerCase(), appId])];
106​
107const sameBytes = (left: Uint8Array, right: Uint8Array): boolean =>
108 left.length === right.length && left.every((byte, index) => byte === right[index]);
109​
110export class DesktopLinuxUrlHandler extends Context.Service<
111 DesktopLinuxUrlHandler,
112 {
113 readonly register: Effect.Effect<void>;
114 }
115>()("@t3tools/desktop/app/DesktopLinuxUrlHandler") {}
116​
117/** @public */
118export const make = Effect.gen(function* () {
119 const environment = yield* DesktopEnvironment.DesktopEnvironment;
120 const fileSystem = yield* FileSystem.FileSystem;
121 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
122 const assets = yield* DesktopAssets.DesktopAssets;
123​
124 const scheme = ElectronProtocol.getDesktopScheme(environment.isDevelopment);
125 const desktopEntryPath = environment.path.join(
126 environment.linuxApplicationsDir,
127 environment.linuxDesktopEntryName,
128 );
129 const iconsDir = environment.path.join(environment.linuxApplicationsDir, "..", "icons");
130 const iconPath = environment.path.join(iconsDir, `${environment.linuxDesktopEntryName}.png`);
131 const hicolorDir = environment.path.join(iconsDir, "hicolor");
132 const themeIconDir = environment.path.join(hicolorDir, LINUX_THEME_ICON_SIZE, "apps");
133​
134 const writeDesktopEntry = Effect.gen(function* () {
135 // Distribution packages that run on a shared Electron set
136 // T3CODE_DESKTOP_LAUNCHER_PATH, because process.execPath is that Electron.
137 // Inside the mounted AppImage, process.execPath points at a transient
138 // /tmp/.mount_* path — the handler must launch the AppImage itself.
139 const execTarget = environment.desktopLauncherPath.pipe(
140 Option.orElse(() => environment.appImagePath),
141 Option.getOrElse(() => process.execPath),
142 );
143 const content = renderUrlHandlerDesktopEntry({
144 displayName: environment.displayName,
145 execTarget,
146 scheme,
147 ...(environment.isPackaged ? { iconPath } : {}),
148 });
149 // Avoid truncating the pre-ready entry while the portal may be reading it.
150 const existing = yield* fileSystem
151 .readFileString(desktopEntryPath)
152 .pipe(Effect.orElseSucceed(() => null));
153 if (existing === content) return;
154 yield* fileSystem.makeDirectory(environment.linuxApplicationsDir, { recursive: true });
155 yield* fileSystem.writeFileString(desktopEntryPath, content);
156 }).pipe(
157 Effect.mapError(
158 (cause) =>
159 new DesktopLinuxUrlHandlerRegistrationError({
160 step: "write-desktop-entry",
161 scheme,
162 desktopEntryPath,
163 cause,
164 }),
165 ),
166 );
167​
168 const updateDesktopDatabase = Effect.scoped(
169 Effect.gen(function* () {
170 const command = ChildProcess.make(
171 "update-desktop-database",
172 [environment.linuxApplicationsDir],
173 {
174 stdin: "ignore",
175 stdout: "ignore",
176 stderr: "ignore",
177 forceKillAfter: "1 second",
178 },
179 );
180 const handle = yield* spawner.spawn(command);
181 const exitCode = yield* handle.exitCode.pipe(Effect.timeout("5 seconds"));
182 if (exitCode !== 0) {
183 return yield* new DesktopLinuxUrlHandlerCacheRefreshError({
184 applicationsDir: environment.linuxApplicationsDir,
185 exitCode,
186 });
187 }
188 }),
189 ).pipe(
190 Effect.mapError((error) =>
191 isCacheRefreshError(error)
192 ? error
193 : new DesktopLinuxUrlHandlerCacheRefreshError({
194 applicationsDir: environment.linuxApplicationsDir,
195 cause: error,
196 }),
197 ),
198 );
199​
200 const refreshIconThemeCache = Effect.scoped(
201 Effect.gen(function* () {
202 const command = ChildProcess.make("gtk-update-icon-cache", ["-f", "-t", hicolorDir], {
203 stdin: "ignore",
204 stdout: "ignore",
205 stderr: "ignore",
206 // Releasing a timed-out helper otherwise waits on SIGTERM indefinitely.
207 forceKillAfter: "1 second",
208 });
209 const handle = yield* spawner.spawn(command);
210 return yield* handle.exitCode.pipe(Effect.timeout("5 seconds"));
211 }),
212 );
213​
214 const modifiedAt = (filePath: string) =>
215 fileSystem
216 .stat(filePath)
217 .pipe(Effect.map((info) => Option.getOrUndefined(info.mtime)?.getTime() ?? 0));
218​
219 const installThemeIcons = Effect.gen(function* () {
220 const source = yield* assets.resolveResourcePath(`icons/${LINUX_THEME_ICON_SIZE}.png`);
221 if (Option.isNone(source)) return;
222 const icon = yield* fileSystem.readFile(source.value);
223 const targets = linuxThemeIconNames(environment.linuxDesktopEntryName).map((name) =>
224 environment.path.join(themeIconDir, `${name}.png`),
225 );
226 let changed = false;
227 for (const target of targets) {
228 const current = yield* fileSystem.readFile(target).pipe(Effect.option);
229 if (Option.isSome(current) && sameBytes(current.value, icon)) continue;
230 yield* fileSystem.makeDirectory(themeIconDir, { recursive: true });
231 yield* fileSystem.writeFile(target, icon);
232 changed = true;
233 }
234 // Creating a cache would leave GTK reading stale icons from other installers.
235 // A newer icon retries a refresh that failed on an earlier launch.
236 const cachePath = environment.path.join(hicolorDir, "icon-theme.cache");
237 const cachedAt = yield* modifiedAt(cachePath).pipe(Effect.option);
238 if (Option.isNone(cachedAt)) return;
239 let stale = changed;
240 for (const target of targets) {
241 if (stale) break;
242 if ((yield* modifiedAt(target)) > cachedAt.value) stale = true;
243 }
244 if (!stale) return;
245 const exitCode = yield* refreshIconThemeCache;
246 if (exitCode !== 0) {
247 yield* logWarning("icon theme cache refresh failed", { hicolorDir, exitCode });
248 }
249 }).pipe(
250 Effect.catch((error) =>
251 logWarning("app id theme icon install failed", { themeIconDir, category: error._tag }),
252 ),
253 );
254​
255 const setDefaultHandler = Effect.scoped(
256 Effect.gen(function* () {
257 const command = ChildProcess.make(
258 "xdg-mime",
259 ["default", environment.linuxDesktopEntryName, `x-scheme-handler/${scheme}`],
260 {
261 stdin: "ignore",
262 stdout: "ignore",
263 stderr: "ignore",
264 forceKillAfter: "1 second",
265 },
266 );
267 const handle = yield* spawner.spawn(command);
268 const exitCode = yield* handle.exitCode.pipe(Effect.timeout("5 seconds"));
269 if (exitCode !== 0) {
270 return yield* new DesktopLinuxUrlHandlerRegistrationError({
271 step: "set-default-handler",
272 scheme,
273 exitCode,
274 });
275 }
276 }),
277 ).pipe(
278 Effect.mapError((error) =>
279 isRegistrationError(error)
280 ? error
281 : new DesktopLinuxUrlHandlerRegistrationError({
282 step: "set-default-handler",
283 scheme,
284 cause: error,
285 }),
286 ),
287 );
288​
289 const register = Effect.gen(function* () {
290 if (environment.platform !== "linux") {
291 return;
292 }
293 yield* writeDesktopEntry;
294 if (!environment.isPackaged) return;
295​
296 yield* Effect.gen(function* () {
297 const { png } = yield* assets.iconPaths;
298 if (Option.isNone(png)) return;
299 // The AppImage mount is temporary; the chooser needs the icon after exit.
300 yield* fileSystem.makeDirectory(iconsDir, { recursive: true });
301 // Electron's copyFile from app.asar extracts to a temp file it never deletes.
302 yield* fileSystem.writeFile(iconPath, yield* fileSystem.readFile(png.value));
303 }).pipe(
304 Effect.catch((error) =>
305 logWarning("URL handler icon install failed", { iconPath, category: error.reason._tag }),
306 ),
307 );
308​
309 yield* installThemeIcons;
310​
311 yield* updateDesktopDatabase.pipe(
312 // GIO verifies scheme associations through mimeinfo.cache. A missing cache updater must not block xdg-mime.
313 Effect.catch((error) =>
314 logWarning("desktop MIME cache refresh failed", {
315 applicationsDir: environment.linuxApplicationsDir,
316 message: error.message,
317 ...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
318 }),
319 ),
320 );
321​
322 yield* setDefaultHandler;
323 yield* logInfo("registered URL scheme handler", { scheme });
324 }).pipe(
325 Effect.catch((error) =>
326 logWarning("URL scheme handler registration failed", {
327 scheme,
328 step: error.step,
329 message: error.message,
330 ...(error.desktopEntryPath === undefined
331 ? {}
332 : { desktopEntryPath: error.desktopEntryPath }),
333 ...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
334 }),
335 ),
336 Effect.withSpan("desktop.linuxUrlHandler.register"),
337 );
338​
339 return DesktopLinuxUrlHandler.of({ register });
340});
341​
342export const layer = Layer.effect(DesktopLinuxUrlHandler, make);