RuneStone 1.0.0
This commit is contained in:
@@ -0,0 +1,295 @@
|
||||
<!--
|
||||
Appearance → Background. The source is a folder (a slideshow), one image, or none. The folder layout and the order
|
||||
are in the `background` settings section. The image and its layout stay in `appearance.newTabBackground`.
|
||||
This component also works in the settings window, where the slideshow does not run. It sends Next to every window.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { onDestroy, onMount } from "svelte";
|
||||
import { t, tr } from "$lib/i18n";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
||||
import { onSettingsChange } from "$lib/settings/store";
|
||||
import { featureSwitches } from "$lib/features/state";
|
||||
import { readBoardCatalog } from "../pmBoards";
|
||||
import { BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, saveAppearance, type Appearance } from "$lib/theme/appearance";
|
||||
import { removeBackgroundImage, saveBackgroundImage } from "$lib/theme/backgroundImages";
|
||||
import { hasImage, normalizeLayout, readBackground, writeBackground, type BackgroundLayout, type BackgroundSettings, type BackgroundSource } from "../backgroundSettings";
|
||||
import { folderHost, readSavedImage, sendBackgroundCommand } from "./sources";
|
||||
import { imageNames } from "./imageSettings";
|
||||
import ImageEditor from "./ImageEditor.svelte";
|
||||
|
||||
/** The background targets of single boards need a UUID board ID. */
|
||||
const boardId = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
let settings = $state<BackgroundSettings>(readBackground());
|
||||
let appearance = $state<Appearance>(readAppearance());
|
||||
let folder = $state<string | null>(null);
|
||||
let folderNote = $state("");
|
||||
let boards = $state<{ id: string; name: string }[]>([]);
|
||||
let boardsNote = $state("");
|
||||
let previewUrl = $state("");
|
||||
let error = $state("");
|
||||
let imageInput: HTMLInputElement;
|
||||
let imageRevision = 0;
|
||||
let boardRevision = 0;
|
||||
let previewKey = "";
|
||||
let closeMenu = () => {};
|
||||
let disposed = false;
|
||||
|
||||
const image = $derived(appearance.newTabBackground);
|
||||
const layout = $derived<BackgroundLayout | null>(settings.source === "folder" ? normalizeLayout(settings) : settings.source === "image" && hasImage(appearance) ? normalizeLayout(image) : null);
|
||||
const sourceLabels = $derived<Record<BackgroundSource, string>>({ folder: $t("Folder"), image: $t("Image"), none: $t("None") });
|
||||
const positionLabels = $derived([$t("Center"), $t("Top left"), $t("Top center"), $t("Top right"), $t("Center left"), $t("Center right"), $t("Bottom left"), $t("Bottom center"), $t("Bottom right")]);
|
||||
const sizeLabels = $derived([$t("Fill"), $t("Fit"), $t("Actual size")]);
|
||||
const orderLabels = $derived({ name: $t("File name"), random: $t("Random") });
|
||||
const targets = $derived([
|
||||
{ id: "app", name: $t("The workspace and new tabs") },
|
||||
{ id: "pm-all", name: $t("All Project Management boards") },
|
||||
...boards.map(board => ({ id: `pm-board:${board.id}`, name: $t("Board: {name}", { name: board.name }) })),
|
||||
// Keep saved targets without a current board, so that the user can remove them.
|
||||
...settings.targets.filter(id => id.startsWith("pm-board:") && !boards.some(board => `pm-board:${board.id}` === id))
|
||||
.map(id => ({ id, name: $t("Unavailable board: {id}", { id: id.slice(9) }) })),
|
||||
]);
|
||||
|
||||
const report = (reason: unknown) => { if (!disposed) error = reason instanceof Error ? reason.message : String(reason); };
|
||||
|
||||
function save(next: BackgroundSettings) {
|
||||
settings = next; error = "";
|
||||
writeBackground(next).catch(() => report(tr("Could not save the background settings.")));
|
||||
}
|
||||
|
||||
function saveImageAppearance(next: Appearance) {
|
||||
try {
|
||||
saveAppearance(next).catch(() => report(tr("Could not save appearance settings.")));
|
||||
appearance = readAppearance(); error = ""; return true;
|
||||
} catch { report(tr("Could not save appearance settings.")); return false; }
|
||||
}
|
||||
|
||||
function changeLayout(patch: Partial<BackgroundLayout>) {
|
||||
if (settings.source === "folder") save({ ...settings, ...patch });
|
||||
else if (image) saveImageAppearance({ ...appearance, newTabBackground: { ...image, ...patch } });
|
||||
}
|
||||
|
||||
function changeOverlay(input: HTMLInputElement) {
|
||||
const percent = input.valueAsNumber;
|
||||
if (!Number.isFinite(percent)) return;
|
||||
changeLayout({ overlay: Math.round(Math.max(-100, Math.min(100, percent))) / 100 });
|
||||
}
|
||||
|
||||
function picker(event: MouseEvent, label: string, choices: { label: string; checked: boolean; run: () => void }[]) {
|
||||
closeMenu();
|
||||
const anchor = event.currentTarget as HTMLButtonElement;
|
||||
const bounds = anchor.getBoundingClientRect();
|
||||
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label, parent: anchor.closest("dialog") ?? undefined,
|
||||
items: choices.map(choice => ({ label: choice.label, radio: true, checked: choice.checked, run: choice.run })) }).close;
|
||||
}
|
||||
|
||||
async function chooseSource(source: BackgroundSource) {
|
||||
error = "";
|
||||
if (source === "folder" && !folder) { await chooseFolder(); return; }
|
||||
if (source === "image" && !hasImage(appearance)) { imageInput.click(); return; }
|
||||
save({ ...settings, source });
|
||||
}
|
||||
|
||||
async function chooseFolder() {
|
||||
try {
|
||||
const chosen = await folderHost.choose(tr("Choose the background folder"));
|
||||
if (!chosen || disposed) return;
|
||||
folder = chosen;
|
||||
save({ ...settings, source: "folder" });
|
||||
await sendBackgroundCommand("reload");
|
||||
void inspectFolder();
|
||||
} catch (reason) { report(reason); }
|
||||
}
|
||||
|
||||
async function removeFolder() {
|
||||
try {
|
||||
await folderHost.clear();
|
||||
folder = null; folderNote = "";
|
||||
if (settings.source === "folder") save({ ...settings, source: "none" });
|
||||
await sendBackgroundCommand("reload");
|
||||
} catch (reason) { report(reason); }
|
||||
}
|
||||
|
||||
/** Count the images of the folder, so that the user sees a problem at once. */
|
||||
async function inspectFolder() {
|
||||
if (!folder) { folderNote = ""; return; }
|
||||
try {
|
||||
const count = imageNames(await folderHost.list()).length;
|
||||
if (!disposed) folderNote = count ? tr(count === 1 ? "{count} image." : "{count} images.", { count }) : tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files.");
|
||||
} catch (reason) { if (!disposed) folderNote = reason instanceof Error ? reason.message : String(reason); }
|
||||
}
|
||||
|
||||
async function importImage(file?: File) {
|
||||
if (!file) return;
|
||||
const revision = ++imageRevision;
|
||||
try {
|
||||
if (!["image/png", "image/jpeg", "image/webp", "image/gif"].includes(file.type)) throw new Error(tr("Choose a PNG, JPEG, WebP, or GIF image."));
|
||||
const imageId = await saveBackgroundImage(file);
|
||||
if (revision !== imageRevision) { await removeBackgroundImage(imageId); return; }
|
||||
const old = appearance.newTabBackground?.imageId;
|
||||
if (saveImageAppearance({ ...appearance, newTabBackground: { ...appearance.newTabBackground, image: undefined, imageId, overlay: appearance.newTabBackground?.overlay ?? 0 } })) {
|
||||
if (settings.source !== "image") save({ ...settings, source: "image" });
|
||||
if (old) await removeBackgroundImage(old);
|
||||
} else await removeBackgroundImage(imageId);
|
||||
} catch (reason) { if (revision === imageRevision) report(reason); }
|
||||
finally { if (revision === imageRevision) imageInput.value = ""; }
|
||||
}
|
||||
|
||||
async function removeImage() {
|
||||
imageRevision++;
|
||||
const old = appearance.newTabBackground?.imageId;
|
||||
if (saveImageAppearance({ ...appearance, newTabBackground: undefined }) && old) {
|
||||
try { await removeBackgroundImage(old); } catch { report(tr("Could not remove the saved image from storage.")); }
|
||||
}
|
||||
}
|
||||
|
||||
function toggleTarget(id: string, on: boolean) {
|
||||
save({ ...settings, targets: on ? [...new Set([...settings.targets, id])] : settings.targets.filter(target => target !== id) });
|
||||
}
|
||||
|
||||
/** The active boards of `.runestone/pm/workspace.json`. It needs no Project Management code. */
|
||||
async function discoverBoards(on: boolean) {
|
||||
const revision = ++boardRevision;
|
||||
if (!on) {
|
||||
boards = []; boardsNote = tr("Turn on Project Management to show the background on one board.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const catalog = await readBoardCatalog();
|
||||
if (disposed || revision !== boardRevision) return;
|
||||
boards = catalog.boards.filter(board => !board.archived && boardId.test(board.id)).map(board => ({ id: board.id, name: board.name }));
|
||||
boardsNote = boards.length ? "" : tr("The workspace has no boards.");
|
||||
} catch (reason) {
|
||||
if (!disposed && revision === boardRevision) boardsNote = tr("Could not read the workspace boards: {error}", { error: reason instanceof Error ? reason.message : String(reason) });
|
||||
}
|
||||
}
|
||||
|
||||
/** The preview of the saved image. It uses its own blob URL, so it works in every window. */
|
||||
async function updatePreview() {
|
||||
const saved = settings.source === "image" ? appearance.newTabBackground : undefined;
|
||||
const key = saved && hasImage(appearance) ? saved.imageId ?? `${saved.image?.length}:${saved.image?.slice(-48)}` : "";
|
||||
if (key === previewKey) return;
|
||||
previewKey = key;
|
||||
if (previewUrl) URL.revokeObjectURL(previewUrl);
|
||||
previewUrl = "";
|
||||
if (!key || !saved) return;
|
||||
try {
|
||||
const url = URL.createObjectURL(await readSavedImage(saved));
|
||||
if (disposed || previewKey !== key) { URL.revokeObjectURL(url); return; }
|
||||
previewUrl = url;
|
||||
} catch (reason) { report(reason); }
|
||||
}
|
||||
|
||||
const overlayShade = $derived(layout ? `linear-gradient(rgba(${layout.overlay < 0 ? "255,255,255" : "0,0,0"},${Math.abs(layout.overlay)}),rgba(${layout.overlay < 0 ? "255,255,255" : "0,0,0"},${Math.abs(layout.overlay)}))` : "none");
|
||||
|
||||
$effect(() => { void settings.source; void appearance.newTabBackground; void updatePreview(); });
|
||||
|
||||
onMount(() => {
|
||||
const read = () => { settings = readBackground(); appearance = readAppearance(); };
|
||||
const stops = [onSettingsChange("background", read), onSettingsChange("appearance", read), featureSwitches.subscribe(switches => { void discoverBoards(switches.pm); })];
|
||||
void folderHost.current().then(value => { if (!disposed) { folder = value; void inspectFolder(); } }, () => { folder = null; });
|
||||
return () => stops.forEach(stop => stop());
|
||||
});
|
||||
onDestroy(() => { disposed = true; closeMenu(); if (previewUrl) URL.revokeObjectURL(previewUrl); });
|
||||
</script>
|
||||
|
||||
<div class="background-settings">
|
||||
<div class="card">
|
||||
<div class="setting-row"><span>{$t("Background source")}</span><button class="picker" aria-label={$t("Background source")} aria-haspopup="menu"
|
||||
onclick={event => picker(event, $t("Background source"), (["folder", "image", "none"] as const).map(source => ({ label: sourceLabels[source], checked: settings.source === source, run: () => void chooseSource(source) })))}>{sourceLabels[settings.source]}<Icon icon="chevron-down" /></button></div>
|
||||
{#if settings.source === "folder"}
|
||||
<div class="setting-row folder-row"><label for="background-folder">{$t("Image folder")}</label><div class="controls folder-controls">
|
||||
<input id="background-folder" readonly value={folder ?? ""} title={folder ?? ""} placeholder={$t("No folder selected")} />
|
||||
<button onclick={() => void chooseFolder()}><Icon icon="folder-open" />{$t("Choose folder…")}</button>
|
||||
{#if folder}<button onclick={() => void removeFolder()}>{$t("Remove folder")}</button>{/if}
|
||||
</div></div>
|
||||
<div class="setting-row"><label for="background-seconds">{$t("Seconds per image")}</label><input id="background-seconds" type="number" min="1" max="86400" step="1" value={settings.seconds}
|
||||
onchange={event => { if (event.currentTarget.reportValidity()) save({ ...settings, seconds: event.currentTarget.valueAsNumber }); }} /></div>
|
||||
<div class="setting-row"><span>{$t("Image order")}</span><button class="picker" aria-label={$t("Image order")} aria-haspopup="menu"
|
||||
onclick={event => picker(event, $t("Image order"), (["name", "random"] as const).map(order => ({ label: orderLabels[order], checked: settings.order === order, run: () => save({ ...settings, order }) })))}>{orderLabels[settings.order]}<Icon icon="chevron-down" /></button></div>
|
||||
<div class="setting-row"><span>{$t("Slideshow")}</span><div class="controls">
|
||||
<button onclick={() => void sendBackgroundCommand("next").catch(report)}><Icon icon="arrow-right" />{$t("Next image")}</button>
|
||||
<button aria-pressed={settings.paused} onclick={() => save({ ...settings, paused: !settings.paused })}>{settings.paused ? $t("Resume slideshow") : $t("Pause slideshow")}</button>
|
||||
</div></div>
|
||||
{:else if settings.source === "image"}
|
||||
<div class="background-preview" role="img" aria-label={$t("Background image preview")}
|
||||
style:background-image={previewUrl ? `${overlayShade}, url("${previewUrl}")` : "none"}
|
||||
style:background-size={layout ? `100% 100%, ${layout.size}` : undefined}
|
||||
style:background-position={layout ? `center, ${layout.position}` : undefined}><span>{$t("Background")}</span></div>
|
||||
<div class="actions">
|
||||
<button onclick={() => imageInput.click()}>{$t("Choose image…")}</button>
|
||||
{#if image}<button onclick={() => void removeImage()}>{$t("Remove image")}</button>{/if}
|
||||
</div>
|
||||
{/if}
|
||||
{#if layout}
|
||||
<div class="setting-row"><span>{$t("Image position")}</span><button class="picker" aria-label={$t("Image position")} aria-haspopup="menu"
|
||||
onclick={event => picker(event, $t("Image position"), BACKGROUND_POSITIONS.map((value, index) => ({ label: positionLabels[index], checked: layout?.position === value, run: () => changeLayout({ position: value }) })))}>{positionLabels[BACKGROUND_POSITIONS.indexOf(layout.position)]}<Icon icon="chevron-down" /></button></div>
|
||||
<div class="setting-row"><span>{$t("Image size")}</span><button class="picker" aria-label={$t("Image size")} aria-haspopup="menu"
|
||||
onclick={event => picker(event, $t("Image size"), BACKGROUND_SIZES.map((value, index) => ({ label: sizeLabels[index], checked: layout?.size === value, run: () => changeLayout({ size: value }) })))}>{sizeLabels[BACKGROUND_SIZES.indexOf(layout.size)]}<Icon icon="chevron-down" /></button></div>
|
||||
<div class="setting-row"><span>{$t("Image overlay")}</span><div class="controls overlay-controls">
|
||||
<input type="range" aria-label={$t("Image overlay")} min="-100" max="100" value={Math.round(layout.overlay * 100)} oninput={event => changeOverlay(event.currentTarget)} />
|
||||
<label class="overlay-value"><input type="number" aria-label={$t("Image overlay percentage")} min="-100" max="100" step="1" value={Math.round(layout.overlay * 100)}
|
||||
oninput={event => changeOverlay(event.currentTarget)} onblur={event => { event.currentTarget.value = String(Math.round((layout?.overlay ?? 0) * 100)); }} /><span>%</span></label>
|
||||
</div></div>
|
||||
{/if}
|
||||
</div>
|
||||
<input bind:this={imageInput} type="file" accept="image/png,image/jpeg,image/webp,image/gif" aria-label={$t("Background image file")} hidden onchange={event => void importImage(event.currentTarget.files?.[0])} />
|
||||
{#if settings.source === "folder"}
|
||||
<p>{$t("Add PNG, JPEG, GIF, or WebP images to the folder. Portrait images show in full over a blurred fill.")}</p>
|
||||
{#if folderNote}<p role="status">{folderNote}</p>{/if}
|
||||
{:else if settings.source === "image"}
|
||||
<p>{$t("PNG, JPEG, WebP, or GIF, up to 50 MiB. The image stays on this device.")}</p>
|
||||
{:else}
|
||||
<p>{$t("Choose a folder for a slideshow, or one image.")}</p>
|
||||
{/if}
|
||||
{#if layout}<p>{$t("Move the overlay left to lighten the image or right to darken it.")}</p>{/if}
|
||||
{#if settings.source === "folder" && folder}
|
||||
<ImageEditor {settings} />
|
||||
{/if}
|
||||
{#if settings.source !== "none"}
|
||||
<fieldset class="targets">
|
||||
<legend>{$t("Show the background in")}</legend>
|
||||
{#each targets as target (target.id)}
|
||||
<label class="check"><input type="checkbox" checked={settings.targets.includes(target.id)} onchange={event => toggleTarget(target.id, event.currentTarget.checked)} /><span>{target.name}</span></label>
|
||||
{/each}
|
||||
{#if boardsNote}<p>{boardsNote}</p>{/if}
|
||||
</fieldset>
|
||||
{/if}
|
||||
{#if error}<p role="alert">{error}</p>{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.background-settings { display: grid; gap: var(--rs-settings-gap); min-width: 0; }
|
||||
p { margin: 0; color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); line-height: 1.5; overflow-wrap: anywhere; }
|
||||
.card { padding: 0 var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); min-width: 0; }
|
||||
.setting-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: var(--rs-settings-gap); padding: var(--rs-settings-row-padding) 0; min-width: 0; }
|
||||
.card > * + * { border-top: 1px solid var(--rs-border); }
|
||||
.controls { display: flex; align-items: center; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; max-width: 100%; }
|
||||
.folder-controls { flex: 1 1 320px; justify-content: flex-end; }
|
||||
.folder-controls input { flex: 1 1 160px; min-width: 120px; width: 0; }
|
||||
input:not([type=checkbox]):not([type=range]), button { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||
button { display: inline-flex; align-items: center; gap: 6px; background: var(--rs-bg-elevated); cursor: pointer; }
|
||||
button:hover { background: var(--rs-bg-active); }
|
||||
button[aria-pressed="true"] { border-color: var(--rs-accent); }
|
||||
button :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
|
||||
.picker { max-width: 100%; background: var(--rs-bg); }
|
||||
input[type=number] { width: 88px; }
|
||||
:is(button, input):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||
.actions { display: flex; flex-wrap: wrap; gap: var(--rs-settings-gap); padding: var(--rs-settings-row-padding) 0; }
|
||||
.background-preview { height: 120px; margin-top: var(--rs-settings-row-padding); background-color: var(--rs-bg); background-repeat: no-repeat; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); display: grid; place-items: center; }
|
||||
.background-preview span { padding: 8px 14px; background: var(--rs-bg-elevated); border-radius: var(--rs-control-radius); }
|
||||
.overlay-controls input[type=range] { width: 160px; max-width: 100%; min-width: 0; appearance: none; background: transparent; height: var(--rs-settings-control-height); margin: 0; cursor: pointer; }
|
||||
.overlay-controls input[type=range]::-webkit-slider-runnable-track { height: 6px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); border-radius: var(--rs-control-radius); }
|
||||
.overlay-controls input[type=range]::-webkit-slider-thumb { appearance: none; width: 18px; height: 18px; margin-top: -7px; background: var(--rs-accent); border: 2px solid var(--rs-text-strong); border-radius: 50%; }
|
||||
.overlay-controls input[type=range]::-moz-range-track { height: 4px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); border-radius: var(--rs-control-radius); }
|
||||
.overlay-controls input[type=range]::-moz-range-thumb { width: 14px; height: 14px; background: var(--rs-accent); border: 2px solid var(--rs-text-strong); border-radius: 50%; }
|
||||
.overlay-controls input[type=range]:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; border-radius: var(--rs-control-radius); }
|
||||
.overlay-value { display: flex; align-items: center; gap: 4px; }
|
||||
.overlay-value input { width: 64px; }
|
||||
.targets { display: grid; gap: 2px; min-width: 0; margin: var(--rs-settings-gap) 0 0; padding: var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); }
|
||||
.targets legend { padding: 0 4px; color: var(--rs-text); }
|
||||
.check { display: flex; align-items: center; gap: var(--rs-settings-gap); min-height: var(--rs-settings-control-height); overflow-wrap: anywhere; }
|
||||
.check input { flex-shrink: 0; accent-color: var(--rs-accent); }
|
||||
[role=alert] { color: var(--rs-error); }
|
||||
</style>
|
||||
@@ -0,0 +1,227 @@
|
||||
<!--
|
||||
The appearance of one image of the folder: fit, position, and overlay. It saves the sidecar file of the folder
|
||||
(`.runestone-backgrounds.json`) only when the file did not change since the read. Then every window reads it again.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { onDestroy, untrack } from "svelte";
|
||||
import { t, tr } from "$lib/i18n";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
||||
import { BACKGROUND_POSITIONS } from "$lib/theme/appearance";
|
||||
import { normalizeLayout, type BackgroundSettings } from "../backgroundSettings";
|
||||
import { folderHost, sendBackgroundCommand } from "./sources";
|
||||
import { imageAppearance, imageFits, imageNames, parseImageSettings, sidecarName, type ImageAppearance, type ImageSettings } from "./imageSettings";
|
||||
|
||||
let { settings }: { settings: BackgroundSettings } = $props();
|
||||
|
||||
let names = $state<string[]>([]);
|
||||
let selected = $state("");
|
||||
let query = $state("");
|
||||
let pickerOpen = $state(false);
|
||||
let draft = $state<ImageAppearance>({ fit: "cover", position: "center", overlay: 0 });
|
||||
let baseline = $state<ImageAppearance>({ fit: "cover", position: "center", overlay: 0 });
|
||||
let saved = $state<ImageSettings>({ schema: 1, images: {} });
|
||||
let source: string | null = null;
|
||||
let url = $state("");
|
||||
let portrait = false;
|
||||
let loaded = $state(false);
|
||||
let busy = $state(false);
|
||||
let status = $state({ text: "", error: false });
|
||||
let generation = 0;
|
||||
let closed = false;
|
||||
let closeMenu = () => {};
|
||||
let trigger: HTMLButtonElement | undefined = $state();
|
||||
let search: HTMLInputElement | undefined = $state();
|
||||
const pickerId = $props.id();
|
||||
|
||||
const filtered = $derived(names.filter(name => name.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase())));
|
||||
const fitLabels = $derived<Record<string, string>>({ cover: $t("Fill"), contain: $t("Fit"), auto: $t("Actual size"), blurred: $t("Full image with blurred fill") });
|
||||
const positionLabels = $derived([$t("Center"), $t("Top left"), $t("Top center"), $t("Top right"), $t("Center left"), $t("Center right"), $t("Bottom left"), $t("Bottom center"), $t("Bottom right")]);
|
||||
const changed = $derived(draft.fit !== baseline.fit || draft.position !== baseline.position || draft.overlay !== baseline.overlay);
|
||||
|
||||
const report = (reason: unknown) => { if (!closed) status = { text: reason instanceof Error ? reason.message : String(reason), error: true }; };
|
||||
|
||||
/** The values that differ from the inherited appearance. Only these go to the file. */
|
||||
function changes(): Partial<ImageAppearance> {
|
||||
return {
|
||||
...(draft.fit !== baseline.fit ? { fit: draft.fit } : {}),
|
||||
...(draft.position !== baseline.position ? { position: draft.position } : {}),
|
||||
...(draft.overlay !== baseline.overlay ? { overlay: draft.overlay } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function load() {
|
||||
const revision = ++generation;
|
||||
loaded = false; pickerOpen = false; names = [];
|
||||
if (url) URL.revokeObjectURL(url);
|
||||
url = "";
|
||||
try {
|
||||
const [text, list] = await Promise.all([folderHost.readSidecar(), folderHost.list()]);
|
||||
if (closed || revision !== generation) return;
|
||||
saved = parseImageSettings(text); source = text;
|
||||
names = imageNames(list);
|
||||
if (!names.includes(selected)) selected = names[0] ?? "";
|
||||
if (selected) await choose(selected);
|
||||
else status = { text: tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files."), error: false };
|
||||
} catch (reason) { report(reason); }
|
||||
}
|
||||
|
||||
async function choose(name: string) {
|
||||
const revision = ++generation;
|
||||
selected = name; loaded = false;
|
||||
if (url) URL.revokeObjectURL(url);
|
||||
url = "";
|
||||
try {
|
||||
const next = URL.createObjectURL(await folderHost.read(name));
|
||||
try {
|
||||
const image = new Image(); image.src = next; await image.decode();
|
||||
if (closed || revision !== generation) { URL.revokeObjectURL(next); return; }
|
||||
portrait = image.naturalHeight > image.naturalWidth;
|
||||
} catch (error) { URL.revokeObjectURL(next); throw error; }
|
||||
url = next;
|
||||
draft = imageAppearance(normalizeLayout(settings), saved.images[name], portrait);
|
||||
baseline = { ...draft };
|
||||
loaded = true;
|
||||
status = { text: saved.images[name] ? tr("Saved appearance.") : tr("Default appearance."), error: false };
|
||||
} catch (reason) { report(reason); }
|
||||
}
|
||||
|
||||
/** A change of the folder layout changes the inherited values. Keep the edits of the user. */
|
||||
function inherit() {
|
||||
if (!loaded) return;
|
||||
const next = imageAppearance(normalizeLayout(settings), saved.images[selected], portrait);
|
||||
if (next.fit === baseline.fit && next.position === baseline.position && next.overlay === baseline.overlay) return;
|
||||
const edited = changes();
|
||||
baseline = next;
|
||||
draft = { ...next, ...edited };
|
||||
}
|
||||
|
||||
async function write(reset: boolean) {
|
||||
if (!loaded || busy) return;
|
||||
const edited = changes();
|
||||
if (!reset && !Object.keys(edited).length) return;
|
||||
busy = true;
|
||||
const revision = generation, name = selected;
|
||||
try {
|
||||
const next = structuredClone($state.snapshot(saved)) as ImageSettings;
|
||||
if (reset) delete next.images[name]; else next.images[name] = { ...next.images[name], ...edited };
|
||||
const contents = JSON.stringify(next, null, 2) + "\n";
|
||||
await folderHost.writeSidecar(contents, source);
|
||||
if (closed || revision !== generation) return;
|
||||
source = contents; saved = next;
|
||||
draft = imageAppearance(normalizeLayout(settings), saved.images[name], portrait);
|
||||
baseline = { ...draft };
|
||||
status = { text: reset ? tr("Default appearance restored.") : tr("Image appearance saved."), error: false };
|
||||
await sendBackgroundCommand("reload");
|
||||
} catch (reason) { report(reason); }
|
||||
finally { busy = false; }
|
||||
}
|
||||
|
||||
function menu(event: MouseEvent, field: "fit" | "position") {
|
||||
closeMenu();
|
||||
const anchor = event.currentTarget as HTMLButtonElement;
|
||||
const bounds = anchor.getBoundingClientRect();
|
||||
const values: readonly string[] = field === "fit" ? imageFits : BACKGROUND_POSITIONS;
|
||||
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: field === "fit" ? $t("Image fit") : $t("Position of this image"), parent: anchor.closest("dialog") ?? undefined,
|
||||
items: values.map((value, index) => ({ label: field === "fit" ? fitLabels[value] : positionLabels[index], radio: true, checked: draft[field] === value,
|
||||
run: () => { draft = { ...draft, [field]: value }; } })) }).close;
|
||||
}
|
||||
|
||||
function overlay(input: HTMLInputElement) {
|
||||
if (input.validity.valid && Number.isFinite(input.valueAsNumber)) draft = { ...draft, overlay: Math.round(Math.max(-100, Math.min(100, input.valueAsNumber))) / 100 };
|
||||
}
|
||||
|
||||
function openPicker() {
|
||||
if (pickerOpen) { pickerOpen = false; return; }
|
||||
query = ""; pickerOpen = true;
|
||||
queueMicrotask(() => search?.focus());
|
||||
}
|
||||
|
||||
function pick(name: string) {
|
||||
pickerOpen = false;
|
||||
void choose(name).then(() => trigger?.focus());
|
||||
}
|
||||
|
||||
function moveFocus(event: KeyboardEvent, list: HTMLElement) {
|
||||
const rows = [...list.querySelectorAll<HTMLButtonElement>("button")];
|
||||
if (!rows.length) return;
|
||||
const index = rows.indexOf(document.activeElement as HTMLButtonElement);
|
||||
const next = event.key === "Home" ? 0 : event.key === "End" ? rows.length - 1 : index < 0 ? (event.key === "ArrowDown" ? 0 : rows.length - 1) : Math.max(0, Math.min(rows.length - 1, index + (event.key === "ArrowDown" ? 1 : -1)));
|
||||
event.preventDefault();
|
||||
rows[next].focus();
|
||||
}
|
||||
|
||||
$effect(() => { void settings.size; void settings.position; void settings.overlay; untrack(inherit); });
|
||||
void load();
|
||||
onDestroy(() => { closed = true; generation++; closeMenu(); if (url) URL.revokeObjectURL(url); });
|
||||
</script>
|
||||
|
||||
<details class="image-editor">
|
||||
<summary>{$t("Per-image appearance")}</summary>
|
||||
<p>{$t("Choose an image to change its fit, position, and overlay. Portrait images show in full over a blurred fill by default.")}</p>
|
||||
<fieldset disabled={busy}>
|
||||
<div class="row"><span>{$t("Image")}</span>
|
||||
<button bind:this={trigger} class="choice" aria-label={$t("Image to change")} aria-expanded={pickerOpen} aria-controls={pickerId} disabled={!names.length} onclick={openPicker}>
|
||||
<span class="name">{selected || $t("Choose an image")}</span><Icon icon="chevron-down" /></button></div>
|
||||
{#if pickerOpen}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions (Escape closes the picker.) -->
|
||||
<div id={pickerId} class="rs-picker image-picker" onkeydown={event => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); pickerOpen = false; trigger?.focus(); } }}>
|
||||
<input bind:this={search} type="search" aria-label={$t("Find an image")} placeholder={$t("Find an image")} bind:value={query}
|
||||
onkeydown={event => { if (event.key === "ArrowDown" || event.key === "ArrowUp") moveFocus(event, event.currentTarget.nextElementSibling as HTMLElement); else if (event.key === "Enter" && filtered[0]) { event.preventDefault(); pick(filtered[0]); } }} />
|
||||
<div class="options" role="listbox" aria-label={$t("Image files")} tabindex="-1"
|
||||
onkeydown={event => { if (["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) moveFocus(event, event.currentTarget); }}>
|
||||
{#each filtered.slice(0, 100) as name (name)}
|
||||
<button class="rs-picker-row" role="option" tabindex="-1" aria-selected={name === selected} onclick={() => pick(name)}>{name}</button>
|
||||
{/each}
|
||||
</div>
|
||||
<p role="status">{!filtered.length ? $t("No matching images.") : filtered.length > 100 ? $t("{count} matches. Type more of the name to see other images.", { count: filtered.length }) : $t(filtered.length === 1 ? "{count} image." : "{count} images.", { count: filtered.length })}</p>
|
||||
</div>
|
||||
{/if}
|
||||
<div class="preview" role="img" aria-label={selected ? $t("Selected image preview: {name}", { name: selected }) : $t("Selected image preview")}>
|
||||
{#if url}
|
||||
{#if draft.fit === "blurred"}<span class="fill" style:background-image={`url("${url}")`}></span>{/if}
|
||||
<span class="foreground" style:background-image={`url("${url}")`} style:background-size={draft.fit === "blurred" ? "contain" : draft.fit} style:background-position={draft.position}></span>
|
||||
{/if}
|
||||
<span class="shade" style:background={draft.overlay < 0 ? "white" : "black"} style:opacity={String(Math.abs(draft.overlay))}></span>
|
||||
</div>
|
||||
<div class="row"><span>{$t("Fit")}</span><button class="choice" aria-label={$t("Image fit")} aria-haspopup="menu" disabled={!loaded} onclick={event => menu(event, "fit")}>{fitLabels[draft.fit]}<Icon icon="chevron-down" /></button></div>
|
||||
<div class="row"><span>{$t("Position")}</span><button class="choice" aria-label={$t("Position of this image")} aria-haspopup="menu" disabled={!loaded} onclick={event => menu(event, "position")}>{positionLabels[BACKGROUND_POSITIONS.indexOf(draft.position)]}<Icon icon="chevron-down" /></button></div>
|
||||
<div class="row"><span>{$t("Overlay")}</span><div class="controls">
|
||||
<input type="range" min="-100" max="100" aria-label={$t("Overlay of this image")} disabled={!loaded} value={Math.round(draft.overlay * 100)} oninput={event => overlay(event.currentTarget)} />
|
||||
<input type="number" min="-100" max="100" step="1" required aria-label={$t("Overlay percentage of this image")} disabled={!loaded} value={Math.round(draft.overlay * 100)} oninput={event => overlay(event.currentTarget)} /><span>%</span>
|
||||
</div></div>
|
||||
<div class="controls">
|
||||
<button disabled={!loaded || !changed} onclick={() => void write(false)}><Icon icon="save" />{$t("Save image appearance")}</button>
|
||||
<button disabled={!loaded || !saved.images[selected]} onclick={() => void write(true)}><Icon icon="undo" />{$t("Reset image appearance")}</button>
|
||||
<button onclick={() => void load()}><Icon icon="refresh" />{$t("Reload image settings")}</button>
|
||||
</div>
|
||||
</fieldset>
|
||||
{#if status.text}<p role={status.error ? "alert" : "status"} class:error={status.error}>{status.text}</p>{/if}
|
||||
</details>
|
||||
|
||||
<style>
|
||||
.image-editor { display: grid; gap: var(--rs-settings-gap); min-width: 0; padding: var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); }
|
||||
summary { cursor: pointer; min-height: var(--rs-settings-control-height); line-height: var(--rs-settings-control-height); border-radius: var(--rs-control-radius); }
|
||||
p { margin: 0; color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); line-height: 1.5; overflow-wrap: anywhere; }
|
||||
.error { color: var(--rs-error); }
|
||||
fieldset { display: grid; gap: var(--rs-settings-gap); min-width: 0; margin: var(--rs-settings-gap) 0 0; padding: 0; border: 0; }
|
||||
.row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; }
|
||||
.controls { display: flex; align-items: center; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; }
|
||||
button:not(.rs-picker-row), input:not([type=range]) { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||
button:not(.rs-picker-row) { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; }
|
||||
button:not(.rs-picker-row):hover:not(:disabled) { background: var(--rs-bg-active); }
|
||||
button:disabled, input:disabled { opacity: .55; cursor: default; }
|
||||
button :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
|
||||
:is(button, input, summary):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||
.choice { max-width: 100%; min-width: 0; }
|
||||
.choice .name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
input[type=number] { width: 72px; }
|
||||
input[type=range] { width: 160px; max-width: 100%; accent-color: var(--rs-accent); }
|
||||
.image-picker { display: grid; gap: var(--rs-settings-gap); width: 100%; min-width: 0; position: static; }
|
||||
.image-picker input { width: 100%; min-width: 0; }
|
||||
.options { display: grid; gap: 2px; max-height: 220px; overflow: auto; min-width: 0; }
|
||||
.options button { justify-content: flex-start; text-align: left; overflow-wrap: anywhere; }
|
||||
.preview { position: relative; width: 100%; height: 170px; overflow: hidden; border-radius: var(--rs-control-radius); background-color: var(--rs-bg-active); }
|
||||
.fill, .foreground, .shade { position: absolute; inset: 0; background-repeat: no-repeat; pointer-events: none; }
|
||||
.fill { inset: -24px; filter: blur(18px); background-size: cover; background-position: center; }
|
||||
</style>
|
||||
@@ -0,0 +1,83 @@
|
||||
// The blurred fill of a portrait image. One worker does the decode, the resize, and the filter away from the
|
||||
// input and paint work of the window. It lives as long as the Background instance.
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
|
||||
const workerSource = `
|
||||
self.onmessage = async ({ data: { id, url, width, height } }) => {
|
||||
let image;
|
||||
try {
|
||||
const source = await (await fetch(url)).blob();
|
||||
image = await createImageBitmap(source, { resizeWidth: width, resizeHeight: height, resizeQuality: 'high' });
|
||||
const canvas = new OffscreenCanvas(width, height);
|
||||
const context = canvas.getContext('2d');
|
||||
context.filter = 'blur(24px)';
|
||||
context.drawImage(image, -48, -48, width + 96, height + 96);
|
||||
self.postMessage({ id, blob: await canvas.convertToBlob({ type: 'image/png' }) });
|
||||
} catch (error) {
|
||||
self.postMessage({ id, error: error instanceof Error ? error.message : String(error) });
|
||||
} finally { image?.close(); }
|
||||
};`;
|
||||
|
||||
/** The size of the blurred copy. Its long side is at most 1024 pixels. */
|
||||
export function blurSize(width: number, height: number): { width: number; height: number } {
|
||||
const scale = Math.min(1, 1024 / Math.max(width, height, 1));
|
||||
return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) };
|
||||
}
|
||||
|
||||
export class BlurWorker {
|
||||
private worker?: Worker;
|
||||
private workerUrl?: string;
|
||||
private serial = 0;
|
||||
private pending = new Map<number, { resolve: (blob: Blob) => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> }>();
|
||||
|
||||
/** A blob URL of the blurred copy of the image at `url`. The caller releases it. */
|
||||
async blur(url: string, width: number, height: number): Promise<string> {
|
||||
const size = blurSize(width, height);
|
||||
if (typeof Worker === "undefined" || typeof OffscreenCanvas === "undefined") return URL.createObjectURL(await this.inWindow(url, size));
|
||||
const worker = this.start();
|
||||
const id = ++this.serial;
|
||||
const blob = await new Promise<Blob>((resolve, reject) => {
|
||||
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(tr("The blurred image took too long to load."))); }, 10000);
|
||||
this.pending.set(id, { resolve, reject, timer });
|
||||
worker.postMessage({ id, url, ...size });
|
||||
});
|
||||
return URL.createObjectURL(blob);
|
||||
}
|
||||
|
||||
private start(): Worker {
|
||||
if (this.worker) return this.worker;
|
||||
this.workerUrl = URL.createObjectURL(new Blob([workerSource], { type: "text/javascript" }));
|
||||
const worker = this.worker = new Worker(this.workerUrl);
|
||||
worker.onmessage = ({ data }) => {
|
||||
const request = this.pending.get(data?.id);
|
||||
if (!request) return;
|
||||
this.pending.delete(data.id); clearTimeout(request.timer);
|
||||
if (data.blob instanceof Blob) request.resolve(data.blob);
|
||||
else request.reject(new Error(data.error || tr("Cannot create the blurred image.")));
|
||||
};
|
||||
worker.onerror = () => this.fail(new Error(tr("Cannot create the blurred image.")));
|
||||
return worker;
|
||||
}
|
||||
|
||||
/** A fallback for a window without OffscreenCanvas. */
|
||||
private async inWindow(url: string, size: { width: number; height: number }): Promise<Blob> {
|
||||
const image = new Image(); image.src = url; await image.decode();
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = size.width; canvas.height = size.height;
|
||||
const context = canvas.getContext("2d")!;
|
||||
context.filter = "blur(24px)";
|
||||
context.drawImage(image, -48, -48, size.width + 96, size.height + 96);
|
||||
return new Promise<Blob>((resolve, reject) => canvas.toBlob(value => value ? resolve(value) : reject(new Error(tr("Cannot create the blurred image."))), "image/png"));
|
||||
}
|
||||
|
||||
private fail(error: Error) {
|
||||
for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
|
||||
this.pending.clear();
|
||||
// A failed worker starts again at the next request.
|
||||
this.worker?.terminate(); this.worker = undefined;
|
||||
if (this.workerUrl) URL.revokeObjectURL(this.workerUrl);
|
||||
this.workerUrl = undefined;
|
||||
}
|
||||
|
||||
dispose() { this.fail(new Error(tr("This feature is off."))); }
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
// 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<string[]>;
|
||||
read(name: string): Promise<Blob>;
|
||||
/** The text of the sidecar file, or null. */
|
||||
sidecar(): Promise<string | null>;
|
||||
}
|
||||
|
||||
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<LoadedImage>;
|
||||
/** Make the blurred fill of a loaded image. The engine releases the URL. */
|
||||
blur(image: LoadedImage): Promise<string>;
|
||||
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<string>();
|
||||
/** The blurred fills, oldest first. */
|
||||
private blurs = new Map<string, string>();
|
||||
private prepared: { name: string; work: Promise<Prepared | null>; 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<void> {
|
||||
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<void> {
|
||||
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<Prepared | null> {
|
||||
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<Prepared | null>; discarded: boolean } = { name, work: Promise.resolve(null), discarded: false };
|
||||
entry.work = (async (): Promise<Prepared | null> => {
|
||||
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<string> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// The per-image settings: the sidecar file `.runestone-backgrounds.json` in the image folder.
|
||||
// The Background Slideshow plugin used the same file, so the settings of each image stay.
|
||||
import { BACKGROUND_POSITIONS } from "../../theme/appearance.ts";
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import type { BackgroundLayout, BackgroundPosition } from "../backgroundSettings.ts";
|
||||
|
||||
export const sidecarName = ".runestone-backgrounds.json";
|
||||
/** `blurred` shows the full image over a blurred copy that fills the view. Portrait images use it by default. */
|
||||
export const imageFits = ["cover", "contain", "auto", "blurred"] as const;
|
||||
export type ImageFit = typeof imageFits[number];
|
||||
export interface ImageAppearance { fit: ImageFit; position: BackgroundPosition; overlay: number }
|
||||
/** Unknown keys of the file and of each image stay when RuneStone saves the file. */
|
||||
export interface ImageSettings { schema: 1; images: Record<string, Partial<ImageAppearance>>; [key: string]: unknown }
|
||||
|
||||
/** Read the sidecar text. `null` (no file) gives empty settings. Invalid settings throw an error. */
|
||||
export function parseImageSettings(source: string | null): ImageSettings {
|
||||
if (source === null) return { schema: 1, images: {} };
|
||||
const value = JSON.parse(source);
|
||||
if (!value || value.schema !== 1 || !value.images || typeof value.images !== "object" || Array.isArray(value.images)) {
|
||||
throw new Error(tr("The image settings file must use schema 1 and an images object."));
|
||||
}
|
||||
for (const [name, raw] of Object.entries(value.images)) {
|
||||
const appearance = raw as Partial<ImageAppearance>;
|
||||
if (!name || /[\\/]/.test(name) || !appearance || typeof appearance !== "object" || Array.isArray(appearance)
|
||||
|| ("fit" in appearance && !imageFits.includes(appearance.fit!))
|
||||
|| ("position" in appearance && !BACKGROUND_POSITIONS.includes(appearance.position!))
|
||||
|| ("overlay" in appearance && (typeof appearance.overlay !== "number" || !Number.isFinite(appearance.overlay) || Math.abs(appearance.overlay) > 1))) {
|
||||
throw new Error(tr("Invalid image settings for {name}.", { name }));
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/** The appearance of one image: the folder layout, the portrait default, then the saved values of the image. */
|
||||
export function imageAppearance(layout: BackgroundLayout, override: Partial<ImageAppearance> | undefined, portrait: boolean): ImageAppearance {
|
||||
return { fit: portrait ? "blurred" : layout.size, position: layout.position, overlay: layout.overlay, ...override };
|
||||
}
|
||||
|
||||
/** The supported image names, without duplicates, in natural order. */
|
||||
export function imageNames(names: readonly string[]): string[] {
|
||||
return [...new Set(names.filter(name => !/[\\/]/.test(name) && /\.(png|jpe?g|gif|webp)$/i.test(name)))]
|
||||
.sort((a, b) => a.localeCompare(b, "en", { numeric: true, sensitivity: "base" }) || a.localeCompare(b, "en"));
|
||||
}
|
||||
|
||||
/** The order of the next images after `current`. A random order puts the current image last. */
|
||||
export function sequence(names: readonly string[], current: string | null, order: "name" | "random", random = Math.random): string[] {
|
||||
if (order === "name") {
|
||||
const index = current === null ? -1 : names.indexOf(current);
|
||||
return [...names.slice(index + 1), ...names.slice(0, index + 1)];
|
||||
}
|
||||
const rest = names.filter(name => name !== current);
|
||||
for (let i = rest.length - 1; i > 0; i--) {
|
||||
const j = Math.min(i, Math.max(0, Math.floor(random() * (i + 1))));
|
||||
[rest[i], rest[j]] = [rest[j], rest[i]];
|
||||
}
|
||||
return current && names.includes(current) ? [...rest, current] : rest;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// The Background feature. `loader.ts` imports this module when a folder or an image is selected (`launch.ts`),
|
||||
// at a palette command, or when Appearance → Background shows its settings.
|
||||
// It shows the images through `backgroundHub`, so the workarea, browser tabs, and Project Management boards get the frames.
|
||||
import { mount, unmount } from "svelte";
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import { backgroundHub } from "../../plugins/backgrounds.ts";
|
||||
import { readAppearance } from "../../theme/appearance.ts";
|
||||
import { hasImage, normalizeLayout, onBackgroundChange, readBackground, writeBackground } from "../backgroundSettings.ts";
|
||||
import type { FeatureContext, FeatureInstance } from "../types.ts";
|
||||
import { BlurWorker } from "./blur.ts";
|
||||
import { Slideshow, type ImageSource } from "./engine.ts";
|
||||
import { browserRuntime, folderHost, folderSource, imageSource, onBackgroundCommand, sendBackgroundCommand } from "./sources.ts";
|
||||
import BackgroundSettings from "./BackgroundSettings.svelte";
|
||||
|
||||
export function start(_context: FeatureContext): FeatureInstance {
|
||||
const owner = Symbol("background");
|
||||
const blur = new BlurWorker();
|
||||
const engine = new Slideshow({ set: (target, frame) => backgroundHub.set(owner, target, frame) }, browserRuntime(blur));
|
||||
/** The host folder for display. `undefined` until the first read. */
|
||||
let folder: string | null | undefined;
|
||||
let generation = 0;
|
||||
let disposed = false;
|
||||
/** The last source and settings. A change of another appearance setting, such as the theme, gives the same value. */
|
||||
let applied = "";
|
||||
|
||||
/** Give the engine the current source and settings. `reread` asks the host for its folder again. */
|
||||
async function apply(reread: boolean) {
|
||||
const run = ++generation;
|
||||
const settings = readBackground();
|
||||
const appearance = readAppearance();
|
||||
let source: ImageSource | null = null;
|
||||
let layout = normalizeLayout(settings);
|
||||
if (settings.source === "folder") {
|
||||
if (reread || folder === undefined) {
|
||||
try { folder = await folderHost.current(); } catch { folder = null; }
|
||||
if (disposed || run !== generation) return;
|
||||
}
|
||||
source = folder ? folderSource(folder) : null;
|
||||
} else if (settings.source === "image" && hasImage(appearance)) {
|
||||
source = imageSource(appearance.newTabBackground!);
|
||||
layout = normalizeLayout(appearance.newTabBackground);
|
||||
}
|
||||
const next = { ...settings, ...layout };
|
||||
const signature = JSON.stringify([source?.key ?? null, next]);
|
||||
if (!reread && signature === applied) return;
|
||||
applied = signature;
|
||||
await engine.configure(source, next);
|
||||
}
|
||||
|
||||
const stopSettings = onBackgroundChange(() => { void apply(false); });
|
||||
const stopCommands = onBackgroundCommand(command => {
|
||||
if (command === "next") void engine.next();
|
||||
else { engine.invalidate(); void apply(true); }
|
||||
});
|
||||
// Another window or program can change the folder. A focus reads the folder, the list, and the sidecar again.
|
||||
const focus = () => { engine.invalidate(); void apply(true); };
|
||||
window.addEventListener("focus", focus);
|
||||
void apply(true);
|
||||
|
||||
return {
|
||||
mount() { throw new Error(tr("This view is unavailable.")); },
|
||||
async run(command) {
|
||||
if (command === "next") await sendBackgroundCommand("next");
|
||||
else if (command === "pause") {
|
||||
const settings = readBackground();
|
||||
await writeBackground({ ...settings, paused: !settings.paused });
|
||||
} else throw new Error(tr("This command is unavailable."));
|
||||
},
|
||||
dispose() {
|
||||
disposed = true; generation++;
|
||||
stopSettings(); stopCommands();
|
||||
window.removeEventListener("focus", focus);
|
||||
engine.dispose();
|
||||
blur.dispose();
|
||||
backgroundHub.removeOwner(owner);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The settings of Appearance → Background. They work also in a window where Background does not run. */
|
||||
export function mountSettings(element: HTMLElement) {
|
||||
const component = mount(BackgroundSettings, { target: element });
|
||||
return () => { void unmount(component); };
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
// The image sources of Background, the host folder commands (`src-tauri/src/backgrounds.rs`), the browser runtime of the
|
||||
// engine, and the commands that reach the Background instance of every window.
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import { emit, listen } from "@tauri-apps/api/event";
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import { readBackgroundImage } from "../../theme/backgroundImages.ts";
|
||||
import type { Appearance } from "../../theme/appearance.ts";
|
||||
import type { BlurWorker } from "./blur.ts";
|
||||
import type { ImageSource, LoadedImage, Runtime } from "./engine.ts";
|
||||
|
||||
const types: Record<string, string> = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp" };
|
||||
const typeOf = (name: string) => types[name.split(".").pop()!.toLowerCase()] ?? "application/octet-stream";
|
||||
|
||||
/** The host commands of the image folder. The host keeps the folder, so no command takes a path. */
|
||||
export const folderHost = {
|
||||
/** Show the folder dialog. Returns the chosen folder for display, or null after Cancel. */
|
||||
choose: (title: string) => invoke<string | null>("background_choose_folder", { title }),
|
||||
/** The current folder for display, or null. */
|
||||
current: () => invoke<string | null>("background_folder"),
|
||||
clear: () => invoke<void>("background_clear_folder"),
|
||||
list: () => invoke<string[]>("background_list"),
|
||||
read: async (name: string): Promise<Blob> => {
|
||||
const bytes = await invoke<ArrayBuffer | Uint8Array | number[]>("background_read", { name });
|
||||
return new Blob([bytes instanceof ArrayBuffer ? bytes : Uint8Array.from(bytes)], { type: typeOf(name) });
|
||||
},
|
||||
readSidecar: () => invoke<string | null>("background_read_sidecar"),
|
||||
writeSidecar: (contents: string, expected: string | null) => invoke<void>("background_write_sidecar", { contents, expected }),
|
||||
};
|
||||
|
||||
/** The images of the host folder. `folder` is the path for display. It makes the key, so another folder starts again. */
|
||||
export function folderSource(folder: string): ImageSource {
|
||||
return { key: `folder:${folder}`, timed: true, list: folderHost.list, read: folderHost.read, sidecar: folderHost.readSidecar };
|
||||
}
|
||||
|
||||
/** The saved image of Appearance, from IndexedDB or from an old data URL. */
|
||||
export async function readSavedImage(background: NonNullable<Appearance["newTabBackground"]>): Promise<Blob> {
|
||||
if (background.imageId) {
|
||||
const blob = await readBackgroundImage(background.imageId);
|
||||
if (!blob) throw new Error(tr("The saved background image is missing. Choose the image again."));
|
||||
return blob;
|
||||
}
|
||||
const image = background.image ?? "";
|
||||
const [header, data] = image.split(",");
|
||||
const bytes = Uint8Array.from(atob(data ?? ""), character => character.charCodeAt(0));
|
||||
return new Blob([bytes], { type: header.slice(5, header.indexOf(";")) });
|
||||
}
|
||||
|
||||
/** A short hash of a data URL, so that another old image gets another key. */
|
||||
function hash(text: string): string {
|
||||
let value = 0x811c9dc5;
|
||||
for (let index = 0; index < text.length; index++) value = Math.imul(value ^ text.charCodeAt(index), 0x01000193);
|
||||
return (value >>> 0).toString(16);
|
||||
}
|
||||
|
||||
/** The one saved image. It has no timer. */
|
||||
export function imageSource(background: NonNullable<Appearance["newTabBackground"]>): ImageSource {
|
||||
const id = background.imageId ?? `data:${background.image?.length ?? 0}:${hash(background.image ?? "")}`;
|
||||
return { key: `image:${id}`, timed: false, list: async () => ["image"], read: () => readSavedImage(background), sidecar: async () => null };
|
||||
}
|
||||
|
||||
/** Make a blob URL and decode the image before it shows, so the fade does not wait for the decode. */
|
||||
export async function loadImage(blob: Blob): Promise<LoadedImage> {
|
||||
const url = URL.createObjectURL(blob);
|
||||
try {
|
||||
const image = new Image();
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
image.src = url;
|
||||
await Promise.race([image.decode(), new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(tr("The image took too long to load."))), 10000); })])
|
||||
.finally(() => clearTimeout(timer));
|
||||
return { url, width: image.naturalWidth, height: image.naturalHeight };
|
||||
} catch (error) { URL.revokeObjectURL(url); throw error; }
|
||||
}
|
||||
|
||||
export function browserRuntime(blur: BlurWorker): Runtime {
|
||||
return {
|
||||
load: loadImage,
|
||||
blur: image => blur.blur(image.url, image.width, image.height),
|
||||
release: url => URL.revokeObjectURL(url),
|
||||
later: (callback, milliseconds) => setTimeout(callback, milliseconds),
|
||||
cancel: timer => clearTimeout(timer as ReturnType<typeof setTimeout>),
|
||||
random: Math.random,
|
||||
now: () => Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
/** `next` shows the next image. `reload` reads the folder, the list, and the sidecar again. */
|
||||
export type BackgroundCommand = "next" | "reload";
|
||||
const EVENT = "background-command";
|
||||
|
||||
/** Send a command to the Background instance of every window, this window too. */
|
||||
export async function sendBackgroundCommand(command: BackgroundCommand): Promise<void> {
|
||||
if (isTauri()) await emit(EVENT, command);
|
||||
else window.dispatchEvent(new CustomEvent(EVENT, { detail: command }));
|
||||
}
|
||||
|
||||
/** Receive the commands of every window. Returns the function that stops it. */
|
||||
export function onBackgroundCommand(listener: (command: BackgroundCommand) => void): () => void {
|
||||
const accept = (value: unknown) => { if (value === "next" || value === "reload") listener(value); };
|
||||
if (!isTauri()) {
|
||||
const handle = (event: Event) => accept((event as CustomEvent).detail);
|
||||
window.addEventListener(EVENT, handle);
|
||||
return () => window.removeEventListener(EVENT, handle);
|
||||
}
|
||||
let stopped = false;
|
||||
let off: (() => void) | undefined;
|
||||
void listen<unknown>(EVENT, event => accept(event.payload)).then(unlisten => { if (stopped) unlisten(); else off = unlisten; }, () => undefined);
|
||||
return () => { stopped = true; off?.(); };
|
||||
}
|
||||
Reference in New Issue
Block a user