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