aboutsummaryrefslogtreecommitdiff
path: root/build/js/ui/ditherscripts.js
blob: e8ea41310f037cb769b2781539a4bed7ef64b13a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
// 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: <name>".
// 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;
}