aboutsummaryrefslogtreecommitdiff
path: root/src/proxyClient.js
blob: 8f4ad7a6f5f32b3dc5e46c829772ad10343e2170 (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
// proxy to/from worker

Module.ctx = Module.canvas.getContext('2d');

var worker = new Worker('{{{ filename }}}.js');

worker.onmessage = function worker_onmessage(event) {
  var data = event.data;
  switch (data.target) {
    case 'stdout': {
      Module.print(data.content);
      break;
    }
    case 'stderr': {
      Module.printErr(data.content);
      break;
    }
    case 'window': {
      window[data.method]();
      break;
    }
    case 'canvas': {
      switch (data.op) {
        case 'resize': {
          Module.canvas.width = data.width;
          Module.canvas.height = data.height;
          Module.canvasData = Module.ctx.getImageData(0, 0, data.width, data.height);
          postMessage({ target: 'canvas', boundingClientRect: Module.canvas.getBoundingClientRect() });
          break;
        }
        case 'render': {
          var src = data.image.data;
          var dst = Module.canvasData.data;
          if (dst.set) {
            dst.set(src);
          } else {
            for (var i = 0; i < src.length; i++) {
              dst[i] = src[i];
            }
          }
          Module.ctx.putImageData(Module.canvasData, 0, 0);
          break;
        }
        default: throw 'eh?';
      }
      break;
    }
    default: throw 'what?';
  }
};

function cloneEvent(event) {
  var ret = {};
  for (var x in event) {
    if (x == x.toUpperCase()) continue;
    var prop = event[x];
    if (typeof prop === 'number' || typeof prop === 'string') ret[x] = prop;
  }
  return ret;
};

['keydown', 'keyup', 'keypress', 'blur', 'visibilitychange'].forEach(function(event) {
  document.addEventListener(event, function(event) {
    worker.postMessage({ target: 'document', event: cloneEvent(event) });
    event.preventDefault();
  });
});

['unload'].forEach(function(event) {
  window.addEventListener(event, function(event) {
    worker.postMessage({ target: 'window', event: cloneEvent(event) });
  });
});

['mousedown', 'mouseup', 'mousemove', 'DOMMouseScroll', 'mousewheel', 'mouseout'].forEach(function(event) {
  Module.canvas.addEventListener(event, function(event) {
    worker.postMessage({ target: 'canvas', event: cloneEvent(event) });
    event.preventDefault();
  }, true);
});