aboutsummaryrefslogtreecommitdiff
path: root/src/headless.js
blob: 5880c087d943223cbbafee32c5f9341cf1c0a2e7 (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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
//== HEADLESS ==//

var headlessPrint = function(x) {
  //print(x);
}

var window = {
  // adjustable parameters
  location: {
    toString: function() {
      return '%s';
    },
    search: '?%s',
    pathname: '%s',
  },
  onIdle: function(){ headlessPrint('triggering click'); document.querySelector('.fullscreen-button.low-res').callEventListeners('click'); window.onIdle = null; },
  dirsToDrop: 0, // go back to root dir if first_js is in a subdir
  //

  headless: true,

  stopped: false,
  fakeNow: 0, // we don't use Date.now()
  rafs: [],
  timeouts: [],
  uid: 0,
  requestAnimationFrame: function(func) {
    func.uid = window.uid++;
    headlessPrint('adding raf ' + func.uid);
    window.rafs.push(func);
  },
  setTimeout: function(func, ms) {
    func.uid = window.uid++;
    headlessPrint('adding timeout ' + func.uid);
    window.timeouts.push({
      func: func,
      when: window.fakeNow + (ms || 0)
    });
    window.timeouts.sort(function(x, y) { return y.when - x.when });
  },
  runEventLoop: function() {
    // run forever until an exception stops this replay
    var iter = 0;
    while (!this.stopped) {
      var start = Date.realNow();
      headlessPrint('event loop: ' + (iter++));
      if (window.rafs.length == 0 && window.timeouts.length == 0) {
        if (window.onIdle) {
          window.onIdle();
        } else {
          throw 'main loop is idle!';
        }
      }
      // rafs
      var currRafs = window.rafs;
      window.rafs = [];
      for (var i = 0; i < currRafs.length; i++) {
        var raf = currRafs[i];
        headlessPrint('calling raf: ' + raf.uid);// + ': ' + raf.toString().substring(0, 50));
        raf();
      }
      // timeouts
      var now = window.fakeNow;
      var timeouts = window.timeouts;
      window.timeouts = [];
      while (timeouts.length && timeouts[timeouts.length-1].when <= now) {
        var timeout = timeouts.pop();
        headlessPrint('calling timeout: ' + timeout.func.uid);// + ': ' + timeout.func.toString().substring(0, 50));
        timeout.func();
      }
      // increment 'time'
      window.fakeNow += 16.666;
      headlessPrint('main event loop iteration took ' + (Date.realNow() - start) + ' ms');
    }
  },
  eventListeners: {},
  addEventListener: function(id, func) {
    var listeners = this.eventListeners[id];
    if (!listeners) {
      listeners = this.eventListeners[id] = [];
    }
    listeners.push(func);
  },
  removeEventListener: function(id, func) {
    var listeners = this.eventListeners[id];
    if (!listeners) return;
    for (var i = 0; i < listeners.length; i++) {
      if (listeners[i] === func) {
        listeners.splice(i, 1);
        return;
      }
    }
  },
  callEventListeners: function(id) {
    var listeners = this.eventListeners[id];
    if (listeners) {
      listeners.forEach(function(listener) { listener() });
    }
  },
  URL: {
    createObjectURL: function(x) {
      return x; // the blob itself is returned
    },
    revokeObjectURL: function(x) {},
  },
  encodeURIComponent: function(x) { return x },
};
var setTimeout = window.setTimeout;
var document = {
  headless: true,
  eventListeners: {},
  addEventListener: window.addEventListener,
  removeEventListener: window.removeEventListener,
  callEventListeners: window.callEventListeners,
  getElementById: function(id) {
    switch(id) {
      case 'canvas': {
        if (this.canvas) return this.canvas;
        return this.canvas = headlessCanvas();
      }
      case 'status-text': case 'progress': {
        return {};
      }
      default: throw 'getElementById: ' + id;
    }
  },
  createElement: function(what) {
    switch (what) {
      case 'canvas': return document.getElementById(what);
      case 'script': {
        var ret = {};
        window.setTimeout(function() {
          headlessPrint('loading script: ' + ret.src);
          load(ret.src);
          headlessPrint('   script loaded.');
          if (ret.onload) {
            window.setTimeout(function() {
              ret.onload(); // yeah yeah this might vanish
            });
          }
        });
        return ret;
      }
      default: throw 'createElement ' + what;
    }
  },
  elements: {},
  querySelector: function(id) {
    if (!document.elements[id]) {
      document.elements[id] = {
        classList: {
          add: function(){},
          remove: function(){},
        },
        eventListeners: {},
        addEventListener: document.addEventListener,
        removeEventListener: document.removeEventListener,
        callEventListeners: document.callEventListeners,
      };
    };
    return document.elements[id];
  },
  styleSheets: [{
    cssRules: [],
    insertRule: function(){},
  }],
  body: {
    appendChild: function(){},
  },
  exitPointerLock: function(){},
  cancelFullScreen: function(){},
};
var alert = function(x) {
  print(x);
};
var performance = {
  now: function() {
    return Date.now();
  },
};
function fixPath(path) {
  if (path[0] == '/') path = path.substring(1);
  for (var i = 0; i < window.dirsToDrop; i++) {
    path = '../' + path;
  }
  return path
}
var XMLHttpRequest = function() {
  return {
    open: function(mode, path, async) {
      path = fixPath(path);
      this.mode = mode;
      this.path = path;
      this.async = async;
    },
    send: function() {
      if (!this.async) {
        this.doSend();
      } else {
        var that = this;
        window.setTimeout(function() {
          that.doSend();
          if (that.onload) that.onload();
        }, 0);
      }
    },
    doSend: function() {
      if (this.responseType == 'arraybuffer') {
        this.response = read(this.path, 'binary');
      } else {
        this.responseText = read(this.path);
      }
    },
  };
};
var Audio = function() {
  return {
    play: function(){},
    pause: function(){},
    cloneNode: function() {
      return this;
    },
  };
};
var Image = function() {
  var that = this;
  window.setTimeout(function() {
    that.complete = true;
    that.width = 64;
    that.height = 64;
    if (that.onload) that.onload();
  });
};
var Worker = function(workerPath) {
  workerPath = fixPath(workerPath);
  var workerCode = read(workerPath);
  workerCode = workerCode.replace(/Module/g, 'zzModuleyy' + (Worker.id++)). // prevent collision with the global Module object. Note that this becomes global, so we need unique ids
                          //replace(/Date.now/g, 'Recorder.dnow'). // recorded values are just for the "main thread" - workers were not recorded, and should not consume
                          //replace(/performance.now/g, 'Recorder.pnow').
                          //replace(/Math.random/g, 'Recorder.random').
                          replace(/\nonmessage = /, '\nvar onmessage = '); // workers commonly do "onmessage = ", we need to varify that to sandbox
  headlessPrint('loading worker ' + workerPath + ' : ' + workerCode.substring(0, 50));
  eval(workerCode); // will implement onmessage()

  function duplicateJSON(json) {
    function handleTypedArrays(key, value) {
      if (value && value.toString && value.toString().substring(0, 8) == '[object ' && value.length && value.byteLength) {
        return Array.prototype.slice.call(value);
      }
      return value;
    }
    return JSON.parse(JSON.stringify(json, handleTypedArrays))
  }
  this.terminate = function(){};
  this.postMessage = function(msg) {
    msg.messageId = Worker.messageId++;
    headlessPrint('main thread sending message ' + msg.messageId + ' to worker ' + workerPath);
    window.setTimeout(function() {
      headlessPrint('worker ' + workerPath + ' receiving message ' + msg.messageId);
      onmessage({ data: duplicateJSON(msg) });
    });
  };
  var thisWorker = this;
  var postMessage = function(msg) {
    msg.messageId = Worker.messageId++;
    headlessPrint('worker ' + workerPath + ' sending message ' + msg.messageId);
    window.setTimeout(function() {
      headlessPrint('main thread receiving message ' + msg.messageId + ' from ' + workerPath);
      thisWorker.onmessage({ data: duplicateJSON(msg) });
    });
  };
};
Worker.id = 0;
Worker.messageId = 0;
var screen = { // XXX these values may need to be adjusted
  width: 2100,
  height: 1313,
  availWidth: 2100,
  availHeight: 1283,
};
var console = {
  log: function(x) {
    print(x);
  },
};
var MozBlobBuilder = function() {
  this.data = new Uint8Array(0);
  this.append = function(buffer) {
    var data = new Uint8Array(buffer);
    var combined = new Uint8Array(this.data.length + data.length);
    combined.set(this.data);
    combined.set(data, this.data.length);
    this.data = combined;
  };
  this.getBlob = function() {
    return this.data.buffer; // return the buffer as a "blob". XXX We might need to change this if it is not opaque
  };
};

// additional setup
if (!Module['canvas']) {
  Module['canvas'] = document.getElementById('canvas');
}

//== HEADLESS ==//