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

DesktopLinuxUrlHandler.test.ts

767 lines29.7 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as Cause from "effect/Cause";
5import * as Deferred from "effect/Deferred";
6import * as Effect from "effect/Effect";
7import * as Exit from "effect/Exit";
8import * as Fiber from "effect/Fiber";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
13import * as PlatformError from "effect/PlatformError";
14import * as Sink from "effect/Sink";
15import * as Stream from "effect/Stream";
16import * as TestClock from "effect/testing/TestClock";
17import * as ChildProcess from "effect/process/ChildProcess";
18import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
19​
20import * as DesktopEnvironment from "./DesktopEnvironment.ts";
21import * as DesktopAssets from "./DesktopAssets.ts";
22import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
23​
24interface RecordedRegistration {
25 readonly directories: string[];
26 readonly files: Array<{ readonly path: string; readonly content: string }>;
27 readonly commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>;
28 readonly copies: Array<{ readonly source: string; readonly destination: string }>;
29 readonly icons: Array<{ readonly path: string; readonly bytes: ReadonlyArray<number> }>;
30 readonly renames: Array<{ readonly from: string; readonly to: string }>;
32​
33const ICON_BYTES = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
34const HANDLER_PATH = "/home/alice/.local/share/com.t3tools.T3Code/open-url";
35const CURRENT_HANDLER = DesktopLinuxUrlHandler.renderAppImageUrlHandler({
36 appImagePath: "/home/alice/Applications/T3-Code.AppImage",
37 executablePath: process.execPath,
38 pid: process.pid,
39});
40​
41const makeEnvironment = (path: Path.Path, overrides: Record<string, unknown> = {}) =>
42 DesktopEnvironment.DesktopEnvironment.of({
43 platform: "linux",
44 isPackaged: true,
45 isDevelopment: false,
46 displayName: "T3 Code (Alpha)",
47 linuxDesktopEntryName: "com.t3tools.T3Code.desktop",
48 linuxApplicationsDir: "/home/alice/.local/share/applications",
49 desktopLauncherPath: Option.none(),
50 appImagePath: Option.some("/home/alice/Applications/T3-Code.AppImage"),
51 path,
52 ...overrides,
53 } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
54​
55const mockProcess = (exitCode: number, stalled = false) =>
56 ChildProcessSpawner.makeHandle({
57 pid: ChildProcessSpawner.ProcessId(1),
58 exitCode: stalled ? Effect.never : Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
59 exitStatus: stalled
60 ? Effect.never
61 : Effect.succeed({ _tag: "Exited", code: ChildProcessSpawner.ExitCode(exitCode) }),
62 isRunning: Effect.succeed(false),
63 kill: () => Effect.void,
64 unref: Effect.succeed(Effect.void),
65 stdin: Sink.drain,
66 stdout: Stream.empty,
67 stderr: Stream.empty,
68 all: Stream.empty,
69 getInputFd: () => Sink.drain,
70 getOutputFd: () => Stream.empty,
71 });
72​
73const layerHandler = (
74 recorded: RecordedRegistration,
75 input: {
76 readonly environment?: Record<string, unknown>;
77 readonly processSpawner?: ChildProcessSpawner.ChildProcessSpawner["Service"];
78 readonly updateDesktopDatabaseExitCode?: number;
79 readonly updateDesktopDatabaseStalled?: boolean;
80 readonly updateDesktopDatabaseStarted?: Deferred.Deferred<void>;
81 readonly xdgMimeExitCode?: number;
82 readonly writeError?: PlatformError.PlatformError;
83 readonly existingEntry?: string;
84 readonly existingHandler?: string;
85 readonly iconSource?: string;
86 readonly iconWriteError?: PlatformError.PlatformError;
87 } = {},
88) =>
89 DesktopLinuxUrlHandler.layer.pipe(
90 Layer.provide(
91 Layer.mergeAll(
92 Layer.effect(
93 DesktopEnvironment.DesktopEnvironment,
94 Path.Path.pipe(
95 Effect.map((path) => makeEnvironment(path, input.environment)),
96 Effect.provide(Path.layer),
97 ),
98 ),
99 Layer.succeed(DesktopAssets.DesktopAssets, {
100 iconPaths: Effect.succeed({
101 png: Option.fromUndefinedOr(input.iconSource),
102 ico: Option.none(),
103 icns: Option.none(),
104 }),
105 resolveResourcePath: () => Effect.succeedNone,
106 }),
107 FileSystem.layerNoop({
108 copyFile: (source, destination) =>
109 Effect.sync(() => {
110 recorded.copies.push({ source, destination });
111 }),
112 readFile: (path) =>
113 path === input.iconSource
114 ? Effect.succeed(ICON_BYTES)
115 : Effect.fail(
116 PlatformError.systemError({
117 _tag: "NotFound",
118 module: "FileSystem",
119 method: "readFile",
120 pathOrDescriptor: path,
121 }),
122 ),
123 writeFile: (path, bytes) =>
124 input.iconWriteError
125 ? Effect.fail(input.iconWriteError)
126 : Effect.sync(() => {
127 recorded.icons.push({ path, bytes: [...bytes] });
128 }),
129 readFileString: (path) =>
130 Effect.succeed(
131 path === HANDLER_PATH
132 ? (input.existingHandler ?? CURRENT_HANDLER)
133 : (input.existingEntry ?? ""),
134 ),
135 rename: (from, to) =>
136 Effect.sync(() => {
137 recorded.renames.push({ from, to });
138 }),
139 makeDirectory: (path) =>
140 Effect.sync(() => {
141 recorded.directories.push(path);
142 }),
143 writeFileString: (path, content) =>
144 input.writeError
145 ? Effect.fail(input.writeError)
146 : Effect.sync(() => {
147 recorded.files.push({ path, content });
148 }),
149 }),
150 Layer.succeed(
151 ChildProcessSpawner.ChildProcessSpawner,
152 ChildProcessSpawner.make((command) => {
153 if (input.processSpawner) return input.processSpawner.spawn(command);
154 const childProcess = command as unknown as {
155 readonly command: string;
156 readonly args: ReadonlyArray<string>;
157 };
158 if (childProcess.command === "update-desktop-database") {
159 assert.isTrue(
160 recorded.files.length > 0 || input.existingEntry !== undefined,
161 "the desktop entry must exist before refreshing the MIME cache",
162 );
163 }
164 recorded.commands.push({
165 command: childProcess.command,
166 args: childProcess.args,
167 });
168 const exitCode =
169 childProcess.command === "update-desktop-database"
170 ? (input.updateDesktopDatabaseExitCode ?? 0)
171 : (input.xdgMimeExitCode ?? 0);
172 const handle = mockProcess(
173 exitCode,
174 childProcess.command === "update-desktop-database" &&
175 input.updateDesktopDatabaseStalled === true,
176 );
177 return childProcess.command === "update-desktop-database" &&
178 input.updateDesktopDatabaseStarted
179 ? Deferred.succeed(input.updateDesktopDatabaseStarted, undefined).pipe(
180 Effect.as(handle),
181 )
182 : Effect.succeed(handle);
183 }),
184 ),
185 ),
186 ),
187 );
188​
189const runRegister = (
190 recorded: RecordedRegistration,
191 input: Parameters<typeof layerHandler>[1] = {},
192) =>
193 Effect.gen(function* () {
194 const handler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
195 yield* handler.register;
196 }).pipe(Effect.provide(layerHandler(recorded, input)));
197​
198const emptyRecording = (): RecordedRegistration => ({
199 directories: [],
200 files: [],
201 commands: [],
202 copies: [],
203 icons: [],
204 renames: [],
205});
206​
207describe("DesktopLinuxUrlHandler", () => {
208 it("renders a scheme-handler desktop entry with freedesktop Exec quoting", () => {
209 const entry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
210 displayName: "T3 Code (Nightly)",
211 execTarget: '/home/al ice/Apps/T3 "100%" $HOME\\x.AppImage',
212 scheme: "t3code",
213 iconPath: "/home/al ice/icons/T3\\x.png",
214 });
215​
216 assert.include(entry, "[Desktop Entry]");
217 assert.include(entry, "Name=T3 Code (Nightly)");
218 assert.include(
219 entry,
220 'Exec="/home/al ice/Apps/T3 \\\\"100%%\\\\" \\\\$HOME\\\\\\\\x.AppImage" %U',
221 );
222 assert.include(entry, "NoDisplay=true");
223 assert.notInclude(entry, "StartupWMClass=");
224 assert.include(entry, "MimeType=x-scheme-handler/t3code;");
225 assert.include(entry, "Icon=/home/al ice/icons/T3\\\\x.png");
226 });
227​
228 it.each([
229 { from: "T3-Code-0.1.8-x86_64.AppImage", to: "T3-Code-x86_64.AppImage", restored: true },
230 {
231 from: "T3-Code-0.1.9-nightly.20261110.4449-arm64.AppImage",
232 to: "T3-Code-Nightly-arm64.AppImage",
233 restored: true,
234 },
235 { from: "T3-Code-0.1.8-x86_64.AppImage", to: "T3-Code-0.1.9-x86_64.AppImage", restored: false },
236 { from: "t3code.AppImage", to: "T3-Code-x86_64.AppImage", restored: false },
237 { from: "T3-Code-x86_64.AppImage", to: "T3-Code-x86_64.AppImage", restored: false },
238 { from: "../T3-Code-0.1.8-x86_64.AppImage", to: "T3-Code-x86_64.AppImage", restored: false },
239 ])("finds the launch path an update from $from to $to removed", ({ from, to, restored }) => {
240 for (const dir of ["/home/alice/Applications", '/home/al ice/My "100%" $Apps\\x']) {
241 const previous = dir + "/" + from;
242 const previousEntry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
243 displayName: "T3 Code (Beta)",
244 execTarget: previous,
245 scheme: "t3code",
246 });
247 assert.equal(
248 DesktopLinuxUrlHandler.replacedVersionedAppImagePath({
249 previousEntry,
250 appImagePath: dir + "/" + to,
251 }),
252 restored ? previous : null,
253 );
254 }
255 });
256​
257 it.effect(
258 "writes the handler entry, refreshes the MIME cache, and claims the scheme default",
259 () => {
260 const recorded = emptyRecording();
261​
262 return Effect.gen(function* () {
263 yield* runRegister(recorded);
264​
265 assert.deepEqual(recorded.directories, ["/home/alice/.local/share/applications"]);
266 assert.equal(recorded.files.length, 1);
267 assert.equal(
268 recorded.files[0]?.path,
269 "/home/alice/.local/share/applications/com.t3tools.T3Code.desktop",
270 );
271 assert.include(recorded.files[0]?.content, `Exec=${HANDLER_PATH} %U`);
272 assert.include(recorded.files[0]?.content, "MimeType=x-scheme-handler/t3code;");
273 assert.deepEqual(recorded.commands, [
274 {
275 command: "update-desktop-database",
276 args: ["/home/alice/.local/share/applications"],
277 },
278 {
279 command: "xdg-mime",
280 args: ["default", "com.t3tools.T3Code.desktop", "x-scheme-handler/t3code"],
281 },
282 ]);
283 });
284 },
285 );
286​
287 it.effect("routes AppImage links through a handler that reuses the running mount", () => {
288 const recorded = emptyRecording();
289​
290 return Effect.gen(function* () {
291 yield* runRegister(recorded, { existingHandler: "" });
292​
293 assert.equal(recorded.files[0]?.content, CURRENT_HANDLER);
294 assert.deepEqual(recorded.renames, [{ from: recorded.files[0]?.path, to: HANDLER_PATH }]);
295 assert.include(recorded.files[1]?.content, `Exec=${HANDLER_PATH} %U`);
296 });
297 });
298​
299 it.effect("falls back to the process executable outside an AppImage", () => {
300 const recorded = emptyRecording();
301​
302 return Effect.gen(function* () {
303 yield* runRegister(recorded, { environment: { appImagePath: Option.none() } });
304​
305 assert.include(
306 recorded.files[0]?.content,
307 DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
308 displayName: "T3 Code (Alpha)",
309 execTarget: process.execPath,
310 scheme: "t3code",
311 iconPath: "/home/alice/.local/share/icons/com.t3tools.T3Code.desktop.png",
312 }),
313 );
314 });
315 });
316​
317 it.effect("launches a distribution package through its configured launcher", () => {
318 const recorded = emptyRecording();
319​
320 return Effect.gen(function* () {
321 yield* runRegister(recorded, {
322 environment: { desktopLauncherPath: Option.some("/opt/T3 Code/t3code") },
323 });
324​
325 assert.include(recorded.files[0]?.content, 'Exec="/opt/T3 Code/t3code" %U');
326 });
327 });
328​
329 it.effect("does not rewrite the pre-ready entry while the portal can be reading it", () => {
330 const recorded = emptyRecording();
331​
332 return Effect.gen(function* () {
333 yield* runRegister(recorded, {
334 existingEntry: DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
335 displayName: "T3 Code (Alpha)",
336 execTarget: HANDLER_PATH,
337 scheme: "t3code",
338 iconPath: "/home/alice/.local/share/icons/com.t3tools.T3Code.desktop.png",
339 }),
340 });
341​
342 assert.deepEqual(recorded.files, []);
343 assert.deepEqual(recorded.directories, []);
344 assert.deepEqual(recorded.commands, [
345 {
346 command: "update-desktop-database",
347 args: ["/home/alice/.local/share/applications"],
348 },
349 {
350 command: "xdg-mime",
351 args: ["default", "com.t3tools.T3Code.desktop", "x-scheme-handler/t3code"],
352 },
353 ]);
354 });
355 });
356​
357 it.effect("installs a persistent icon even when the desktop entry is already current", () => {
358 const recorded = emptyRecording();
359 const iconPath = "/home/alice/.local/share/icons/com.t3tools.T3Code.desktop.png";
360 return Effect.gen(function* () {
361 yield* runRegister(recorded, {
362 iconSource: "/tmp/.mount_T3/resources/icon.png",
363 existingEntry: DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
364 displayName: "T3 Code (Alpha)",
365 execTarget: HANDLER_PATH,
366 scheme: "t3code",
367 iconPath,
368 }),
369 });
370 assert.deepEqual(recorded.files, []);
371 assert.deepEqual(recorded.copies, [], "icon must not be copied out of the app bundle");
372 assert.deepEqual(recorded.icons, [{ path: iconPath, bytes: [...ICON_BYTES] }]);
373 assert.equal(recorded.commands.at(-1)?.command, "xdg-mime");
374 });
375 });
376​
377 it.effect("still registers the handler when installing its icon fails", () => {
378 const recorded = emptyRecording();
379 return Effect.gen(function* () {
380 yield* runRegister(recorded, {
381 iconSource: "/tmp/.mount_T3/resources/icon.png",
382 iconWriteError: PlatformError.systemError({
383 _tag: "PermissionDenied",
384 module: "FileSystem",
385 method: "writeFile",
386 description: "read-only icon directory",
387 }),
388 });
389 assert.equal(recorded.files.length, 1);
390 assert.deepEqual(
391 recorded.commands.map(({ command }) => command),
392 ["update-desktop-database", "xdg-mime"],
393 );
394 });
395 });
396​
397 it.effect("writes the portal identity without claiming the URL scheme in development", () => {
398 const nonLinux = emptyRecording();
399 const unpackaged = emptyRecording();
400​
401 return Effect.gen(function* () {
402 yield* runRegister(nonLinux, { environment: { platform: "darwin" } });
403 yield* runRegister(unpackaged, {
404 environment: {
405 isPackaged: false,
406 linuxDesktopEntryName: "com.t3tools.T3Code.Development.desktop",
407 appImagePath: Option.none(),
408 },
409 });
410​
411 assert.deepEqual(nonLinux.files, []);
412 assert.equal(
413 unpackaged.files[0]?.path,
414 "/home/alice/.local/share/applications/com.t3tools.T3Code.Development.desktop",
415 );
416 assert.deepEqual(unpackaged.commands, []);
417 });
418 });
419​
420 it.effect("never fails startup when registration cannot complete", () => {
421 const desktopDatabaseFailed = emptyRecording();
422 const xdgMimeFailed = emptyRecording();
423 const writeFailed = emptyRecording();
424​
425 return Effect.gen(function* () {
426 yield* runRegister(desktopDatabaseFailed, { updateDesktopDatabaseExitCode: 1 });
427 yield* runRegister(xdgMimeFailed, { xdgMimeExitCode: 1 });
428 yield* runRegister(writeFailed, {
429 writeError: PlatformError.systemError({
430 _tag: "PermissionDenied",
431 module: "FileSystem",
432 method: "writeFileString",
433 description: "read-only filesystem",
434 pathOrDescriptor: "/home/alice/.local/share/applications/com.t3tools.T3Code.desktop",
435 }),
436 });
437​
438 assert.deepEqual(
439 desktopDatabaseFailed.commands.map(({ command }) => command),
440 ["update-desktop-database", "xdg-mime"],
441 );
442 assert.equal(xdgMimeFailed.files.length, 1);
443 assert.deepEqual(writeFailed.commands, []);
444 });
445 });
446​
447 for (const stalledHelper of ["update-desktop-database", "xdg-mime"] as const) {
448 it.effect.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
449 `finishes registration after a timed-out ${stalledHelper} ignores SIGTERM`,
450 () =>
451 Effect.gen(function* () {
452 const realSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
453 const nodeExecutable = yield* HostProcess.ExecutablePath;
454 const recorded = emptyRecording();
455 const spawned = yield* Deferred.make<ChildProcessSpawner.ChildProcessHandle>();
456 const ready = yield* Deferred.make<void>();
457 const processSpawner = ChildProcessSpawner.make((command) =>
458 Effect.gen(function* () {
459 if (!ChildProcess.isStandardCommand(command)) {
460 return yield* Effect.die("expected a single registration command");
461 }
462 recorded.commands.push({ command: command.command, args: command.args.map(String) });
463 if (command.command !== stalledHelper) return mockProcess(0);
464 const child = yield* realSpawner.spawn(
465 ChildProcess.make(
466 nodeExecutable,
467 [
468 "-e",
469 // The watchdog makes the unfixed case exit with a distinguishable code.
470 "process.on('SIGTERM', () => setTimeout(() => process.exit(99), 5000));" +
471 "process.stdout.write('ready\\n'); setInterval(() => {}, 2147483647);",
472 ],
473 { ...command.options, stdout: "pipe" },
474 ),
475 );
476 yield* Deferred.succeed(spawned, child);
477 yield* Stream.runHead(child.stdout);
478 yield* Deferred.succeed(ready, undefined);
479 return child;
480 }),
481 );
482 const registration = yield* runRegister(recorded, { processSpawner }).pipe(
483 Effect.forkScoped,
484 );
485 const child = yield* Deferred.await(spawned);
486 yield* Effect.addFinalizer(() =>
487 child.isRunning.pipe(
488 Effect.flatMap((running) =>
489 running ? child.kill({ killSignal: "SIGKILL" }) : Effect.void,
490 ),
491 Effect.ignore,
492 ),
493 );
494 yield* Deferred.await(ready);
495 yield* TestClock.adjust("5 seconds");
496 yield* Fiber.join(registration);
497​
498 const exit = yield* Effect.exit(child.exitCode);
499 if (Exit.isFailure(exit)) {
500 assert.include(Cause.pretty(exit.cause), "SIGKILL");
501 } else {
502 assert.fail(`${stalledHelper} exited with ${exit.value} instead of being force-killed`);
503 }
504 assert.deepEqual(
505 recorded.commands.map(({ command }) => command),
506 ["update-desktop-database", "xdg-mime"],
507 );
508 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
509 );
510 }
511});
512​
513interface ThemeIconRun {
514 readonly root: string;
515 readonly commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>;
516 readonly iconCacheOptions?: Array<Record<string, unknown>>;
517 readonly sourceMissing?: boolean;
518 readonly iconCacheExitCode?: number;
519 readonly iconCacheSpawnFails?: boolean;
520 readonly iconCacheStalled?: boolean;
521 readonly iconCacheStarted?: Deferred.Deferred<void>;
522 // Stands in for gtk-update-icon-cache rewriting the cache on success.
523 readonly onIconCacheRefresh?: Effect.Effect<void>;
525​
526const registerWithRealFileSystem = (run: ThemeIconRun) =>
527 Effect.gen(function* () {
528 const handler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
529 yield* handler.register;
530 }).pipe(
531 Effect.provide(
532 DesktopLinuxUrlHandler.layer.pipe(
533 Layer.provide(
534 Layer.mergeAll(
535 Layer.effect(
536 DesktopEnvironment.DesktopEnvironment,
537 Path.Path.pipe(
538 Effect.map((path) =>
539 makeEnvironment(path, {
540 linuxApplicationsDir: path.join(run.root, "applications"),
541 }),
542 ),
543 ),
544 ),
545 Layer.effect(
546 DesktopAssets.DesktopAssets,
547 Path.Path.pipe(
548 Effect.map((path) => ({
549 iconPaths: Effect.succeed({
550 png: Option.none(),
551 ico: Option.none(),
552 icns: Option.none(),
553 }),
554 resolveResourcePath: (fileName: string) =>
555 Effect.succeed(
556 fileName === "icons/256x256.png"
557 ? Option.some(
558 path.join(
559 run.root,
560 run.sourceMissing ? "missing" : "resources",
561 fileName,
562 ),
563 )
564 : Option.none(),
565 ),
566 })),
567 ),
568 ),
569 Layer.succeed(
570 ChildProcessSpawner.ChildProcessSpawner,
571 ChildProcessSpawner.make((command) => {
572 const childProcess = command as unknown as {
573 readonly command: string;
574 readonly args: ReadonlyArray<string>;
575 };
576 run.commands.push({ command: childProcess.command, args: childProcess.args });
577 if (childProcess.command !== "gtk-update-icon-cache") {
578 return Effect.succeed(mockProcess(0));
579 }
580 run.iconCacheOptions?.push(
581 (command as unknown as { readonly options: Record<string, unknown> }).options,
582 );
583 if (run.iconCacheSpawnFails) {
584 return Effect.fail(
585 PlatformError.systemError({
586 _tag: "NotFound",
587 module: "ChildProcess",
588 method: "spawn",
589 description: "gtk-update-icon-cache is not installed",
590 }),
591 );
592 }
593 const exitCode = run.iconCacheExitCode ?? 0;
594 const handle = mockProcess(exitCode, run.iconCacheStalled === true);
595 const refreshed =
596 exitCode === 0 && run.onIconCacheRefresh ? run.onIconCacheRefresh : Effect.void;
597 return refreshed.pipe(
598 Effect.andThen(
599 run.iconCacheStarted
600 ? Deferred.succeed(run.iconCacheStarted, undefined)
601 : Effect.void,
602 ),
603 Effect.as(handle),
604 );
605 }),
606 ),
607 ),
608 ),
609 ),
610 ),
611 );
612​
613const themeIconFixture = (source: Uint8Array) =>
614 Effect.gen(function* () {
615 const fileSystem = yield* FileSystem.FileSystem;
616 const path = yield* Path.Path;
617 const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-theme-icons-" });
618 yield* fileSystem.makeDirectory(path.join(root, "resources", "icons"), { recursive: true });
619 yield* fileSystem.writeFile(path.join(root, "resources", "icons", "256x256.png"), source);
620 const hicolorDir = path.join(root, "icons", "hicolor");
621 const appsDir = path.join(hicolorDir, "256x256", "apps");
622 const cachePath = path.join(hicolorDir, "icon-theme.cache");
623 const pastSeconds = 1_600_000_000;
624 const seedCache = Effect.gen(function* () {
625 yield* fileSystem.makeDirectory(appsDir, { recursive: true });
626 yield* fileSystem.writeFile(cachePath, new Uint8Array([0]));
627 yield* fileSystem.utimes(cachePath, pastSeconds, pastSeconds);
628 });
629 const rewriteCache = fileSystem
630 .writeFile(cachePath, new Uint8Array([1]))
631 .pipe(Effect.orDie, Effect.provideService(FileSystem.FileSystem, fileSystem));
632 return { root, hicolorDir, appsDir, cachePath, pastSeconds, seedCache, rewriteCache };
633 });
634​
635const iconCacheRuns = (run: ThemeIconRun) =>
636 run.commands.filter(({ command }) => command === "gtk-update-icon-cache").length;
637​
638it.layer(NodeServices.layer)("DesktopLinuxUrlHandler theme icons", (it) => {
639 it.effect("installs both app id spellings without creating an icon cache", () =>
640 Effect.gen(function* () {
641 const fileSystem = yield* FileSystem.FileSystem;
642 const path = yield* Path.Path;
643 const icon = new Uint8Array([137, 80, 78, 71, 1, 2, 3]);
644 const fixture = yield* themeIconFixture(icon);
645 const run: ThemeIconRun = { root: fixture.root, commands: [] };
646​
647 yield* registerWithRealFileSystem(run);
648 assert.deepEqual([...(yield* fileSystem.readDirectory(fixture.appsDir))].sort(), [
649 "com.t3tools.T3Code.png",
650 "com.t3tools.t3code.png",
651 ]);
652 for (const name of ["com.t3tools.t3code", "com.t3tools.T3Code"]) {
653 const target = path.join(fixture.appsDir, `${name}.png`);
654 assert.deepEqual([...(yield* fileSystem.readFile(target))], [...icon]);
655 yield* fileSystem.utimes(target, fixture.pastSeconds, fixture.pastSeconds);
656 }
657​
658 yield* registerWithRealFileSystem(run);
659 for (const name of ["com.t3tools.t3code", "com.t3tools.T3Code"]) {
660 const info = yield* fileSystem.stat(path.join(fixture.appsDir, `${name}.png`));
661 assert.equal(Option.getOrThrow(info.mtime).getTime(), fixture.pastSeconds * 1000);
662 }
663 assert.isFalse(yield* fileSystem.exists(fixture.cachePath));
664 assert.equal(iconCacheRuns(run), 0);
665 }),
666 );
667​
668 it.effect("replaces same-length stale icons and refreshes an existing cache once", () =>
669 Effect.gen(function* () {
670 const fileSystem = yield* FileSystem.FileSystem;
671 const path = yield* Path.Path;
672 const fixture = yield* themeIconFixture(new Uint8Array([1, 2, 3]));
673 yield* fixture.seedCache;
674 const lower = path.join(fixture.appsDir, "com.t3tools.t3code.png");
675 const upper = path.join(fixture.appsDir, "com.t3tools.T3Code.png");
676 yield* fileSystem.writeFile(lower, new Uint8Array([3, 2, 1]));
677 yield* fileSystem.writeFile(upper, new Uint8Array([1, 2, 3]));
678 for (const target of [lower, upper]) {
679 yield* fileSystem.utimes(target, fixture.pastSeconds, fixture.pastSeconds);
680 }
681 const run: ThemeIconRun = {
682 root: fixture.root,
683 commands: [],
684 onIconCacheRefresh: fixture.rewriteCache,
685 };
686​
687 yield* registerWithRealFileSystem(run);
688 yield* registerWithRealFileSystem(run);
689​
690 assert.deepEqual([...(yield* fileSystem.readFile(lower))], [1, 2, 3]);
691 const upperInfo = yield* fileSystem.stat(upper);
692 assert.equal(Option.getOrThrow(upperInfo.mtime).getTime(), fixture.pastSeconds * 1000);
693 assert.deepEqual(
694 run.commands.filter(({ command }) => command === "gtk-update-icon-cache"),
695 [{ command: "gtk-update-icon-cache", args: ["-f", "-t", fixture.hicolorDir] }],
696 );
697 }),
698 );
699​
700 it.effect("refreshes when this launch changed an icon even if the cache looks newer", () =>
701 Effect.gen(function* () {
702 const fileSystem = yield* FileSystem.FileSystem;
703 const path = yield* Path.Path;
704 const fixture = yield* themeIconFixture(new Uint8Array([1, 2, 3]));
705 yield* fixture.seedCache;
706 const run: ThemeIconRun = {
707 root: fixture.root,
708 commands: [],
709 onIconCacheRefresh: fixture.rewriteCache,
710 };
711 const future = fixture.pastSeconds + 10 * 365 * 24 * 60 * 60;
712 yield* fileSystem.utimes(fixture.cachePath, future, future);
713​
714 yield* registerWithRealFileSystem(run);
715​
716 assert.isTrue(yield* fileSystem.exists(path.join(fixture.appsDir, "com.t3tools.T3Code.png")));
717 assert.equal(iconCacheRuns(run), 1);
718 }),
719 );
720​
721 it.effect("retries a failed icon cache refresh on the next launch", () =>
722 Effect.gen(function* () {
723 const fixture = yield* themeIconFixture(new Uint8Array([1, 2, 3]));
724 yield* fixture.seedCache;
725 const failing: ThemeIconRun = { root: fixture.root, commands: [], iconCacheExitCode: 1 };
726 yield* registerWithRealFileSystem(failing);
727 assert.equal(iconCacheRuns(failing), 1);
728 assert.deepEqual(failing.commands.map(({ command }) => command).slice(1), [
729 "update-desktop-database",
730 "xdg-mime",
731 ]);
732​
733 const recovering: ThemeIconRun = {
734 root: fixture.root,
735 commands: [],
736 onIconCacheRefresh: fixture.rewriteCache,
737 };
738 yield* registerWithRealFileSystem(recovering);
739 yield* registerWithRealFileSystem(recovering);
740 assert.equal(iconCacheRuns(recovering), 1);
741 }),
742 );
743​
744 it.effect("still registers the handler when the theme icon install fails", () =>
745 Effect.gen(function* () {
746 const fixture = yield* themeIconFixture(new Uint8Array([1, 2, 3]));
747 const missingSource: ThemeIconRun = { root: fixture.root, commands: [], sourceMissing: true };
748 yield* registerWithRealFileSystem(missingSource);
749 assert.deepEqual(
750 missingSource.commands.map(({ command }) => command),
751 ["update-desktop-database", "xdg-mime"],
752 );
753​
754 yield* fixture.seedCache;
755 const missingTool: ThemeIconRun = {
756 root: fixture.root,
757 commands: [],
758 iconCacheSpawnFails: true,
759 };
760 yield* registerWithRealFileSystem(missingTool);
761 assert.deepEqual(
762 missingTool.commands.map(({ command }) => command),
763 ["gtk-update-icon-cache", "update-desktop-database", "xdg-mime"],
764 );
765 }),
766 );
767});