// The Background feature: the engine (ported from the Background Slideshow plugin), the per-image settings, // the sources, the settings section, the launch rule, and the first-start migration. import { test } from "node:test"; import assert from "node:assert/strict"; import { DEFAULT_BACKGROUND, hasBackgroundSource, migrateBackground, normalizeBackground, normalizeLayout, type BackgroundMigrationHost, type BackgroundSettings } from "../../../src/lib/features/backgroundSettings.ts"; import { LAUNCH_RULES, launchWanted, runsInWindow } from "../../../src/lib/features/launch.ts"; import { BLUR_CACHE, RESCAN_SLIDES, Slideshow, transitionMs, type EngineSettings, type ImageSource, type Runtime } from "../../../src/lib/features/background/engine.ts"; import { imageAppearance, imageNames, parseImageSettings, sequence } from "../../../src/lib/features/background/imageSettings.ts"; import { folderSource, imageSource, readSavedImage } from "../../../src/lib/features/background/sources.ts"; import type { LegacyPlugin } from "../../../src/lib/features/migration.ts"; import type { BackgroundFrame } from "../../../src/lib/plugins/backgroundContracts.ts"; const settle = () => new Promise(resolve => setImmediate(resolve)); const on: EngineSettings = { ...normalizeBackground({ source: "folder", seconds: 3, targets: ["app", "pm-all"] }) }; function fixture({ width = 200, height = 100 } = {}) { const frames = new Map(); const released: string[] = []; const reads: string[] = []; const counts = { list: 0, sidecar: 0, blur: 0 }; let names = ["2.png", "1.png", "10.png"]; let sidecar: string | null = null; let serial = 0; let scheduled: { callback: () => void; delay: number } | undefined; const source = (key = "folder:D:\\Pictures"): ImageSource => ({ key, timed: true, list: async () => { counts.list++; return names; }, read: async name => { reads.push(name); return new Blob([name]); }, sidecar: async () => { counts.sidecar++; return sidecar; }, }); const runtime: Runtime = { load: async blob => ({ url: `blob:${await blob.text()}-${serial++}`, width, height }), blur: async image => { counts.blur++; return `${image.url}-blur`; }, release: url => { released.push(url); }, later: (callback, delay) => { scheduled = { callback, delay }; return scheduled; }, cancel: () => { scheduled = undefined; }, random: () => 0, now: () => 0, }; const engine = new Slideshow({ set: (target, frame) => { if (frame) frames.set(target, frame); else frames.delete(target); } }, runtime); return { engine, frames, released, reads, counts, runtime, source, names: (value: string[]) => { names = value; }, sidecar: (value: string | null) => { sidecar = value; }, scheduled: () => scheduled, /** Run the timer, then let the read of the next prepared image finish. */ tick: async () => { await scheduled!.callback(); await settle(); await settle(); }, }; } test("settings and names normalize, and the order is natural", () => { assert.equal(normalizeBackground({ seconds: NaN }).seconds, 60); assert.equal(normalizeBackground({ seconds: -2 }).seconds, 1); assert.equal(normalizeBackground({ seconds: 1e9 }).seconds, 86400); assert.equal(normalizeBackground({ overlay: Infinity }).overlay, 0); assert.equal(normalizeBackground({ overlay: -3 }).overlay, -1); assert.deepEqual(normalizeBackground({ targets: ["app", "app", "bogus", "pm-board:../x", "pm-board:0c18bcdc-f41e-4a31-87f4-87c369f398c1"] }).targets, ["app", "pm-board:0c18bcdc-f41e-4a31-87f4-87c369f398c1"]); assert.deepEqual(normalizeBackground(null), { ...DEFAULT_BACKGROUND, targets: ["app"] }); assert.deepEqual(normalizeBackground({ source: "web", order: "shuffle", paused: "yes", position: "middle", size: "100px" }), { ...DEFAULT_BACKGROUND, targets: ["app"] }); assert.deepEqual(normalizeLayout({ overlay: 0.5, position: "top left", size: "auto" }), { overlay: 0.5, position: "top left", size: "auto" }); assert.deepEqual(imageNames(["10.png", "2.png", "README.md", "../bad.png", "2.png", "a.JPEG"]), ["2.png", "10.png", "a.JPEG"]); assert.deepEqual(sequence(["a", "b", "c"], "b", "name"), ["c", "a", "b"]); assert.notEqual(sequence(["a", "b", "c"], "a", "random", () => 0)[0], "a"); assert.deepEqual(sequence(["a"], "a", "random"), ["a"]); }); test("a folder rotates, shows one frame on every target, and a pause keeps the current image", async () => { const f = fixture(); await f.engine.configure(f.source(), { ...on, overlay: -0.4, position: "top left", size: "contain" }); assert.equal(f.engine.status.image, "1.png"); assert.equal(f.scheduled()!.delay, 3000); assert.equal(f.frames.get("app")!.overlay, -0.4); assert.equal(f.frames.get("app")!.size, "contain"); assert.deepEqual(f.frames.get("app"), f.frames.get("pm-all")); await f.tick(); assert.equal(f.engine.status.image, "2.png"); await f.engine.next(); assert.equal(f.engine.status.image, "10.png"); await f.engine.configure(f.source(), { ...on, paused: true }); assert.equal(f.engine.status.image, "10.png", "A pause keeps the image."); assert.equal(f.scheduled(), undefined, "A pause has no timer."); assert.equal(f.frames.size, 2); await f.engine.next(); assert.equal(f.engine.status.image, "1.png", "Next works during a pause."); assert.equal(f.scheduled(), undefined); await f.engine.configure(null, on); assert.equal(f.frames.size, 0, "Without a source, the frames go away."); f.engine.dispose(); }); test("unreadable images are skipped, and an empty folder tries again", async () => { const f = fixture(); const read = f.source(); const source: ImageSource = { ...read, read: async name => { if (name === "1.png") throw new Error("removed"); return read.read(name); } }; await f.engine.configure(source, on); assert.equal(f.engine.status.image, "2.png"); assert.match(f.engine.status.message, /skipped 1/); f.names([]); f.engine.invalidate(); await f.engine.next(); assert.equal(f.frames.size, 0); assert.equal(f.engine.status.error, true); assert.equal(f.scheduled()!.delay, 5000); f.names(["restored.png"]); f.engine.invalidate(); await f.tick(); assert.equal(f.engine.status.image, "restored.png"); f.engine.dispose(); }); test("both images of a fade stay alive, and each image is released once", async () => { const f = fixture(); await f.engine.configure(f.source(), on); const first = f.frames.get("app")!; assert.equal(first.previous, undefined); await f.engine.next(); await settle(); const second = f.frames.get("app")!; assert.deepEqual(second.previous, first); assert.equal(second.transitionMs, transitionMs); assert.equal(f.released.length, 0); await f.engine.next(); await settle(); const third = f.frames.get("app")!; assert.deepEqual(third.previous, { url: second.url, overlay: 0, position: "center", size: "cover" }); assert.deepEqual(f.released, [first.url]); f.engine.dispose(); await settle(); assert.equal(new Set(f.released).size, f.released.length, "No URL is released twice."); for (const url of [first.url, second.url, third.url]) assert.ok(f.released.includes(url), url); }); test("a settings change keeps the current image and applies the new layout without a fade", async () => { const f = fixture(); await f.engine.configure(f.source(), on); const first = f.frames.get("app")!; await f.engine.configure(f.source(), { ...on, overlay: 0.4, position: "bottom", targets: ["app"] }); const changed = f.frames.get("app")!; assert.equal(changed.url, first.url); assert.equal(changed.overlay, 0.4); assert.equal(changed.position, "bottom"); assert.equal(changed.previous, undefined); assert.equal(f.frames.has("pm-all"), false, "A removed target loses its frame."); assert.equal(f.engine.status.image, "1.png"); assert.deepEqual(f.released, []); f.engine.dispose(); }); test("the next image is read and decoded before its fade", async () => { const f = fixture(); await f.engine.configure(f.source(), on); await settle(); await settle(); assert.deepEqual(f.reads, ["1.png", "2.png"], "The next image loads after the current one shows."); await f.tick(); assert.equal(f.engine.status.image, "2.png"); assert.deepEqual(f.reads, ["1.png", "2.png", "10.png"], "The timer used the prepared image without a new read."); // A change of order drops the prepared image when the folder no longer has it. f.names(["1.png", "2.png"]); f.engine.invalidate(); await f.tick(); assert.equal(f.engine.status.image, "1.png"); assert.ok(f.released.some(url => url.startsWith("blob:10.png")), "The unused prepared image is released."); f.engine.dispose(); }); test("a missing folder shows an error, and the folder recovers on the next try", async () => { const f = fixture(); const missing: ImageSource = { ...f.source(), list: async () => { throw new Error("The background folder is missing. Choose the folder again."); } }; await f.engine.configure(missing, on); assert.equal(f.engine.status.error, true); assert.match(f.engine.status.message, /Choose the folder again/); assert.equal(f.frames.size, 0); await f.engine.configure(f.source("folder:D:\\Other"), on); assert.equal(f.engine.status.error, false); assert.equal(f.engine.status.image, "1.png"); f.engine.dispose(); }); test("a host failure clears the published targets and releases every image", async () => { const f = fixture(); let fail = false; const engine = new Slideshow({ set: (target, frame) => { if (fail && target === "pm-all" && frame) throw new Error("Background access ended."); if (frame) f.frames.set(target, frame); else f.frames.delete(target); } }, f.runtime); await engine.configure(f.source(), on); await engine.next(); await settle(); fail = true; await engine.next(); await settle(); assert.equal(engine.status.error, true); assert.equal(f.frames.size, 0); assert.equal(new Set(f.released).size, f.released.length, "No URL is released twice."); assert.ok(f.released.length >= 3); engine.dispose(); }); test("another source starts again, and a late read of the old source is ignored", async () => { const f = fixture(); let resolve!: (value: string[]) => void; const slow: ImageSource = { ...f.source("folder:D:\\Slow"), list: () => new Promise(done => { resolve = done; }) }; const pending = f.engine.configure(slow, on); await settle(); await f.engine.configure(f.source("folder:D:\\Other"), on); const current = f.frames.get("app")!.url; resolve(["stale.png"]); await pending; assert.equal(f.frames.get("app")!.url, current); assert.equal(f.engine.status.image, "1.png"); f.engine.dispose(); }); test("the list and the sidecar are read again only after a change, a focus, or every 10 images", async () => { const f = fixture(); await f.engine.configure(f.source(), { ...on, seconds: 1 }); assert.deepEqual([f.counts.list, f.counts.sidecar], [1, 1]); for (let index = 1; index < RESCAN_SLIDES; index++) await f.tick(); assert.deepEqual([f.counts.list, f.counts.sidecar], [1, 1], "Nine timer images read nothing again."); await f.tick(); assert.deepEqual([f.counts.list, f.counts.sidecar], [2, 2], "The eleventh image reads the folder again."); f.engine.invalidate(); await f.tick(); assert.deepEqual([f.counts.list, f.counts.sidecar], [3, 3], "A focus reads it again."); await f.engine.configure(f.source(), { ...on, seconds: 2 }); assert.deepEqual([f.counts.list, f.counts.sidecar], [4, 4], "A settings change reads it again."); f.engine.dispose(); }); test("a late image after disposal is released and never published", async () => { const f = fixture(); let resolve!: (value: { url: string; width: number; height: number }) => void; f.runtime.load = () => new Promise(done => { resolve = done; }); const pending = f.engine.configure(f.source(), on); await settle(); await settle(); f.engine.dispose(); resolve({ url: "blob:late", width: 1, height: 1 }); await pending; assert.deepEqual(f.released, ["blob:late"]); assert.equal(f.frames.size, 0); assert.equal(f.scheduled(), undefined); }); test("disposal clears the targets and stops the timer", async () => { const f = fixture(); await f.engine.configure(f.source(), on); const timer = f.scheduled()!; f.engine.dispose(); timer.callback(); await settle(); assert.equal(f.frames.size, 0); assert.equal(f.scheduled(), undefined); }); test("the image source shows one image without a timer and without the portrait default", async () => { const f = fixture({ width: 100, height: 300 }); const image: ImageSource = { key: "image:abc", timed: false, list: async () => ["image"], read: async () => new Blob(["saved"]), sidecar: async () => { throw new Error("not asked"); } }; await f.engine.configure(image, { ...on, size: "cover" }); assert.equal(f.frames.get("app")!.size, "cover"); assert.equal(f.frames.get("app")!.blurredUrl, undefined); assert.equal(f.scheduled(), undefined); await f.engine.next(); assert.equal(f.frames.get("app")!.previous, undefined, "Next keeps the one image."); assert.equal(f.counts.blur, 0); f.engine.dispose(); }); test("the sidecar keeps file names and other data, and rejects invalid appearance", () => { const value = { schema: 1, owner: "personal", images: { "Portrait.png": { fit: "blurred", position: "top", overlay: -0.25 } } }; assert.deepEqual(parseImageSettings(JSON.stringify(value)), value); assert.deepEqual(parseImageSettings(null), { schema: 1, images: {} }); for (const source of ["{}", '{"schema":2,"images":{}}', '{"schema":1,"images":[]}', '{"schema":1,"images":{"../a.png":{"fit":"cover"}}}', '{"schema":1,"images":{"a.png":{"fit":"crop"}}}', '{"schema":1,"images":{"a.png":{"overlay":2}}}']) { assert.throws(() => parseImageSettings(source), source); } const layout = { overlay: 0.3, position: "center" as const, size: "auto" as const }; assert.equal(imageAppearance(layout, undefined, true).fit, "blurred"); assert.equal(imageAppearance(layout, undefined, false).fit, "auto"); assert.equal(imageAppearance(layout, { fit: "cover", position: "bottom", overlay: -0.2 }, true).fit, "cover"); }); test("a partial image override inherits every other field", () => { const source = { schema: 1, owner: "personal", images: { "Portrait.png": { position: "top", note: "keep" }, "Other.png": {} } }; assert.deepEqual(parseImageSettings(JSON.stringify(source)), source); const layout = { overlay: 0.3, position: "center" as const, size: "auto" as const }; assert.deepEqual(imageAppearance(layout, { position: "top" }, false), { fit: "auto", position: "top", overlay: 0.3 }); assert.deepEqual(imageAppearance({ ...layout, size: "contain", overlay: -0.4 }, { position: "top" }, false), { fit: "contain", position: "top", overlay: -0.4 }); assert.deepEqual(imageAppearance(layout, { overlay: 0 }, true), { fit: "blurred", position: "center", overlay: 0 }); for (const value of [null, [], "cover", 1, { fit: null }, { position: "invalid" }, { overlay: "0" }, { overlay: null }]) { assert.throws(() => parseImageSettings(JSON.stringify({ schema: 1, images: { "Image.png": value } }))); } }); test("a partial override stays while the folder layout changes", async () => { const f = fixture(); f.names(["A.png"]); f.sidecar(JSON.stringify({ schema: 1, images: { "A.png": { position: "top" } } })); await f.engine.configure(f.source(), on); assert.equal(f.frames.get("app")!.size, "cover"); await f.engine.configure(f.source(), { ...on, size: "contain", overlay: -0.4, position: "bottom" }); assert.equal(f.frames.get("app")!.size, "contain"); assert.equal(f.frames.get("app")!.overlay, -0.4); assert.equal(f.frames.get("app")!.position, "top"); f.engine.dispose(); }); test("a portrait image shows in full over a blurred fill that stays alive through the fade", async () => { const f = fixture({ width: 100, height: 300 }); f.names(["A.png", "B.png"]); await f.engine.configure(f.source(), on); const first = f.frames.get("app")!; assert.equal(first.size, "contain"); assert.equal(first.blurredUrl, `${first.url}-blur`); f.sidecar(JSON.stringify({ schema: 1, images: { "B.png": { fit: "cover", position: "bottom", overlay: 0.4 } } })); f.engine.invalidate(); await f.engine.next(); await settle(); const second = f.frames.get("app")!; assert.equal(second.size, "cover"); assert.equal(second.position, "bottom"); assert.equal(second.overlay, 0.4); assert.equal(second.blurredUrl, undefined); assert.equal(second.previous!.blurredUrl, first.blurredUrl); assert.equal(f.released.includes(first.blurredUrl!), false, "The fill of the fade stays."); f.engine.dispose(); await settle(); for (const url of [first.url, first.blurredUrl!, second.url]) assert.ok(f.released.includes(url), url); }); test("the blurred fills of the last three images stay in the cache", async () => { const f = fixture({ width: 100, height: 300 }); f.names(["A.png", "B.png", "C.png", "D.png", "E.png"]); await f.engine.configure(f.source(), { ...on, order: "name" }); for (let index = 0; index < 4; index++) { await f.engine.next(); await settle(); await settle(); } const blurs = f.counts.blur; const releasedBlurs = f.released.filter(url => url.endsWith("-blur")).length; assert.ok(releasedBlurs >= 1, "Old fills beyond the cache are released."); assert.ok(blurs - releasedBlurs <= BLUR_CACHE + 1, "At most the cache and the prepared fill stay."); // The same image again uses the cached fill. const repeat = fixture({ width: 100, height: 300 }); repeat.names(["A.png", "B.png"]); await repeat.engine.configure(repeat.source(), on); for (let index = 0; index < 4; index++) { await repeat.engine.next(); await settle(); await settle(); } assert.equal(repeat.counts.blur, 2, "Two images that alternate use their cached fills."); f.engine.dispose(); repeat.engine.dispose(); }); test("a late blurred fill is released when the source goes away", async () => { let resolve!: (url: string) => void; const f = fixture({ width: 100, height: 300 }); f.names(["A.png"]); f.runtime.blur = () => new Promise(done => { resolve = done; }); const loading = f.engine.configure(f.source(), on); await settle(); await settle(); await f.engine.configure(null, on); resolve("blob:blur"); await loading; assert.equal(f.frames.size, 0); assert.ok(f.released.includes("blob:blur")); assert.ok(f.released.some(url => url.startsWith("blob:A.png"))); f.engine.dispose(); }); test("the sources have stable keys, and the saved image of an old data URL decodes", async () => { assert.equal(folderSource("D:\\Pictures").key, "folder:D:\\Pictures"); assert.equal(folderSource("D:\\Pictures").timed, true); const id = "01234567-89ab-cdef-0123-456789abcdef"; assert.equal(imageSource({ imageId: id }).key, `image:${id}`); assert.equal(imageSource({ imageId: id }).timed, false); assert.deepEqual(await imageSource({ imageId: id }).list(), ["image"]); const data = "data:image/png;base64,iVBORw0KGgo="; const blob = await readSavedImage({ image: data }); assert.equal(blob.type, "image/png"); assert.deepEqual([...new Uint8Array(await blob.arrayBuffer())], [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); assert.notEqual(imageSource({ image: data }).key, imageSource({ image: data.replace("KGgo", "KGgp") }).key); }); test("Background has a source only with a folder or an existing image", () => { const appearance = { theme: "default" as const, mode: "dark" as const }; const withImage = { ...appearance, newTabBackground: { imageId: "01234567-89ab-cdef-0123-456789abcdef" } }; assert.equal(hasBackgroundSource(normalizeBackground({ source: "none" }), withImage), false); assert.equal(hasBackgroundSource(normalizeBackground({ source: "folder" }), appearance), true); assert.equal(hasBackgroundSource(normalizeBackground({ source: "image" }), appearance), false); assert.equal(hasBackgroundSource(normalizeBackground({ source: "image" }), withImage), true); }); test("the launch rule starts Background when it has a source, also in browser windows, but not in the settings window", () => { const rule = LAUNCH_RULES.background!; assert.equal(rule.browserWindow, true); assert.equal(LAUNCH_RULES.git, undefined, "Git loads at first need."); assert.equal(runsInWindow("background", { browserWindow: true }), true); assert.equal(runsInWindow("git", { browserWindow: true }), false); assert.equal(runsInWindow("git", { browserWindow: false }), true); assert.equal(launchWanted("git", { settingsWindow: false }), false); // In Node the settings are empty, so the source is "none". assert.equal(rule.wanted(), false); assert.equal(launchWanted("background", { settingsWindow: false }), false); const wanted = rule.wanted; rule.wanted = () => true; try { assert.equal(launchWanted("background", { settingsWindow: false }), true); assert.equal(launchWanted("background", { settingsWindow: true }), false); } finally { rule.wanted = wanted; } }); function migrationHost({ image = false, folder = true, fails = false } = {}) { const calls = { folder: 0 }; const written: BackgroundSettings[] = []; const host: BackgroundMigrationHost = { missing: () => true, hasImage: () => image, migrateFolder: async () => { calls.folder++; if (fails) throw new Error("no folder"); return folder; }, write: async value => { written.push(value); }, }; return { host, calls, written }; } const plugin = (installed: boolean, enabled: boolean, settings: unknown): LegacyPlugin => ({ id: "runestone.bg-slideshow", installed, enabled, settings }); const grant = "6f0c7a8e-5b1d-4c2e-9a3f-2d7b8e1c4a90"; const kept = { grant, folder: "D:\\Pictures", seconds: 10, order: "random", enabled: true, targets: ["app", "pm-all"], overlay: 0.25, position: "top", size: "contain" }; test("the migration selects the folder of an installed, enabled, and running slideshow", async () => { const { host, calls, written } = migrationHost({ image: true }); const value = await migrateBackground(plugin(true, true, kept), host); assert.equal(calls.folder, 1); assert.deepEqual(value, { source: "folder", seconds: 10, order: "random", paused: false, targets: ["app", "pm-all"], overlay: 0.25, position: "top", size: "contain" }); assert.deepEqual(written, [value]); }); test("a disabled package, a stopped slideshow, or a lost folder gives the image or none, and the folder still migrates", async () => { for (const [legacy, folder] of [[plugin(true, false, kept), true], [plugin(true, true, { ...kept, enabled: false }), true], [plugin(false, false, kept), true], [plugin(true, true, kept), false]] as const) { const withImage = migrationHost({ image: true, folder }); assert.equal((await migrateBackground(legacy, withImage.host)).source, "image"); assert.equal(withImage.calls.folder, 1, "A kept grant always migrates its folder."); const without = migrationHost({ folder }); const value = await migrateBackground(legacy, without.host); assert.equal(value.source, "none"); assert.equal(value.seconds, 10, "The kept settings still give the sequence and the layout."); } }); test("a failed folder migration is not a failed start", async () => { const errors = console.error; console.error = () => {}; try { const { host, written } = migrationHost({ image: true, fails: true }); assert.equal((await migrateBackground(plugin(true, true, kept), host)).source, "image"); assert.equal(written.length, 1); } finally { console.error = errors; } }); test("without the old plugin, an image gives the image source and nothing gives none", async () => { const image = migrationHost({ image: true }); assert.deepEqual(await migrateBackground(undefined, image.host), { ...DEFAULT_BACKGROUND, targets: ["app"], source: "image" }); assert.equal(image.calls.folder, 0, "Without a grant, no folder migrates."); const none = migrationHost(); assert.deepEqual(await migrateBackground(plugin(false, false, null), none.host), { ...DEFAULT_BACKGROUND, targets: ["app"] }); // Settings of version 0.0.10 and earlier have a path and no grant. Only a grant migrates. const old = migrationHost(); assert.equal((await migrateBackground(plugin(true, true, { folder: "D:\\Pictures", enabled: true }), old.host)).source, "none"); assert.equal(old.calls.folder, 0); // Invalid kept values take the defaults. const invalid = migrationHost(); const value = await migrateBackground(plugin(true, true, { grant, enabled: true, seconds: "x", targets: ["bogus"], overlay: 9 }), invalid.host); assert.deepEqual([value.source, value.seconds, value.targets, value.overlay], ["folder", 60, [], 1]); });