From c09a23f2ad81f5ea46d6e1df5f766b6a80ef0d07 Mon Sep 17 00:00:00 2001 From: Marcel Michau <7761114+MarcelMichau@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:16:24 +0200 Subject: [PATCH 1/5] feat(rewrite) rewrite on modern node with per-monitor wallpapers replace trianglify, wallpaper and minimist with maintained delaunator + chroma-js render triangles with a 2x supersampled scanline fill and encode png with node zlib generate one wallpaper per monitor at its native resolution set wallpapers via IDesktopWallpaper on windows and NSWorkspace (JXA) on macos derive all random choices from the seed and print it so wallpapers can be recreated accept colorbrewer palette names for --colors and validate all flags store wallpapers in the app data folder and remove the previous run's files add node:test suite require node >= 22.2 and bump package major version Co-Authored-By: Claude Opus 5.5 --- README.md | 44 ++++++++------ cli.mjs | 118 ++++++++++++++++++++++++------------ lib/generate.mjs | 122 ++++++++++++++++++++++++++++++++++++++ lib/options.mjs | 91 ++++++++++++++++++++++++++++ lib/png.mjs | 48 +++++++++++++++ lib/random.mjs | 52 ++++++++++++++++ lib/wallpaper/index.mjs | 30 ++++++++++ lib/wallpaper/macos.mjs | 64 ++++++++++++++++++++ lib/wallpaper/windows.mjs | 119 +++++++++++++++++++++++++++++++++++++ package-lock.json | 41 +++++++++++++ package.json | 30 +++++++--- test/generate.test.mjs | 45 ++++++++++++++ test/options.test.mjs | 52 ++++++++++++++++ test/png.test.mjs | 47 +++++++++++++++ 14 files changed, 838 insertions(+), 65 deletions(-) create mode 100644 lib/generate.mjs create mode 100644 lib/options.mjs create mode 100644 lib/png.mjs create mode 100644 lib/random.mjs create mode 100644 lib/wallpaper/index.mjs create mode 100644 lib/wallpaper/macos.mjs create mode 100644 lib/wallpaper/windows.mjs create mode 100644 package-lock.json create mode 100644 test/generate.test.mjs create mode 100644 test/options.test.mjs create mode 100644 test/png.test.mjs diff --git a/README.md b/README.md index b401b6c..cd782d1 100644 --- a/README.md +++ b/README.md @@ -8,13 +8,13 @@ A CLI utility to set algorithmically generated triangle art as your desktop wall --- -Uses the awesome [Trianglify](https://github.com/qrohlf/trianglify) to randomly generate a low-poly triangle art desktop wallpaper: +Randomly generates a low-poly triangle art wallpaper for each of your monitors, at each monitor's native resolution: ![Preview Image](images/example.png 'Preview Image') ## Install -Requires [Node.js](https://nodejs.org/) >= 14. +Requires [Node.js](https://nodejs.org/) >= 22.2, on Windows 10+ or macOS. ``` $ npm install -g wallangle @@ -28,42 +28,52 @@ $ npm install -g wallangle $ wallangle ``` +Every run prints the seed it used. Pass it back with `--seed` to recreate the same wallpapers. + ### With Config ``` -$ wallangle --width=2560 --height=1440 --variance=0.75 --cellSize=250 --seed=helloworld --colors="#083d77,#ebebd3,#da4167,#f4d35e,#f78764" +$ wallangle --variance=0.75 --cellSize=250 --seed=helloworld --colors="#083d77,#ebebd3,#da4167,#f4d35e,#f78764" ``` ## Flags -These flags set specific options for Trianglify: - -### --width +Flags apply to every monitor. Anything left unset is chosen randomly for each monitor, derived from the seed. -Resolution width of your display. Defaults to `3840`. +### --width / --height -### --height - -Resolution height of your display. Defaults to `2160`. +Image size in pixels. Defaults to each monitor's resolution, so you normally won't need these. ### --variance -Decimal value between 0 and 1 (inclusive), defaults to `Math.random()`. Specify the amount of randomness used when generating triangles. +Decimal value between 0 and 1 (inclusive). Specify the amount of randomness used when generating triangles. 0 gives a regular grid. ### --cellSize -Integer, defaults to `Math.floor(Math.random() * 200 + 40)`. Specify the size of the mesh used to generate triangles. Larger values will result in coarser patterns, smaller values will result in finer patterns. Note that very small values may dramatically increase the runtime of Trianglify. +Integer, at least 10. Defaults to a random value between 40 and 239. Specify the size of the mesh used to generate triangles. Larger values will result in coarser patterns, smaller values will result in finer patterns. ### --seed -Number or string, defaults to `null`. Seeds the random number generator to create repeatable patterns. When set to null, the random number will be seeded with random values from the environment. +Any string or number. Seeds the random number generator to create repeatable patterns. Defaults to a random seed. ### --colors -Comma-separated string of CSS-formatted colors. Defaults to `'random'`. You can use a tool such as [Coolors](https://coolors.co/) to generate color palettes. Example is `--colors="#083d77,#ebebd3,#da4167,#f4d35e,#f78764"` +One of: + +- A comma-separated list of CSS colours, e.g. `--colors="#083d77,#ebebd3,#da4167,#f4d35e,#f78764"`. You can use a tool such as [Coolors](https://coolors.co/) to generate palettes. +- The name of a sequential or diverging [ColorBrewer](https://colorbrewer2.org/) palette, e.g. `--colors=YlGnBu` or `--colors=Spectral`. +- `random` (the default), which picks a ColorBrewer palette. + +## Where wallpapers are stored + +- Windows: `%LOCALAPPDATA%\wallangle` +- macOS: `~/Library/Application Support/wallangle` + +Each run writes new files and removes the previous run's files. On macOS, the wallpaper is set for the current Space on each display. ## Libraries Used -- [Trianglify](https://github.com/qrohlf/trianglify) -- [wallpaper](https://github.com/sindresorhus/wallpaper) -- [minimist](https://github.com/substack/minimist) +- [delaunator](https://github.com/mapbox/delaunator) for triangulation +- [chroma.js](https://github.com/gka/chroma.js) for colour scales and ColorBrewer palettes + +Inspired by the awesome [Trianglify](https://github.com/qrohlf/trianglify). diff --git a/cli.mjs b/cli.mjs index e4b1618..fb8135b 100644 --- a/cli.mjs +++ b/cli.mjs @@ -1,42 +1,82 @@ #!/usr/bin/env node -import parseArgs from 'minimist'; -import Trianglify from 'trianglify'; -import wallpaper from 'wallpaper'; -import fs from 'fs'; - -(async () => { - const parsedArgs = parseArgs(process.argv.slice(2)); - - const screenWidth = parsedArgs.width ?? 3840; - const screenHeight = parsedArgs.height ?? 2160; - const variance = parsedArgs.variance ?? Math.random(); - const cellSize = parsedArgs.cellSize ?? Math.floor(Math.random() * 200 + 40); - const seed = parsedArgs.seed ?? null; - const colors = parsedArgs.colors?.split(',') ?? 'random'; - - const pngURI = Trianglify({ - width: screenWidth, - height: screenHeight, - cell_size: cellSize, - x_colors: colors, - y_colors: 'match_x', - variance, - seed, - }).png(); - - const data = pngURI.substr(pngURI.indexOf('base64') + 7); - - const buffer = new Buffer.from(data, 'base64'); - - const wallpaperFileName = 'wallpaper.png'; - - fs.writeFile(wallpaperFileName, buffer, async () => { - await wallpaper.set(wallpaperFileName); - console.log( - `Wallpaper generated & set with screenWidth: ${screenWidth}, screenHeight: ${screenHeight}, variance: ${variance}, cellSize: ${cellSize}, seed: ${seed} & colors: ${ - Array.isArray(colors) ? colors.join(',') : colors - }.` +import { mkdir, readdir, rm, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { generate, pickPalette } from './lib/generate.mjs'; +import { USAGE, UsageError, parseOptions } from './lib/options.mjs'; +import { encodePng } from './lib/png.mjs'; +import { createRandom, randomSeed } from './lib/random.mjs'; +import { loadPlatform } from './lib/wallpaper/index.mjs'; + +const FILE_PATTERN = /^wallangle-.*\.png$/; + +async function main(args) { + const options = parseOptions(args); + if (options.help) { + console.log(USAGE); + return; + } + + const platform = await loadPlatform(); + const monitors = await platform.listMonitors(); + if (monitors.length === 0) { + throw new Error('No monitors were found.'); + } + + const seed = options.seed ?? randomSeed(); + await mkdir(platform.directory, { recursive: true }); + // macOS and Windows cache wallpapers by path, so every run needs fresh file names. + const stamp = Date.now(); + + const assignments = []; + const summaries = []; + for (const [index, monitor] of monitors.entries()) { + const monitorSeed = index === 0 ? seed : `${seed}:${index}`; + // Separate streams keep the point layout stable when only --variance, --cellSize or --colors change. + const pickParam = createRandom(`${monitorSeed}:params`); + const width = options.width ?? monitor.width; + const height = options.height ?? monitor.height; + const variance = options.variance ?? pickParam(); + const cellSize = options.cellSize ?? Math.floor(pickParam() * 200 + 40); + const palette = options.palette ?? pickPalette(pickParam); + + const image = generate({ + width, + height, + cellSize, + variance, + colors: palette.colors, + random: createRandom(`${monitorSeed}:points`), + }); + + const path = join(platform.directory, `wallangle-${stamp}-${index}.png`); + await writeFile(path, encodePng(image)); + assignments.push({ id: monitor.id, path }); + summaries.push( + ` Monitor ${index + 1}: ${width}x${height}, variance ${variance.toFixed(3)}, cellSize ${cellSize}, colors ${palette.name}` ); - }); -})(); + } + + await platform.setWallpapers(assignments); + + const current = new Set(assignments.map(({ path }) => path)); + for (const file of await readdir(platform.directory)) { + const path = join(platform.directory, file); + if (FILE_PATTERN.test(file) && !current.has(path)) { + await rm(path, { force: true }); + } + } + + console.log(`Wallpaper generated & set with seed ${seed}:\n${summaries.join('\n')}`); + console.log(`Run again with --seed=${seed} to recreate it.`); +} + +main(process.argv.slice(2)).catch((error) => { + if (error instanceof UsageError) { + console.error(`${error.message}\n\n${USAGE}`); + process.exitCode = 2; + } else { + console.error(`wallangle: ${error.message}`); + process.exitCode = 1; + } +}); diff --git a/lib/generate.mjs b/lib/generate.mjs new file mode 100644 index 0000000..52abf58 --- /dev/null +++ b/lib/generate.mjs @@ -0,0 +1,122 @@ +import chroma from 'chroma-js'; +import Delaunator from 'delaunator'; + +// Qualitative ColorBrewer palettes are made of unrelated hues and look muddy as gradients. +const QUALITATIVE = new Set(['Set1', 'Set2', 'Set3', 'Accent', 'Dark2', 'Paired', 'Pastel1', 'Pastel2']); + +/** Names of the ColorBrewer palettes that `random` picks from. */ +export const PALETTE_NAMES = Object.keys(chroma.brewer).filter((name) => !QUALITATIVE.has(name)); + +/** Looks up a palette by name, case-insensitively. */ +export function findPalette(name) { + const match = PALETTE_NAMES.find((candidate) => candidate.toLowerCase() === name.toLowerCase()); + return match && { name: match, colors: chroma.brewer[match] }; +} + +export function pickPalette(random) { + const name = PALETTE_NAMES[Math.floor(random() * PALETTE_NAMES.length)]; + return { name, colors: chroma.brewer[name] }; +} + +/** + * Lays out a grid of points covering the image plus a margin, each nudged by up to + * `variance * cellSize / 2` so the triangulation reaches past every edge. + */ +function createPoints(width, height, cellSize, variance, random) { + const columns = Math.ceil(width / cellSize) + 3; + const rows = Math.ceil(height / cellSize) + 3; + const offsetX = (width - (columns - 1) * cellSize) / 2; + const offsetY = (height - (rows - 1) * cellSize) / 2; + const jitter = variance * cellSize; + + const coords = new Float64Array(columns * rows * 2); + let i = 0; + for (let row = 0; row < rows; row++) { + for (let column = 0; column < columns; column++) { + coords[i++] = offsetX + column * cellSize + (random() - 0.5) * jitter; + coords[i++] = offsetY + row * cellSize + (random() - 0.5) * jitter; + } + } + return coords; +} + +function edgeX(ax, ay, bx, by, y) { + return ax + ((y - ay) * (bx - ax)) / (by - ay); +} + +/** + * Adds a flat-coloured triangle into a 2x supersampled accumulation buffer. + * + * Samples sit at the centres of a grid twice the image resolution; a sample is covered when it + * lies in [top, bottom) and [left, right) of the triangle. Vertices are ordered by (y, x), so two + * triangles sharing an edge evaluate it identically and every sample is covered exactly once. + */ +function fillTriangle(acc, width, height, vertices, r, g, b) { + vertices.sort((p, q) => p[1] - q[1] || p[0] - q[0]); + const [[x0, y0], [x1, y1], [x2, y2]] = vertices; + const sampleWidth = width * 2; + + const rowStart = Math.max(0, Math.ceil(y0 - 0.5)); + const rowEnd = Math.min(height * 2, Math.ceil(y2 - 0.5)); + for (let sy = rowStart; sy < rowEnd; sy++) { + const y = sy + 0.5; + const xLong = edgeX(x0, y0, x2, y2, y); + const xShort = y < y1 ? edgeX(x0, y0, x1, y1, y) : edgeX(x1, y1, x2, y2, y); + const left = Math.min(xLong, xShort); + const right = Math.max(xLong, xShort); + + const columnStart = Math.max(0, Math.ceil(left - 0.5)); + const columnEnd = Math.min(sampleWidth, Math.ceil(right - 0.5)); + const rowOffset = (sy >> 1) * width; + for (let sx = columnStart; sx < columnEnd; sx++) { + const i = (rowOffset + (sx >> 1)) * 3; + acc[i] += r; + acc[i + 1] += g; + acc[i + 2] += b; + } + } +} + +/** + * Generates low-poly triangle art. + * @param {object} options + * @param {number} options.width + * @param {number} options.height + * @param {number} options.cellSize Spacing of the point grid, in pixels. + * @param {number} options.variance 0 (regular grid) to 1 (maximum jitter). + * @param {string[]} options.colors Colours the gradient runs through, in any CSS format chroma-js accepts. + * @param {() => number} options.random + * @returns {{ width: number, height: number, data: Uint8Array }} 8-bit RGB pixels. + */ +export function generate({ width, height, cellSize, variance, colors, random }) { + const points = createPoints(width, height, cellSize, variance, random); + const { triangles } = new Delaunator(points); + + // The same scale runs along x and y; mixing the two gives a diagonal gradient. + const scale = chroma.scale(colors).mode('lab'); + const clamp = (value) => Math.min(1, Math.max(0, value)); + + const acc = new Uint16Array(width * height * 3); + for (let t = 0; t < triangles.length; t += 3) { + const vertices = []; + let centroidX = 0; + let centroidY = 0; + for (let k = 0; k < 3; k++) { + const p = triangles[t + k] * 2; + vertices.push([points[p] * 2, points[p + 1] * 2]); + centroidX += points[p] / 3; + centroidY += points[p + 1] / 3; + } + + const color = chroma.mix(scale(clamp(centroidX / width)), scale(clamp(centroidY / height)), 0.5, 'lab'); + const [r, g, b] = color.rgb(); + fillTriangle(acc, width, height, vertices, r, g, b); + } + + // Each pixel received exactly four samples; average them. + const data = new Uint8Array(acc.length); + for (let i = 0; i < acc.length; i++) { + data[i] = (acc[i] + 2) >> 2; + } + return { width, height, data }; +} diff --git a/lib/options.mjs b/lib/options.mjs new file mode 100644 index 0000000..72f8142 --- /dev/null +++ b/lib/options.mjs @@ -0,0 +1,91 @@ +import { parseArgs } from 'node:util'; +import chroma from 'chroma-js'; +import { findPalette } from './generate.mjs'; + +export const USAGE = `Usage: wallangle [options] + +Generates low-poly triangle art and sets it as the wallpaper on every monitor. + +Options: + --width= Image width. Defaults to each monitor's resolution. + --height= Image height. Defaults to each monitor's resolution. + --variance=<0-1> Randomness of the triangles. Random by default. + --cellSize= Size of the triangle grid (min 10). Random (40-239) by default. + --seed= Seed for repeatable patterns. Random by default. + --colors= Comma-separated CSS colours, a ColorBrewer palette name, or "random" (default). + -h, --help Show this message.`; + +export class UsageError extends Error {} + +function number(name, value, { min, max, integer = false }) { + const parsed = Number(value); + const valid = + value.trim() !== '' && + Number.isFinite(parsed) && + (!integer || Number.isInteger(parsed)) && + (min === undefined || parsed >= min) && + (max === undefined || parsed <= max); + if (!valid) { + const kind = integer ? 'an integer' : 'a number'; + const range = max === undefined ? `>= ${min}` : `between ${min} and ${max}`; + throw new UsageError(`--${name} must be ${kind} ${range}, got "${value}".`); + } + return parsed; +} + +// Splits on commas that are not inside parentheses, so "rgb(1, 2, 3),#fff" stays two colours. +function parseColors(value) { + const list = value + .split(/,(?![^(]*\))/) + .map((color) => color.trim()) + .filter(Boolean); + + if (list.length === 0 || (list.length === 1 && list[0].toLowerCase() === 'random')) { + return undefined; + } + if (list.length === 1) { + const palette = findPalette(list[0]); + if (palette) return palette; + } + + const invalid = list.filter((color) => !chroma.valid(color)); + if (invalid.length > 0) { + throw new UsageError(`--colors contains invalid colours: ${invalid.join(', ')}.`); + } + return { name: list.join(','), colors: list }; +} + +/** + * Parses command line arguments. Options left unset are `undefined` and are chosen per monitor. + * @param {string[]} args + */ +export function parseOptions(args) { + let values; + try { + ({ values } = parseArgs({ + args, + options: { + width: { type: 'string' }, + height: { type: 'string' }, + variance: { type: 'string' }, + cellSize: { type: 'string' }, + seed: { type: 'string' }, + colors: { type: 'string' }, + help: { type: 'boolean', short: 'h' }, + }, + strict: true, + })); + } catch (error) { + throw new UsageError(error.message); + } + + return { + help: values.help ?? false, + width: values.width === undefined ? undefined : number('width', values.width, { min: 1, integer: true }), + height: values.height === undefined ? undefined : number('height', values.height, { min: 1, integer: true }), + variance: values.variance === undefined ? undefined : number('variance', values.variance, { min: 0, max: 1 }), + cellSize: values.cellSize === undefined ? undefined : number('cellSize', values.cellSize, { min: 10, integer: true }), + seed: values.seed, + palette: values.colors === undefined ? undefined : parseColors(values.colors), + }; +} diff --git a/lib/png.mjs b/lib/png.mjs new file mode 100644 index 0000000..99b94bb --- /dev/null +++ b/lib/png.mjs @@ -0,0 +1,48 @@ +import { crc32, deflateSync } from 'node:zlib'; + +const SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + +function chunk(type, data) { + const typeBuffer = Buffer.from(type, 'latin1'); + const header = Buffer.alloc(4); + header.writeUInt32BE(data.length); + const footer = Buffer.alloc(4); + footer.writeUInt32BE(crc32(data, crc32(typeBuffer))); + return Buffer.concat([header, typeBuffer, data, footer]); +} + +/** + * Encodes an 8-bit RGB image as a PNG. + * @param {{ width: number, height: number, data: Uint8Array }} image `data` holds `width * height * 3` bytes. + * @returns {Buffer} + */ +export function encodePng({ width, height, data }) { + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(width, 0); + ihdr.writeUInt32BE(height, 4); + ihdr[8] = 8; // bit depth + ihdr[9] = 2; // colour type: truecolour (RGB) + ihdr[10] = 0; // compression + ihdr[11] = 0; // filter method + ihdr[12] = 0; // no interlacing + + // Every scanline uses the "Sub" filter: flat triangle runs become zeros, which deflate squeezes well. + const stride = width * 3; + const raw = Buffer.alloc(height * (stride + 1)); + for (let y = 0; y < height; y++) { + const src = y * stride; + const dst = y * (stride + 1); + raw[dst] = 1; + for (let x = 0; x < stride; x++) { + const left = x >= 3 ? data[src + x - 3] : 0; + raw[dst + 1 + x] = (data[src + x] - left) & 0xff; + } + } + + return Buffer.concat([ + SIGNATURE, + chunk('IHDR', ihdr), + chunk('IDAT', deflateSync(raw)), + chunk('IEND', Buffer.alloc(0)), + ]); +} diff --git a/lib/random.mjs b/lib/random.mjs new file mode 100644 index 0000000..f94475c --- /dev/null +++ b/lib/random.mjs @@ -0,0 +1,52 @@ +import { randomBytes } from 'node:crypto'; + +// cyrb128: hashes a string into four 32-bit values used to seed sfc32. +function hashSeed(seed) { + let h1 = 1779033703; + let h2 = 3144134277; + let h3 = 1013904242; + let h4 = 2773480762; + for (let i = 0; i < seed.length; i++) { + const k = seed.charCodeAt(i); + h1 = h2 ^ Math.imul(h1 ^ k, 597399067); + h2 = h3 ^ Math.imul(h2 ^ k, 2869860233); + h3 = h4 ^ Math.imul(h3 ^ k, 951274213); + h4 = h1 ^ Math.imul(h4 ^ k, 2716044179); + } + h1 = Math.imul(h3 ^ (h1 >>> 18), 597399067); + h2 = Math.imul(h4 ^ (h2 >>> 22), 2869860233); + h3 = Math.imul(h1 ^ (h3 >>> 17), 951274213); + h4 = Math.imul(h2 ^ (h4 >>> 19), 2716044179); + h1 ^= h2 ^ h3 ^ h4; + h2 ^= h1; + h3 ^= h1; + h4 ^= h1; + return [h1 >>> 0, h2 >>> 0, h3 >>> 0, h4 >>> 0]; +} + +/** + * Returns a deterministic random number generator (sfc32) producing floats in [0, 1). + * @param {string} seed + */ +export function createRandom(seed) { + let [a, b, c, d] = hashSeed(String(seed)); + return () => { + a >>>= 0; + b >>>= 0; + c >>>= 0; + d >>>= 0; + let t = (a + b) | 0; + a = b ^ (b >>> 9); + b = (c + (c << 3)) | 0; + c = (c << 21) | (c >>> 11); + d = (d + 1) | 0; + t = (t + d) | 0; + c = (c + t) | 0; + return (t >>> 0) / 4294967296; + }; +} + +/** A short random seed, printed so a generated wallpaper can be reproduced later. */ +export function randomSeed() { + return randomBytes(6).toString('base64url'); +} diff --git a/lib/wallpaper/index.mjs b/lib/wallpaper/index.mjs new file mode 100644 index 0000000..55b3c0c --- /dev/null +++ b/lib/wallpaper/index.mjs @@ -0,0 +1,30 @@ +import { homedir } from 'node:os'; +import { join } from 'node:path'; + +const platforms = { + win32: { + load: () => import('./windows.mjs'), + directory: () => join(process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local'), 'wallangle'), + }, + darwin: { + load: () => import('./macos.mjs'), + directory: () => join(homedir(), 'Library', 'Application Support', 'wallangle'), + }, +}; + +/** + * Loads the wallpaper backend for the current OS. + * @returns {Promise<{ + * directory: string, + * listMonitors: () => Promise<{ id: string, width: number, height: number }[]>, + * setWallpapers: (assignments: { id: string, path: string }[]) => Promise, + * }>} + */ +export async function loadPlatform(platform = process.platform) { + const entry = platforms[platform]; + if (!entry) { + throw new Error(`wallangle supports Windows and macOS; "${platform}" is not supported yet.`); + } + const { listMonitors, setWallpapers } = await entry.load(); + return { directory: entry.directory(), listMonitors, setWallpapers }; +} diff --git a/lib/wallpaper/macos.mjs b/lib/wallpaper/macos.mjs new file mode 100644 index 0000000..36f493b --- /dev/null +++ b/lib/wallpaper/macos.mjs @@ -0,0 +1,64 @@ +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; + +const execFileAsync = promisify(execFile); + +// JavaScript for Automation talks to AppKit directly, which avoids the Automation permission +// prompt that scripting System Events would trigger. +const LIST_MONITORS = ` +ObjC.import('AppKit'); +function run() { + const screens = $.NSScreen.screens; + const monitors = []; + for (let i = 0; i < screens.count; i++) { + const screen = screens.objectAtIndex(i); + // Frames are in points; the backing scale factor converts to physical (e.g. Retina) pixels. + const scale = screen.backingScaleFactor; + monitors.push({ + id: String(ObjC.unwrap(screen.deviceDescription.objectForKey('NSScreenNumber'))), + width: Math.round(screen.frame.size.width * scale), + height: Math.round(screen.frame.size.height * scale), + }); + } + return JSON.stringify(monitors); +} +`; + +const SET_WALLPAPERS = ` +ObjC.import('AppKit'); +function run(argv) { + const assignments = JSON.parse(argv[0]); + const screens = $.NSScreen.screens; + const workspace = $.NSWorkspace.sharedWorkspace; + for (let i = 0; i < screens.count; i++) { + const screen = screens.objectAtIndex(i); + const id = String(ObjC.unwrap(screen.deviceDescription.objectForKey('NSScreenNumber'))); + const assignment = assignments.find((candidate) => candidate.id === id); + if (!assignment) continue; + + const error = Ref(); + const url = $.NSURL.fileURLWithPath(assignment.path); + if (!workspace.setDesktopImageURLForScreenOptionsError(url, screen, $({}), error)) { + throw new Error(ObjC.unwrap(error[0].localizedDescription)); + } + } +} +`; + +async function runJxa(script, args = []) { + const { stdout } = await execFileAsync('osascript', ['-l', 'JavaScript', '-e', script, ...args]); + return stdout; +} + +/** @returns {Promise<{ id: string, width: number, height: number }[]>} */ +export async function listMonitors() { + return JSON.parse(await runJxa(LIST_MONITORS)); +} + +/** + * Only affects the current Space on each monitor; macOS has no public API for the others. + * @param {{ id: string, path: string }[]} assignments + */ +export async function setWallpapers(assignments) { + await runJxa(SET_WALLPAPERS, [JSON.stringify(assignments)]); +} diff --git a/lib/wallpaper/windows.mjs b/lib/wallpaper/windows.mjs new file mode 100644 index 0000000..42013bb --- /dev/null +++ b/lib/wallpaper/windows.mjs @@ -0,0 +1,119 @@ +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; + +const execFileAsync = promisify(execFile); + +// IDesktopWallpaper (Windows 8+) is the only API that sets a different wallpaper per monitor. +// PowerShell can't call COM interfaces through a cast, so the calls live in C# and PowerShell +// only invokes the static methods. +const PRELUDE = ` +$ErrorActionPreference = 'Stop' +$ProgressPreference = 'SilentlyContinue' +trap { [Console]::Error.WriteLine($_.Exception.Message); exit 1 } +Add-Type -TypeDefinition @' +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; + +namespace Wallangle { + [StructLayout(LayoutKind.Sequential)] + public struct Rect { public int Left, Top, Right, Bottom; } + + public enum Position { Center = 0, Tile = 1, Stretch = 2, Fit = 3, Fill = 4, Span = 5 } + + // Methods must be declared in vtable order; the ones after SetPosition are not needed. + [ComImport, Guid("B92B56A9-8B55-4E14-9A89-0199BBB6F93B"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + interface IDesktopWallpaper { + void SetWallpaper([MarshalAs(UnmanagedType.LPWStr)] string monitorId, [MarshalAs(UnmanagedType.LPWStr)] string wallpaper); + [return: MarshalAs(UnmanagedType.LPWStr)] string GetWallpaper([MarshalAs(UnmanagedType.LPWStr)] string monitorId); + [return: MarshalAs(UnmanagedType.LPWStr)] string GetMonitorDevicePathAt(uint monitorIndex); + uint GetMonitorDevicePathCount(); + Rect GetMonitorRECT([MarshalAs(UnmanagedType.LPWStr)] string monitorId); + void SetBackgroundColor(uint color); + uint GetBackgroundColor(); + void SetPosition(Position position); + } + + [ComImport, Guid("C2CF3110-460E-4fc1-B9D0-8A1C0C9CC4BD")] + class DesktopWallpaperClass {} + + public class Monitor { + public string id { get; set; } + public int width { get; set; } + public int height { get; set; } + } + + public static class Desktop { + [DllImport("user32.dll")] + static extern bool SetProcessDPIAware(); + + static IDesktopWallpaper Open() { + // Without this, monitor sizes are reported in DPI-scaled rather than physical pixels. + SetProcessDPIAware(); + return (IDesktopWallpaper)new DesktopWallpaperClass(); + } + + public static Monitor[] ListMonitors() { + var desktop = Open(); + var monitors = new List(); + for (uint i = 0; i < desktop.GetMonitorDevicePathCount(); i++) { + var id = desktop.GetMonitorDevicePathAt(i); + Rect rect; + // Disconnected monitors are still listed but have no rectangle. + try { rect = desktop.GetMonitorRECT(id); } catch (COMException) { continue; } + var width = rect.Right - rect.Left; + var height = rect.Bottom - rect.Top; + if (width > 0 && height > 0) { + monitors.Add(new Monitor { id = id, width = width, height = height }); + } + } + return monitors.ToArray(); + } + + public static void SetWallpapers(string[] ids, string[] paths) { + var desktop = Open(); + desktop.SetPosition(Position.Fill); + for (var i = 0; i < ids.Length; i++) { + desktop.SetWallpaper(ids[i], paths[i]); + } + } + } +} +'@ +`; + +const LIST_MONITORS = ` +ConvertTo-Json -InputObject @([Wallangle.Desktop]::ListMonitors()) -Compress +`; + +const SET_WALLPAPERS = ` +[Wallangle.Desktop]::SetWallpapers($env:WALLANGLE_IDS -split '\\n', $env:WALLANGLE_PATHS -split '\\n') +`; + +async function runPowerShell(script, env = {}) { + const encoded = Buffer.from(PRELUDE + script, 'utf16le').toString('base64'); + try { + const { stdout } = await execFileAsync( + 'powershell.exe', + ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', encoded], + { env: { ...process.env, ...env }, windowsHide: true } + ); + return stdout; + } catch (error) { + throw new Error(`PowerShell failed: ${error.stderr?.trim() || error.message}`); + } +} + +/** @returns {Promise<{ id: string, width: number, height: number }[]>} */ +export async function listMonitors() { + return JSON.parse(await runPowerShell(LIST_MONITORS)); +} + +/** @param {{ id: string, path: string }[]} assignments */ +export async function setWallpapers(assignments) { + // Monitor IDs and paths never contain newlines, so they travel as newline-separated lists. + await runPowerShell(SET_WALLPAPERS, { + WALLANGLE_IDS: assignments.map(({ id }) => id).join('\n'), + WALLANGLE_PATHS: assignments.map(({ path }) => path).join('\n'), + }); +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..0c35d82 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,41 @@ +{ + "name": "wallangle", + "version": "1.1.2", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "wallangle", + "version": "1.1.2", + "license": "MIT", + "dependencies": { + "chroma-js": "^3.2.0", + "delaunator": "^5.1.0" + }, + "bin": { + "wallangle": "cli.mjs" + } + }, + "node_modules/chroma-js": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/chroma-js/-/chroma-js-3.2.0.tgz", + "integrity": "sha512-os/OippSlX1RlWWr+QDPcGUZs0uoqr32urfxESG9U93lhUfbnlyckte84Q8P1UQY/qth983AS1JONKmLS4T0nw==", + "license": "(BSD-3-Clause AND Apache-2.0)" + }, + "node_modules/delaunator": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.1.0.tgz", + "integrity": "sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==", + "license": "ISC", + "dependencies": { + "robust-predicates": "^3.0.2" + } + }, + "node_modules/robust-predicates": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.3.tgz", + "integrity": "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==", + "license": "Unlicense" + } + } +} diff --git a/package.json b/package.json index 2f43eee..ce4fa94 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,11 @@ { "name": "wallangle", - "version": "1.1.2", + "version": "2.0.0", "description": "A CLI utility to set algorithmically generated triangle art as your desktop wallpaper/background.", - "repository": "https://github.com/MarcelMichau/wallangle", + "repository": { + "type": "git", + "url": "git+https://github.com/MarcelMichau/wallangle.git" + }, "author": { "name": "Marcel Michau", "email": "marcelmichau@gmail.com", @@ -13,21 +16,30 @@ }, "main": "cli.mjs", "files": [ - "cli.mjs" + "cli.mjs", + "lib" ], "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" + "test": "node --test" }, "keywords": [ "wallpaper", "background", "procedural", - "triangles" + "triangles", + "multi-monitor" ], "license": "MIT", "dependencies": { - "minimist": "^1.2.5", - "trianglify": "^3.0.0", - "wallpaper": "^4.4.1" - } + "chroma-js": "^3.2.0", + "delaunator": "^5.1.0" + }, + "type": "module", + "engines": { + "node": ">=22.2" + }, + "os": [ + "win32", + "darwin" + ] } diff --git a/test/generate.test.mjs b/test/generate.test.mjs new file mode 100644 index 0000000..4442ba3 --- /dev/null +++ b/test/generate.test.mjs @@ -0,0 +1,45 @@ +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { test } from 'node:test'; +import { PALETTE_NAMES, findPalette, generate, pickPalette } from '../lib/generate.mjs'; +import { createRandom } from '../lib/random.mjs'; + +const hash = (image) => createHash('sha256').update(image.data).digest('hex'); + +test('covers every pixel exactly once, for any variance and cell size', () => { + // With a single colour, an uncovered or doubly covered sample would show up as a value other than 255. + for (const [width, height, cellSize, variance] of [ + [64, 48, 10, 0], + [97, 61, 13, 0.5], + [200, 120, 37, 1], + [33, 250, 50, 0.9], + ]) { + const image = generate({ width, height, cellSize, variance, colors: ['#fff', '#fff'], random: createRandom('cover') }); + assert.equal(image.data.length, width * height * 3); + const wrong = image.data.findIndex((value) => value !== 255); + assert.equal(wrong, -1, `pixel ${Math.floor(wrong / 3)} wrong for ${width}x${height}/${cellSize}/${variance}`); + } +}); + +test('is deterministic for a seed', () => { + const options = { width: 120, height: 80, cellSize: 20, variance: 0.75, colors: ['#083d77', '#da4167'] }; + const a = generate({ ...options, random: createRandom('hello') }); + const b = generate({ ...options, random: createRandom('hello') }); + const c = generate({ ...options, random: createRandom('world') }); + assert.equal(hash(a), hash(b)); + assert.notEqual(hash(a), hash(c)); +}); + +test('runs a gradient across the image', () => { + const image = generate({ width: 100, height: 100, cellSize: 10, variance: 0, colors: ['#000', '#fff'], random: createRandom('x') }); + const pixel = (x, y) => image.data[(y * 100 + x) * 3]; + assert.ok(pixel(2, 2) < 60, 'top-left is dark'); + assert.ok(pixel(97, 97) > 200, 'bottom-right is light'); +}); + +test('palettes', () => { + assert.ok(!PALETTE_NAMES.includes('Set1'), 'qualitative palettes are excluded'); + assert.equal(findPalette('ylgnbu').name, 'YlGnBu'); + assert.equal(findPalette('nope'), undefined); + assert.ok(PALETTE_NAMES.includes(pickPalette(createRandom('p')).name)); +}); diff --git a/test/options.test.mjs b/test/options.test.mjs new file mode 100644 index 0000000..18b604a --- /dev/null +++ b/test/options.test.mjs @@ -0,0 +1,52 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { UsageError, parseOptions } from '../lib/options.mjs'; + +test('leaves unset options undefined', () => { + assert.deepEqual(parseOptions([]), { + help: false, + width: undefined, + height: undefined, + variance: undefined, + cellSize: undefined, + seed: undefined, + palette: undefined, + }); +}); + +test('parses the README example', () => { + const options = parseOptions([ + '--width=2560', + '--height=1440', + '--variance=0.75', + '--cellSize=250', + '--seed=helloworld', + '--colors=#083d77,#ebebd3,#da4167,#f4d35e,#f78764', + ]); + assert.equal(options.width, 2560); + assert.equal(options.height, 1440); + assert.equal(options.variance, 0.75); + assert.equal(options.cellSize, 250); + assert.equal(options.seed, 'helloworld'); + assert.deepEqual(options.palette.colors, ['#083d77', '#ebebd3', '#da4167', '#f4d35e', '#f78764']); +}); + +test('accepts 0 as a seed and variance', () => { + const options = parseOptions(['--seed=0', '--variance=0']); + assert.equal(options.seed, '0'); + assert.equal(options.variance, 0); +}); + +test('colors', () => { + assert.equal(parseOptions(['--colors=']).palette, undefined); + assert.equal(parseOptions(['--colors=random']).palette, undefined); + assert.equal(parseOptions(['--colors=spectral']).palette.name, 'Spectral'); + assert.deepEqual(parseOptions(['--colors=rgb(1, 2, 3), red']).palette.colors, ['rgb(1, 2, 3)', 'red']); + assert.throws(() => parseOptions(['--colors=#fff,notacolor']), /notacolor/); +}); + +test('rejects invalid values', () => { + for (const arg of ['--variance=1.5', '--variance=abc', '--cellSize=5', '--cellSize=12.5', '--width=0', '--width=', '--bogus']) { + assert.throws(() => parseOptions([arg]), UsageError, arg); + } +}); diff --git a/test/png.test.mjs b/test/png.test.mjs new file mode 100644 index 0000000..9aff246 --- /dev/null +++ b/test/png.test.mjs @@ -0,0 +1,47 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { crc32, inflateSync } from 'node:zlib'; +import { encodePng } from '../lib/png.mjs'; + +function readChunks(png) { + const chunks = []; + for (let offset = 8; offset < png.length; ) { + const length = png.readUInt32BE(offset); + const type = png.toString('latin1', offset + 4, offset + 8); + const data = png.subarray(offset + 8, offset + 8 + length); + const crc = png.readUInt32BE(offset + 8 + length); + assert.equal(crc, crc32(data, crc32(Buffer.from(type, 'latin1'))), `${type} CRC`); + chunks.push({ type, data }); + offset += 12 + length; + } + return chunks; +} + +test('encodes RGB pixels that decode back to the input', () => { + const width = 5; + const height = 3; + const data = Uint8Array.from({ length: width * height * 3 }, (_, i) => (i * 37) % 256); + const png = encodePng({ width, height, data }); + + assert.deepEqual([...png.subarray(0, 8)], [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + const chunks = readChunks(png); + assert.deepEqual(chunks.map(({ type }) => type), ['IHDR', 'IDAT', 'IEND']); + + const ihdr = chunks[0].data; + assert.equal(ihdr.readUInt32BE(0), width); + assert.equal(ihdr.readUInt32BE(4), height); + assert.deepEqual([...ihdr.subarray(8)], [8, 2, 0, 0, 0]); + + // Undo the Sub filter. + const raw = inflateSync(chunks[1].data); + const stride = width * 3; + const decoded = new Uint8Array(width * height * 3); + for (let y = 0; y < height; y++) { + assert.equal(raw[y * (stride + 1)], 1); + for (let x = 0; x < stride; x++) { + const left = x >= 3 ? decoded[y * stride + x - 3] : 0; + decoded[y * stride + x] = (raw[y * (stride + 1) + 1 + x] + left) & 0xff; + } + } + assert.deepEqual(decoded, data); +}); From a459dced08cded6086fd8c933f9ac1b57466f48f Mon Sep 17 00:00:00 2001 From: Marcel Michau <7761114+MarcelMichau@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:16:25 +0200 Subject: [PATCH 2/5] ci(github actions) add ci and release workflows run tests on windows and macos across node 22.2.0, lts and current add non-blocking monitor detection smoke check on real runners publish to npm via trusted publishing and create github release on version tags normalise package.json repository url for npm provenance Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 49 +++++++++++++++++++++++ .github/workflows/release.yml | 75 +++++++++++++++++++++++++++++++++++ 2 files changed, 124 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/release.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..5367997 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,49 @@ +name: CI + +on: + push: + branches: [master] + pull_request: + workflow_call: + +permissions: + contents: read + +jobs: + test: + name: Test (${{ matrix.os }}, Node ${{ matrix.node }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [windows-latest, macos-latest] + # The minimum version from package.json engines, the active LTS, and the current release. + node: ['22.2.0', 'lts/*', 'current'] + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: ${{ matrix.node }} + cache: npm + - run: npm ci + - run: npm test + + smoke: + # Exercises the real OS integration. Hosted runners may not expose a desktop the way a + # real machine does, so this is informational rather than a required check. + name: Monitor detection (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + continue-on-error: true + strategy: + fail-fast: false + matrix: + os: [windows-latest, macos-latest] + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: lts/* + cache: npm + - run: npm ci + - name: List monitors + run: node --input-type=module -e "const p = await (await import('./lib/wallpaper/index.mjs')).loadPlatform(); console.log(await p.listMonitors());" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..69697bd --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,75 @@ +name: Release + +# Push a tag matching the package.json version to release, e.g.: +# npm version minor && git push --follow-tags +on: + push: + tags: ['v*'] + +permissions: + contents: read + +concurrency: + group: release + cancel-in-progress: false + +jobs: + test: + uses: ./.github/workflows/ci.yml + + publish: + name: Publish to npm + needs: test + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write # npm trusted publishing (OIDC); also generates provenance + outputs: + prerelease: ${{ steps.version.outputs.prerelease }} + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: lts/* + registry-url: https://registry.npmjs.org + - name: Check tag matches package.json + id: version + run: | + version="$(node -p "require('./package.json').version")" + if [ "v$version" != "$GITHUB_REF_NAME" ]; then + echo "::error::Tag $GITHUB_REF_NAME does not match package.json version $version" + exit 1 + fi + if [[ "$version" == *-* ]]; then + echo "prerelease=true" >> "$GITHUB_OUTPUT" + echo "dist_tag=next" >> "$GITHUB_OUTPUT" + else + echo "prerelease=false" >> "$GITHUB_OUTPUT" + echo "dist_tag=latest" >> "$GITHUB_OUTPUT" + fi + # Trusted publishing needs npm >= 11.5.1. + - run: npm install -g npm@latest + - run: npm publish --tag ${{ steps.version.outputs.dist_tag }} + + github-release: + # A separate job so that a failure here can be re-run without re-publishing to npm. + name: Create GitHub release + needs: publish + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: lts/* + - run: npm pack + - name: Create release + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release create "$GITHUB_REF_NAME" wallangle-*.tgz \ + --verify-tag \ + --generate-notes \ + --title "$GITHUB_REF_NAME" \ + ${{ needs.publish.outputs.prerelease == 'true' && '--prerelease' || '' }} From dd5b43022a231708bf2ed7e34ec53bed6e39b382 Mon Sep 17 00:00:00 2001 From: Marcel Michau <7761114+MarcelMichau@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:25:08 +0200 Subject: [PATCH 3/5] fix(review) keep recent wallpapers and stabilise seeded defaults keep wallpapers from the 10 most recent runs instead of deleting all but the current run, so inactive macos spaces and overlapping runs keep their files draw every seeded default before applying overrides, so overriding one flag no longer changes the others add tests for parameter selection and wallpaper pruning Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- cli.mjs | 30 +++++++++--------------------- lib/params.mjs | 22 ++++++++++++++++++++++ lib/storage.mjs | 32 ++++++++++++++++++++++++++++++++ test/params.test.mjs | 21 +++++++++++++++++++++ test/storage.test.mjs | 43 +++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 128 insertions(+), 22 deletions(-) create mode 100644 lib/params.mjs create mode 100644 lib/storage.mjs create mode 100644 test/params.test.mjs create mode 100644 test/storage.test.mjs diff --git a/README.md b/README.md index cd782d1..e500629 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ One of: - Windows: `%LOCALAPPDATA%\wallangle` - macOS: `~/Library/Application Support/wallangle` -Each run writes new files and removes the previous run's files. On macOS, the wallpaper is set for the current Space on each display. +Each run writes new files. Wallpapers from the 10 most recent runs are kept, older ones are removed. On macOS, the wallpaper is set for the current Space on each display. ## Libraries Used diff --git a/cli.mjs b/cli.mjs index fb8135b..3d94182 100644 --- a/cli.mjs +++ b/cli.mjs @@ -1,15 +1,14 @@ #!/usr/bin/env node -import { mkdir, readdir, rm, writeFile } from 'node:fs/promises'; -import { join } from 'node:path'; -import { generate, pickPalette } from './lib/generate.mjs'; +import { mkdir, writeFile } from 'node:fs/promises'; +import { generate } from './lib/generate.mjs'; import { USAGE, UsageError, parseOptions } from './lib/options.mjs'; +import { pickParams } from './lib/params.mjs'; import { encodePng } from './lib/png.mjs'; import { createRandom, randomSeed } from './lib/random.mjs'; +import { pruneOldRuns, wallpaperPath } from './lib/storage.mjs'; import { loadPlatform } from './lib/wallpaper/index.mjs'; -const FILE_PATTERN = /^wallangle-.*\.png$/; - async function main(args) { const options = parseOptions(args); if (options.help) { @@ -25,20 +24,15 @@ async function main(args) { const seed = options.seed ?? randomSeed(); await mkdir(platform.directory, { recursive: true }); - // macOS and Windows cache wallpapers by path, so every run needs fresh file names. - const stamp = Date.now(); + const runId = Date.now(); const assignments = []; const summaries = []; for (const [index, monitor] of monitors.entries()) { const monitorSeed = index === 0 ? seed : `${seed}:${index}`; - // Separate streams keep the point layout stable when only --variance, --cellSize or --colors change. - const pickParam = createRandom(`${monitorSeed}:params`); const width = options.width ?? monitor.width; const height = options.height ?? monitor.height; - const variance = options.variance ?? pickParam(); - const cellSize = options.cellSize ?? Math.floor(pickParam() * 200 + 40); - const palette = options.palette ?? pickPalette(pickParam); + const { variance, cellSize, palette } = pickParams(monitorSeed, options); const image = generate({ width, @@ -46,10 +40,11 @@ async function main(args) { cellSize, variance, colors: palette.colors, + // A separate stream keeps the point layout stable when only --variance, --cellSize or --colors change. random: createRandom(`${monitorSeed}:points`), }); - const path = join(platform.directory, `wallangle-${stamp}-${index}.png`); + const path = wallpaperPath(platform.directory, runId, index); await writeFile(path, encodePng(image)); assignments.push({ id: monitor.id, path }); summaries.push( @@ -58,14 +53,7 @@ async function main(args) { } await platform.setWallpapers(assignments); - - const current = new Set(assignments.map(({ path }) => path)); - for (const file of await readdir(platform.directory)) { - const path = join(platform.directory, file); - if (FILE_PATTERN.test(file) && !current.has(path)) { - await rm(path, { force: true }); - } - } + await pruneOldRuns(platform.directory); console.log(`Wallpaper generated & set with seed ${seed}:\n${summaries.join('\n')}`); console.log(`Run again with --seed=${seed} to recreate it.`); diff --git a/lib/params.mjs b/lib/params.mjs new file mode 100644 index 0000000..a313099 --- /dev/null +++ b/lib/params.mjs @@ -0,0 +1,22 @@ +import { pickPalette } from './generate.mjs'; +import { createRandom } from './random.mjs'; + +/** + * Chooses the generation parameters for one monitor. Every default is drawn from the seed before + * overrides are applied, so overriding one option never changes the others. + * @param {string} seed + * @param {{ variance?: number, cellSize?: number, palette?: { name: string, colors: string[] } }} options + */ +export function pickParams(seed, options) { + const random = createRandom(`${seed}:params`); + const defaults = { + variance: random(), + cellSize: Math.floor(random() * 200 + 40), + palette: pickPalette(random), + }; + return { + variance: options.variance ?? defaults.variance, + cellSize: options.cellSize ?? defaults.cellSize, + palette: options.palette ?? defaults.palette, + }; +} diff --git a/lib/storage.mjs b/lib/storage.mjs new file mode 100644 index 0000000..f812285 --- /dev/null +++ b/lib/storage.mjs @@ -0,0 +1,32 @@ +import { readdir, rm } from 'node:fs/promises'; +import { join } from 'node:path'; + +const FILE_PATTERN = /^wallangle-(\d+)-\d+\.png$/; + +/** + * How many runs' wallpapers to keep. Older wallpapers can still be in use (macOS only updates the + * current Space, so other Spaces keep pointing at earlier files), and a run that overlaps with + * this one must not lose its files before it applies them. + */ +export const KEEP_RUNS = 10; + +/** Run ids sort chronologically, and every file name is unique, so the OS never shows a cached image. */ +export function wallpaperPath(directory, runId, index) { + return join(directory, `wallangle-${runId}-${index}.png`); +} + +/** Deletes wallpapers from all but the newest `keepRuns` runs. */ +export async function pruneOldRuns(directory, keepRuns = KEEP_RUNS) { + const files = (await readdir(directory)) + .map((file) => ({ file, runId: Number(FILE_PATTERN.exec(file)?.[1]) })) + .filter(({ runId }) => Number.isFinite(runId)); + + const keep = new Set( + [...new Set(files.map(({ runId }) => runId))].sort((a, b) => b - a).slice(0, keepRuns) + ); + for (const { file, runId } of files) { + if (!keep.has(runId)) { + await rm(join(directory, file), { force: true }); + } + } +} diff --git a/test/params.test.mjs b/test/params.test.mjs new file mode 100644 index 0000000..a51f4c3 --- /dev/null +++ b/test/params.test.mjs @@ -0,0 +1,21 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { pickParams } from '../lib/params.mjs'; + +test('is deterministic for a seed', () => { + assert.deepEqual(pickParams('hello', {}), pickParams('hello', {})); + assert.notDeepEqual(pickParams('hello', {}), pickParams('world', {})); +}); + +test('overriding one option leaves the other defaults unchanged', () => { + const defaults = pickParams('hello', {}); + const palette = { name: 'custom', colors: ['#000', '#fff'] }; + + assert.deepEqual(pickParams('hello', { variance: 0.5 }), { ...defaults, variance: 0.5 }); + assert.deepEqual(pickParams('hello', { cellSize: 100 }), { ...defaults, cellSize: 100 }); + assert.deepEqual(pickParams('hello', { palette }), { ...defaults, palette }); +}); + +test('keeps 0 as an explicit variance', () => { + assert.equal(pickParams('hello', { variance: 0 }).variance, 0); +}); diff --git a/test/storage.test.mjs b/test/storage.test.mjs new file mode 100644 index 0000000..1403cc5 --- /dev/null +++ b/test/storage.test.mjs @@ -0,0 +1,43 @@ +import assert from 'node:assert/strict'; +import { mkdtemp, readdir, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import { pruneOldRuns, wallpaperPath } from '../lib/storage.mjs'; + +async function withDirectory(fn) { + const directory = await mkdtemp(join(tmpdir(), 'wallangle-test-')); + try { + await fn(directory); + } finally { + await rm(directory, { recursive: true, force: true }); + } +} + +test('keeps every monitor of the newest runs and deletes older runs', () => + withDirectory(async (directory) => { + // Run ids deliberately have different digit counts, so a string sort would get them wrong. + for (const runId of [9, 100, 20, 300]) { + for (const index of [0, 1]) { + await writeFile(wallpaperPath(directory, runId, index), ''); + } + } + await writeFile(join(directory, 'unrelated.png'), ''); + + await pruneOldRuns(directory, 2); + + assert.deepEqual((await readdir(directory)).sort(), [ + 'unrelated.png', + 'wallangle-100-0.png', + 'wallangle-100-1.png', + 'wallangle-300-0.png', + 'wallangle-300-1.png', + ]); + })); + +test('keeps everything when there are fewer runs than the limit', () => + withDirectory(async (directory) => { + await writeFile(wallpaperPath(directory, 1, 0), ''); + await pruneOldRuns(directory, 10); + assert.deepEqual(await readdir(directory), ['wallangle-1-0.png']); + })); From eb1dc5161f4fe39e960c55c1585873a01d8cd65b Mon Sep 17 00:00:00 2001 From: Marcel Michau <7761114+MarcelMichau@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:27:58 +0200 Subject: [PATCH 4/5] docs(readme) document running with npx Co-Authored-By: Claude Opus 5.5 --- README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/README.md b/README.md index e500629..496e617 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,14 @@ Randomly generates a low-poly triangle art wallpaper for each of your monitors, Requires [Node.js](https://nodejs.org/) >= 22.2, on Windows 10+ or macOS. +Run it without installing: + +``` +$ npx wallangle@latest +``` + +Or install it globally: + ``` $ npm install -g wallangle ``` @@ -28,6 +36,8 @@ $ npm install -g wallangle $ wallangle ``` +With `npx`, put the flags after the package name, e.g. `npx wallangle@latest --colors=YlGnBu`. + Every run prints the seed it used. Pass it back with `--seed` to recreate the same wallpapers. ### With Config From acd265f40a0bf911689f9e65c9dfcfa4ed31ac46 Mon Sep 17 00:00:00 2001 From: Marcel Michau <7761114+MarcelMichau@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:30:53 +0200 Subject: [PATCH 5/5] feat(node version) show a readable error on unsupported node versions move cli logic to lib/main.mjs and load it dynamically from cli.mjs after a version check npx installs regardless of engines.node, and older node versions otherwise fail with a cryptic missing zlib.crc32 export error add a test keeping the minimum version in sync with engines.node add a ci job asserting the error on node 20 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 18 +++++++++ cli.mjs | 79 ++++++-------------------------------- lib/main.mjs | 73 +++++++++++++++++++++++++++++++++++ lib/node-version.mjs | 15 ++++++++ test/node-version.test.mjs | 19 +++++++++ 5 files changed, 137 insertions(+), 67 deletions(-) create mode 100644 lib/main.mjs create mode 100644 lib/node-version.mjs create mode 100644 test/node-version.test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5367997..8af6c0a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -47,3 +47,21 @@ jobs: - run: npm ci - name: List monitors run: node --input-type=module -e "const p = await (await import('./lib/wallpaper/index.mjs')).loadPlatform(); console.log(await p.listMonitors());" + + old-node: + # npx installs despite engines.node, so an unsupported Node must get a readable error. + name: Readable error on unsupported Node + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 20 + - name: Run the CLI + run: | + if output="$(node cli.mjs --help 2>&1)"; then + echo "::error::Expected a non-zero exit code on Node $(node -v)" + exit 1 + fi + echo "$output" + grep -q "wallangle needs Node.js" <<< "$output" diff --git a/cli.mjs b/cli.mjs index 3d94182..0297cac 100644 --- a/cli.mjs +++ b/cli.mjs @@ -1,70 +1,15 @@ #!/usr/bin/env node -import { mkdir, writeFile } from 'node:fs/promises'; -import { generate } from './lib/generate.mjs'; -import { USAGE, UsageError, parseOptions } from './lib/options.mjs'; -import { pickParams } from './lib/params.mjs'; -import { encodePng } from './lib/png.mjs'; -import { createRandom, randomSeed } from './lib/random.mjs'; -import { pruneOldRuns, wallpaperPath } from './lib/storage.mjs'; -import { loadPlatform } from './lib/wallpaper/index.mjs'; - -async function main(args) { - const options = parseOptions(args); - if (options.help) { - console.log(USAGE); - return; - } - - const platform = await loadPlatform(); - const monitors = await platform.listMonitors(); - if (monitors.length === 0) { - throw new Error('No monitors were found.'); - } - - const seed = options.seed ?? randomSeed(); - await mkdir(platform.directory, { recursive: true }); - const runId = Date.now(); - - const assignments = []; - const summaries = []; - for (const [index, monitor] of monitors.entries()) { - const monitorSeed = index === 0 ? seed : `${seed}:${index}`; - const width = options.width ?? monitor.width; - const height = options.height ?? monitor.height; - const { variance, cellSize, palette } = pickParams(monitorSeed, options); - - const image = generate({ - width, - height, - cellSize, - variance, - colors: palette.colors, - // A separate stream keeps the point layout stable when only --variance, --cellSize or --colors change. - random: createRandom(`${monitorSeed}:points`), - }); - - const path = wallpaperPath(platform.directory, runId, index); - await writeFile(path, encodePng(image)); - assignments.push({ id: monitor.id, path }); - summaries.push( - ` Monitor ${index + 1}: ${width}x${height}, variance ${variance.toFixed(3)}, cellSize ${cellSize}, colors ${palette.name}` - ); - } - - await platform.setWallpapers(assignments); - await pruneOldRuns(platform.directory); - - console.log(`Wallpaper generated & set with seed ${seed}:\n${summaries.join('\n')}`); - console.log(`Run again with --seed=${seed} to recreate it.`); +// The real CLI is loaded dynamically: its static imports (e.g. zlib.crc32) fail with a cryptic +// error on older Node versions, before any check inside it could run. +import { MINIMUM_NODE_VERSION, isSupportedNodeVersion } from './lib/node-version.mjs'; + +if (isSupportedNodeVersion(process.versions.node)) { + import('./lib/main.mjs').then(({ run }) => run(process.argv.slice(2))); +} else { + console.error( + 'wallangle needs Node.js ' + MINIMUM_NODE_VERSION + ' or newer, but this is ' + process.version + '.\n' + + 'Update Node.js from https://nodejs.org/ and try again.' + ); + process.exitCode = 1; } - -main(process.argv.slice(2)).catch((error) => { - if (error instanceof UsageError) { - console.error(`${error.message}\n\n${USAGE}`); - process.exitCode = 2; - } else { - console.error(`wallangle: ${error.message}`); - process.exitCode = 1; - } -}); diff --git a/lib/main.mjs b/lib/main.mjs new file mode 100644 index 0000000..1adde4a --- /dev/null +++ b/lib/main.mjs @@ -0,0 +1,73 @@ +import { mkdir, writeFile } from 'node:fs/promises'; +import { generate } from './generate.mjs'; +import { USAGE, UsageError, parseOptions } from './options.mjs'; +import { pickParams } from './params.mjs'; +import { encodePng } from './png.mjs'; +import { createRandom, randomSeed } from './random.mjs'; +import { pruneOldRuns, wallpaperPath } from './storage.mjs'; +import { loadPlatform } from './wallpaper/index.mjs'; + +async function main(args) { + const options = parseOptions(args); + if (options.help) { + console.log(USAGE); + return; + } + + const platform = await loadPlatform(); + const monitors = await platform.listMonitors(); + if (monitors.length === 0) { + throw new Error('No monitors were found.'); + } + + const seed = options.seed ?? randomSeed(); + await mkdir(platform.directory, { recursive: true }); + const runId = Date.now(); + + const assignments = []; + const summaries = []; + for (const [index, monitor] of monitors.entries()) { + const monitorSeed = index === 0 ? seed : `${seed}:${index}`; + const width = options.width ?? monitor.width; + const height = options.height ?? monitor.height; + const { variance, cellSize, palette } = pickParams(monitorSeed, options); + + const image = generate({ + width, + height, + cellSize, + variance, + colors: palette.colors, + // A separate stream keeps the point layout stable when only --variance, --cellSize or --colors change. + random: createRandom(`${monitorSeed}:points`), + }); + + const path = wallpaperPath(platform.directory, runId, index); + await writeFile(path, encodePng(image)); + assignments.push({ id: monitor.id, path }); + summaries.push( + ` Monitor ${index + 1}: ${width}x${height}, variance ${variance.toFixed(3)}, cellSize ${cellSize}, colors ${palette.name}` + ); + } + + await platform.setWallpapers(assignments); + await pruneOldRuns(platform.directory); + + console.log(`Wallpaper generated & set with seed ${seed}:\n${summaries.join('\n')}`); + console.log(`Run again with --seed=${seed} to recreate it.`); +} + +/** Runs the CLI, reporting errors through the exit code rather than throwing. */ +export async function run(args) { + try { + await main(args); + } catch (error) { + if (error instanceof UsageError) { + console.error(`${error.message}\n\n${USAGE}`); + process.exitCode = 2; + } else { + console.error(`wallangle: ${error.message}`); + process.exitCode = 1; + } + } +} diff --git a/lib/node-version.mjs b/lib/node-version.mjs new file mode 100644 index 0000000..cc1d1b9 --- /dev/null +++ b/lib/node-version.mjs @@ -0,0 +1,15 @@ +// Loaded before anything else, so it must stay free of imports and of syntax newer than ES2017, +// letting old Node versions report the problem instead of crashing. + +/** Keep in sync with `engines.node` in package.json (enforced by a test). */ +export const MINIMUM_NODE_VERSION = '22.2.0'; + +/** @param {string} version e.g. `process.versions.node` */ +export function isSupportedNodeVersion(version) { + const actual = version.split('.').map(Number); + const minimum = MINIMUM_NODE_VERSION.split('.').map(Number); + for (let i = 0; i < minimum.length; i++) { + if (actual[i] !== minimum[i]) return actual[i] > minimum[i]; + } + return true; +} diff --git a/test/node-version.test.mjs b/test/node-version.test.mjs new file mode 100644 index 0000000..3354009 --- /dev/null +++ b/test/node-version.test.mjs @@ -0,0 +1,19 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { test } from 'node:test'; +import { MINIMUM_NODE_VERSION, isSupportedNodeVersion } from '../lib/node-version.mjs'; + +test('compares versions numerically', () => { + for (const version of ['22.2.0', '22.2.1', '22.10.0', '23.0.0', '100.0.0']) { + assert.ok(isSupportedNodeVersion(version), version); + } + for (const version of ['22.1.9', '22.0.0', '21.99.99', '20.18.0', '9.0.0']) { + assert.ok(!isSupportedNodeVersion(version), version); + } +}); + +test('matches engines.node in package.json', async () => { + const { engines } = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')); + const [major, minor = '0', patch = '0'] = engines.node.replace('>=', '').trim().split('.'); + assert.equal(`${major}.${minor}.${patch}`, MINIMUM_NODE_VERSION); +});