// Dither Scripts: a small editor for user-written dithering algorithms. Scripts are stored // in preferences and listed in the Dither dialog's Algorithm menu as "Script: ". // They run in a worker (imaging/dither-worker.js) with the API described in API_HELP. import { el, debounce, downloadBlob, pickFiles, stripExtension } from '../core/util.js'; import { openDialog, confirmDialog } from './dialogs.js'; import { getUserScripts, setUserScripts, prepare, finish, runScript } from '../imaging/dither.js'; export const TEMPLATES = [ { name: 'Custom kernel (Fan)', source: `// Error diffusion with your own kernel: [dx, dy, weight] relative to the // current pixel. This is Zhigang Fan's kernel (less "worm" texture than // Floyd–Steinberg): // * 7 // 1 3 5 ÷ 16 api.diffuse([ [1, 0, 7], [-2, 1, 1], [-1, 1, 3], [0, 1, 5], ], { divisor: 16 }); `, }, { name: 'Threshold pattern', source: `// Ordered dithering with a hand-made pattern. The numbers only need to be in // rank order: a pixel turns light once its tone passes its cell's rank. api.ordered([ [ 0, 8, 2, 10], [12, 4, 14, 6], [ 3, 11, 1, 9], [15, 7, 13, 5], ]); // Or compute the threshold (0..1) per pixel. x and y are document coordinates // divided by the dialog's Pattern scale. Diagonal lines: // api.ordered((x, y) => (((x + y) % 6) + 0.5) / 6); `, }, { name: 'Full loop (Floyd–Steinberg)', source: `// Everything by hand: walk the pixels, pick the nearest allowed value, // and push the error onto neighbours that haven't been visited yet. const { width: w, height: h, channels: C, data, alpha } = img; const k = img.params.strength; // the dialog's Diffusion slider, 0..1 for (let y = 0; y < h; y++) { for (let x = 0; x < w; x++) { const p = y * w + x; if (!alpha[p]) continue; // transparent: leave it alone for (let c = 0; c < C; c++) { const i = p * C + c; const old = data[i]; const q = api.nearest(old, c); data[i] = q; const e = (old - q) * k; if (x + 1 < w) data[i + C] += e * 7 / 16; if (y + 1 < h) { if (x > 0) data[i + (w - 1) * C] += e * 3 / 16; data[i + w * C] += e * 5 / 16; if (x + 1 < w) data[i + (w + 1) * C] += e * 1 / 16; } } } } `, }, { name: 'Blank', source: `// img.data holds the tones (0 = dark … 1 = light). Rewrite them in place. // Whatever you leave there is snapped to the nearest allowed level. `, }, ]; const API_HELP = [ ['img.width, img.height', 'size of the area being dithered (the selection bounds, or the whole layer)'], ['img.channels', '1 for Luminance mode, 3 for RGB mode'], ['img.data', 'Float32Array of tones, 0 (dark) to 1 (light), row by row with channels interleaved. Write your result into it'], ['img.alpha', 'Uint8Array of alpha per pixel; 0 means transparent, so skip it'], ['img.x0, img.y0', 'document position of the first pixel, for patterns that line up across selections'], ['img.params', '{ strength (0..1), serpentine, scale, seed } from the Dither dialog'], ['api.levels[c]', 'the allowed values for channel c, ascending'], ['api.nearest(v, c)', 'the allowed value nearest to v'], ['api.bracket(v, c)', '{ lo, hi, t }: the allowed values around v and how far v is between them (0..1)'], ['api.diffuse(kernel, opts)', 'error diffusion. kernel is [[dx, dy, weight], …] or a built-in name such as "atkinson". opts: { divisor, serpentine, strength }'], ['api.ordered(pattern, opts)', 'ordered dithering. pattern is a 2D array (ranked), a function (x, y) → 0..1, or a name such as "bayer8" or "blue-noise". opts: { scale }'], ['api.bayer(n)', 'an n×n Bayer rank matrix (n a power of two), for api.ordered'], ['api.random()', 'a seeded random number in 0..1 (seed from the dialog)'], ['api.hash(x, y, seed)', 'a repeatable per-pixel random number in 0..1'], ]; const newId = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 7); /** Run a script on a gradient strip so authors can see what it does. */ async function testScript(source, canvas) { const w = canvas.width, h = canvas.height; const id = new ImageData(w, h); for (let y = 0; y < h; y++) { for (let x = 0; x < w; x++) { const i = (y * w + x) * 4, v = Math.round((x / (w - 1)) * 255); id.data[i] = id.data[i + 1] = id.data[i + 2] = v; id.data[i + 3] = 255; } } const p = { mode: 'mono', levels: 2, strength: 100, serpentine: true, scale: 1, seed: 1 }; const s = prepare(id, p); const r = await runScript(source, s, p, {}, { timeout: 10000 }); canvas.getContext('2d').putImageData(finish(s, id, r.data), 0, 0); return r.ms; } /** * Open the script manager. Resolves with a script id when the user chose "Use This Script" * (only offered with offerUse), otherwise null. */ export async function ditherScriptsDialog(app, { selectId = null, offerUse = false } = {}) { let scripts = getUserScripts().map((s) => ({ ...s })); let current = scripts.find((s) => s.id === selectId) || scripts[0] || null; const save = () => { setUserScripts(scripts); app.prefs.set('ditherScripts', scripts); }; const saveSoon = debounce(save, 300); const list = el('select', { class: 'ds-list', size: 9, 'aria-label': 'Scripts' }); const name = el('input', { type: 'text', class: 'ds-name', placeholder: 'Script name', 'aria-label': 'Script name' }); const code = el('textarea', { class: 'ds-code', spellcheck: 'false', 'aria-label': 'Script source', wrap: 'off' }); const status = el('div', { class: 'ds-status', role: 'status' }); const preview = el('canvas', { class: 'ds-preview', width: 256, height: 32 }); const templateSel = el('select', { 'aria-label': 'Template for new scripts' }, ...TEMPLATES.map((t, i) => el('option', { value: String(i) }, t.name))); const renderList = () => { list.replaceChildren(...scripts.map((s) => el('option', { value: s.id }, s.name || 'Untitled'))); if (current) list.value = current.id; const has = !!current; for (const n of [name, code, testBtn, delBtn, dlBtn]) n.disabled = !has; name.value = current?.name || ''; code.value = current?.source || ''; if (!has) status.textContent = 'No scripts yet. Pick a template and press New.'; }; const setStatus = (msg, isError = false) => { status.textContent = msg; status.classList.toggle('error', isError); }; const add = (nm, source) => { const base = nm || 'Untitled'; let n = base, k = 2; while (scripts.some((s) => s.name === n)) n = `${base} ${k++}`; current = { id: newId(), name: n, source }; scripts.push(current); save(); renderList(); setStatus(''); code.focus(); }; const newBtn = el('button', { type: 'button', class: 'btn', onclick: () => { const t = TEMPLATES[Number(templateSel.value)]; add(t.name, t.source); } }, 'New'); const delBtn = el('button', { type: 'button', class: 'btn', onclick: async () => { if (!current || !(await confirmDialog(`Delete the script "${current.name}"?`, { ok: 'Delete', danger: true }))) return; const i = scripts.indexOf(current); scripts.splice(i, 1); current = scripts[Math.min(i, scripts.length - 1)] || null; save(); renderList(); }, }, 'Delete'); const loadBtn = el('button', { type: 'button', class: 'btn', title: 'Add scripts from .js or .txt files', onclick: async () => { const files = await pickFiles({ accept: '.js,.mjs,.txt,text/javascript,text/plain', multiple: true }); for (const f of files) add(stripExtension(f.name), await f.text()); }, }, 'Load…'); const dlBtn = el('button', { type: 'button', class: 'btn', title: 'Save this script as a .js file', onclick: () => current && downloadBlob(new Blob([current.source], { type: 'text/javascript' }), `${(current.name || 'dither').replace(/[\\/:*?"<>|]+/g, '_')}.js`), }, 'Download'); let testRun = 0; const testBtn = el('button', { type: 'button', class: 'btn', onclick: async () => { if (!current) return; const my = ++testRun; setStatus('Running…'); try { const ms = await testScript(current.source, preview); if (my === testRun) setStatus(`OK, ${ms.toFixed(1)} ms on a ${preview.width}×${preview.height} gradient`); } catch (err) { if (my === testRun && !err.superseded) setStatus(err.message, true); } }, }, 'Test'); list.addEventListener('change', () => { current = scripts.find((s) => s.id === list.value) || null; renderList(); setStatus(''); }); list.addEventListener('keydown', (e) => e.stopPropagation()); name.addEventListener('input', () => { if (!current) return; current.name = name.value; const opt = list.querySelector(`option[value="${CSS.escape(current.id)}"]`); if (opt) opt.textContent = name.value || 'Untitled'; saveSoon(); }); name.addEventListener('keydown', (e) => e.stopPropagation()); code.addEventListener('input', () => { if (current) { current.source = code.value; saveSoon(); } }); code.addEventListener('keydown', (e) => { e.stopPropagation(); if (e.key === 'Tab' && !e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey) { e.preventDefault(); code.setRangeText(' ', code.selectionStart, code.selectionEnd, 'end'); code.dispatchEvent(new Event('input')); } else if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); testBtn.click(); } }); const help = el('details', { class: 'ds-help' }, el('summary', {}, 'Script API'), el('p', {}, 'Your script is the body of a function (img, api). It runs in a separate worker, so it can\'t touch the editor, and it is stopped after 30 s. Ctrl+Enter runs Test.'), el('dl', {}, ...API_HELP.flatMap(([k, v]) => [el('dt', {}, el('code', {}, k)), el('dd', {}, v)])), el('p', {}, 'Afterwards every value is snapped to the nearest allowed level, so the result only uses the chosen colors.')); const body = el('div', { class: 'ds' }, el('div', { class: 'ds-side' }, list, el('div', { class: 'ds-new' }, templateSel, newBtn), el('div', { class: 'form-row' }, loadBtn, delBtn)), el('div', { class: 'ds-main' }, el('div', { class: 'form-row' }, name, dlBtn), code, el('div', { class: 'form-row ds-test' }, testBtn, preview), status, help)); renderList(); const buttons = [{ label: 'Close', value: null }]; if (offerUse) buttons.push({ label: 'Use This Script', value: 'use', primary: true }); const result = await openDialog({ title: 'Dither Scripts', body, width: 'min(860px, calc(100vw - 32px))', buttons, className: 'ds-dialog' }); save(); return result === 'use' && current ? current.id : null; }