aboutsummaryrefslogtreecommitdiff
path: root/build/js/imaging/dither-worker.js
blob: a434766ccce164d10691efee6e2d7dea5a83ff94 (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
// Runs a user-written dither script off the main thread, so a slow or endless script can be
// stopped (the page terminates the worker) and cannot reach the editor's DOM or state.
import { scriptApi } from './dither.js';

const HEADER_LINES = 3; // "function anonymous(img,api\n) {\n"use strict";\n" precedes the source

self.onmessage = (e) => {
  const { source, img, levels } = e.data;
  let fn;
  try {
    fn = new Function('img', 'api', `"use strict";\n${source}`);
  } catch (err) {
    self.postMessage({ ok: false, error: `Syntax error: ${err.message}` });
    return;
  }
  try {
    const t0 = performance.now();
    fn(img, scriptApi(img, levels));
    const ms = performance.now() - t0;
    self.postMessage({ ok: true, data: img.data, ms }, img.data instanceof Float32Array ? [img.data.buffer] : []);
  } catch (err) {
    const m = /<anonymous>:(\d+):\d+/.exec(String(err?.stack || ''));
    const line = m ? Number(m[1]) - HEADER_LINES : 0;
    self.postMessage({ ok: false, error: `${err?.name || 'Error'}: ${err?.message ?? err}${line > 0 ? ` (line ${line})` : ''}` });
  }
};