// The Background engine: it shows the images of a source as background frames, one after the other. // It comes from the engine of the Background Slideshow plugin, with these changes for the open card // "Lag before image transition": the next image loads and decodes before its fade, the blurred fills of the // last images stay in a cache, and the folder list and the sidecar are read again only after a settings change, // on window focus, or after every 10 images. import { tr } from "../../i18n/index.ts"; import type { BackgroundFrame } from "../../plugins/backgroundContracts.ts"; import type { BackgroundLayout } from "../backgroundSettings.ts"; import { imageAppearance, imageNames, parseImageSettings, sequence, type ImageAppearance, type ImageSettings } from "./imageSettings.ts"; /** The time of the fade from one image to the next. */ export const transitionMs = 2000; /** The folder list and the sidecar are read again after this number of images. */ export const RESCAN_SLIDES = 10; /** The number of blurred fills that stay in the cache. */ export const BLUR_CACHE = 3; /** The shortest wait before a new try after an error. */ export const RETRY_MS = 5000; /** Where the images come from: the image folder of the host, or the one saved image. */ export interface ImageSource { /** A different key means a different folder or image. The engine then starts again. */ readonly key: string; /** True for a folder: the images change on a timer, and the sidecar and the portrait default apply. */ readonly timed: boolean; /** The image names. */ list(): Promise; read(name: string): Promise; /** The text of the sidecar file, or null. */ sidecar(): Promise; } export interface LoadedImage { url: string; width: number; height: number } /** The browser services of the engine. Tests replace them. */ export interface Runtime { /** Make a blob URL and decode the image before it shows. */ load(blob: Blob): Promise; /** Make the blurred fill of a loaded image. The engine releases the URL. */ blur(image: LoadedImage): Promise; release(url: string): void; later(callback: () => void, milliseconds: number): unknown; cancel(timer: unknown): void; random(): number; now(): number; } export interface Frames { set(target: string, frame: BackgroundFrame | null): void } export interface EngineSettings extends BackgroundLayout { seconds: number; order: "name" | "random"; paused: boolean; targets: string[]; } export interface Status { message: string; image: string | null; count: number; error: boolean } interface Shown { name: string; key: string; image: LoadedImage; appearance: ImageAppearance; blurred?: string } interface Prepared { name: string; key: string; image: LoadedImage } function toFrame(shown: Shown): BackgroundFrame { const frame: BackgroundFrame = { url: shown.image.url, overlay: shown.appearance.overlay, position: shown.appearance.position, size: shown.appearance.fit === "blurred" ? "contain" : shown.appearance.fit }; if (shown.blurred) frame.blurredUrl = shown.blurred; return frame; } const sameAppearance = (a: ImageAppearance, b: ImageAppearance) => a.fit === b.fit && a.position === b.position && a.overlay === b.overlay; export class Slideshow { status: Status = { message: "", image: null, count: 0, error: false }; private source: ImageSource | null = null; private settings: EngineSettings | null = null; private revision = 0; private stopped = false; private timer: unknown; /** When the current timer fires, or null without a timer. */ private due: number | null = null; private names: string[] | null = null; private imageSettings: ImageSettings = { schema: 1, images: {} }; private sidecarError = ""; private stale = true; private slides = 0; private shown: Shown | null = null; /** The image that the current frame fades from. */ private previous: Shown | null = null; private targets = new Set(); /** The blurred fills, oldest first. */ private blurs = new Map(); private prepared: { name: string; work: Promise; discarded: boolean } | null = null; /** Changes at each `clear`, so that a late blurred fill of an old image does not enter the cache. */ private epoch = 0; private listeners = new Set<() => void>(); private frames: Frames; private runtime: Runtime; constructor(frames: Frames, runtime: Runtime) { this.frames = frames; this.runtime = runtime; } subscribe(listener: () => void) { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; } private notify() { for (const listener of [...this.listeners]) listener(); } /** Use a new source or new settings. The current image stays when the source is the same and still has it. */ configure(source: ImageSource | null, settings: EngineSettings): Promise { if (this.stopped) return Promise.resolve(); if (source?.key !== this.source?.key) { this.clear(); this.names = null; } this.source = source; this.settings = { ...settings, targets: [...settings.targets] }; this.stale = true; return this.update(false); } /** Read the list and the sidecar again before the next image, for example after a window focus. */ invalidate() { this.stale = true; } /** Read the list and the sidecar again now, and apply them to the current image. */ reload = () => { this.stale = true; return this.update(false); }; /** Show the next image now. */ next = () => this.update(true); dispose() { if (this.stopped) return; this.stopped = true; this.revision++; this.runtime.cancel(this.timer); this.timer = undefined; this.clear(); this.listeners.clear(); } private async update(advance: boolean): Promise { if (this.stopped) return; const revision = ++this.revision; const remaining = this.due === null ? null : Math.max(0, this.due - this.runtime.now()); this.runtime.cancel(this.timer); this.timer = undefined; this.due = null; const valid = () => !this.stopped && revision === this.revision; const source = this.source, settings = this.settings; try { if (!source || !settings) { this.clear(); this.setStatus(tr("Choose a folder or an image to show a background.")); return; } if (!settings.targets.length) { this.clear(); this.setStatus(tr("Select where to show the background.")); return; } if (this.stale || !this.names) { const [list, sidecar] = await Promise.all([source.list(), source.timed ? source.sidecar() : Promise.resolve(null)]); if (!valid()) return; this.names = source.timed ? imageNames(list) : [...list]; try { this.imageSettings = parseImageSettings(sidecar); this.sidecarError = ""; } catch (reason) { this.imageSettings = { schema: 1, images: {} }; this.sidecarError = reason instanceof Error ? reason.message : String(reason); } this.stale = false; this.slides = 0; if (this.prepared && !this.names.includes(this.prepared.name)) this.discardPrepared(); } const names = this.names; this.status.count = names.length; if (!names.length) throw new Error(tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files.")); const shown = this.shown; if (shown && names.includes(shown.name) && (!advance || names.length === 1)) { await this.reapply(shown, settings, valid); if (!valid()) return; this.schedule(remaining ?? settings.seconds * 1000, revision); this.prepare(); return; } let failures = 0; const order = sequence(names, shown?.name ?? null, settings.order, this.runtime.random); const candidates = this.prepared && order.includes(this.prepared.name) ? [this.prepared.name, ...order.filter(name => name !== this.prepared!.name)] : order; for (const name of candidates) { let loaded: Prepared | null = null; let next: Shown; try { loaded = await this.load(name); if (!valid()) { if (loaded) this.runtime.release(loaded.image.url); return; } if (!loaded) throw new Error(tr("The image cannot be displayed.")); next = { ...loaded, appearance: this.appearanceOf(name, loaded.image, settings) }; if (next.appearance.fit === "blurred") { next.blurred = await this.blurOf(loaded); if (!valid()) { this.runtime.release(loaded.image.url); return; } } } catch { if (loaded) this.runtime.release(loaded.image.url); if (!valid()) return; failures++; continue; } this.publish(next, settings, true); const message = failures ? tr("{name}: skipped {count} unreadable images.", { name, count: failures }) : name; this.status = { image: name, count: names.length, error: !!this.sidecarError, message: this.sidecarError ? `${message} ${this.sidecarError}` : message }; this.notify(); if (++this.slides >= RESCAN_SLIDES) this.stale = true; this.schedule(settings.seconds * 1000, revision); this.prepare(); return; } throw new Error(tr("No readable images in this folder. Check the image files.")); } catch (error) { if (!valid()) return; this.clear(); this.status = { ...this.status, image: null, error: true, message: error instanceof Error ? error.message : String(error) }; this.notify(); if (source?.timed && settings) this.schedule(Math.max(RETRY_MS, settings.seconds * 1000), revision, true); } } private setStatus(message: string) { this.status = { message, image: null, count: 0, error: false }; this.notify(); } private appearanceOf(name: string, image: LoadedImage, settings: EngineSettings): ImageAppearance { if (!this.source?.timed) return { fit: settings.size, position: settings.position, overlay: settings.overlay }; return imageAppearance(settings, this.imageSettings.images[name], image.height > image.width); } /** The image of `name`: the prepared image when it matches, or a new read. */ private async load(name: string): Promise { const prepared = this.prepared; if (prepared?.name === name) { this.prepared = null; const result = await prepared.work.catch(() => null); if (result) return result; } const source = this.source!; const blob = await source.read(name); const image = await this.runtime.load(blob); return { name, key: `${source.key}\n${name}\n${blob.size}`, image }; } /** Load and decode the next image of a timed source now, so that its fade starts on time. */ private prepare() { const source = this.source, settings = this.settings, names = this.names, shown = this.shown; if (!source?.timed || !settings || settings.paused || !names || names.length < 2 || !shown || this.prepared) return; const name = sequence(names, shown.name, settings.order, this.runtime.random)[0]; const entry: { name: string; work: Promise; discarded: boolean } = { name, work: Promise.resolve(null), discarded: false }; entry.work = (async (): Promise => { const blob = await source.read(name); const image = await this.runtime.load(blob); // A prepared image that nobody wants any more goes away at once. if (this.stopped || entry.discarded) { this.runtime.release(image.url); return null; } const result = { name, key: `${source.key}\n${name}\n${blob.size}`, image }; const appearance = imageAppearance(settings, this.imageSettings.images[name], image.height > image.width); if (appearance.fit === "blurred") await this.blurOf(result).catch(() => undefined); return result; })(); entry.work.catch(() => undefined); this.prepared = entry; } private discardPrepared() { const prepared = this.prepared; this.prepared = null; if (!prepared) return; prepared.discarded = true; void prepared.work.then(result => { if (result) this.runtime.release(result.image.url); }, () => undefined); } /** The blurred fill of an image, from the cache when possible. */ private async blurOf(image: Prepared): Promise { const cached = this.blurs.get(image.key); if (cached) { this.blurs.delete(image.key); this.blurs.set(image.key, cached); return cached; } const epoch = this.epoch; const url = await this.runtime.blur(image.image); if (this.stopped || epoch !== this.epoch) { this.runtime.release(url); throw new Error(tr("The background changed.")); } const again = this.blurs.get(image.key); if (again) { this.runtime.release(url); return again; } this.blurs.set(image.key, url); this.trimBlurs(url); return url; } /** Release the oldest blurred fills beyond the cache size. Fills that a frame shows stay. */ private trimBlurs(keep?: string) { const used = new Set([this.shown?.blurred, this.previous?.blurred, keep]); for (const [key, url] of this.blurs) { if (this.blurs.size <= BLUR_CACHE) break; if (used.has(url)) continue; this.blurs.delete(key); this.runtime.release(url); } } /** Apply new settings or new image settings to the image that shows, without a fade. */ private async reapply(shown: Shown, settings: EngineSettings, valid: () => boolean) { const appearance = this.appearanceOf(shown.name, shown.image, settings); const sameTargets = settings.targets.length === this.targets.size && settings.targets.every(target => this.targets.has(target)); const needsBlur = appearance.fit === "blurred" && !shown.blurred; if (sameTargets && sameAppearance(appearance, shown.appearance) && !needsBlur) return; const next: Shown = { ...shown, appearance, blurred: undefined }; if (appearance.fit === "blurred") { next.blurred = await this.blurOf(shown); if (!valid()) return; } this.publish(next, settings, false); this.notify(); } /** Show `next` on every target. With `fade`, the frame fades from the image that showed before. */ private publish(next: Shown, settings: EngineSettings, fade: boolean) { const old = this.shown; const frame = toFrame(next); if (fade && old) { frame.previous = toFrame(old); frame.transitionMs = transitionMs; } try { for (const target of this.targets) if (!settings.targets.includes(target)) this.frames.set(target, null); // Track the new targets before the frames go out, so that a cleanup also clears a partial publish. for (const target of settings.targets) this.targets.add(target); for (const target of settings.targets) this.frames.set(target, frame); } catch (error) { if (next.image !== old?.image) this.runtime.release(next.image.url); throw error; } this.targets = new Set(settings.targets); // Keep the image of the fade until the next frame replaces it. const release = this.previous; if (release && release.image !== next.image && release.image !== old?.image) this.runtime.release(release.image.url); this.previous = fade && old && old.image !== next.image ? old : null; if (!fade && old && old.image !== next.image) this.runtime.release(old.image.url); this.shown = next; this.trimBlurs(); } /** Remove the frames of every target and release every image. */ private clear() { for (const target of this.targets) { try { this.frames.set(target, null); } catch { /* The window can close before the cleanup. */ } } this.targets.clear(); const images = new Set([this.shown?.image.url, this.previous?.image.url]); for (const url of images) if (url) this.runtime.release(url); for (const url of this.blurs.values()) this.runtime.release(url); this.blurs.clear(); this.epoch++; this.discardPrepared(); this.shown = null; this.previous = null; this.status = { ...this.status, image: null }; } private schedule(milliseconds: number, revision: number, retry = false) { const settings = this.settings; if (this.stopped || this.revision !== revision || !this.source?.timed || !settings) return; if (settings.paused && !retry) return; this.due = this.runtime.now() + milliseconds; this.timer = this.runtime.later(() => { this.timer = undefined; this.due = null; void this.update(true); }, milliseconds); } }