1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// Set to true when the Document is loaded IFF "test=true" is in the query
6// string.
7var isTest = false;
8
9// Set to true when loading a "Release" NaCl module, false when loading a
10// "Debug" NaCl module.
11var isRelease = true;
12
13// Javascript module pattern:
14//   see http://en.wikipedia.org/wiki/Unobtrusive_JavaScript#Namespaces
15// In essence, we define an anonymous function which is immediately called and
16// returns a new object. The new object contains only the exported definitions;
17// all other definitions in the anonymous function are inaccessible to external
18// code.
19var common = (function() {
20
21  function isHostToolchain(tool) {
22    return tool == 'win' || tool == 'linux' || tool == 'mac';
23  }
24
25  /**
26   * Return the mime type for NaCl plugin.
27   *
28   * @param {string} tool The name of the toolchain, e.g. "glibc", "newlib" etc.
29   * @return {string} The mime-type for the kind of NaCl plugin matching
30   * the given toolchain.
31   */
32  function mimeTypeForTool(tool) {
33    // For NaCl modules use application/x-nacl.
34    var mimetype = 'application/x-nacl';
35    if (isHostToolchain(tool)) {
36      // For non-NaCl PPAPI plugins use the x-ppapi-debug/release
37      // mime type.
38      if (isRelease)
39        mimetype = 'application/x-ppapi-release';
40      else
41        mimetype = 'application/x-ppapi-debug';
42    } else if (tool == 'pnacl') {
43      mimetype = 'application/x-pnacl';
44    }
45    return mimetype;
46  }
47
48  /**
49   * Check if the browser supports NaCl plugins.
50   *
51   * @param {string} tool The name of the toolchain, e.g. "glibc", "newlib" etc.
52   * @return {bool} True if the browser supports the type of NaCl plugin
53   * produced by the given toolchain.
54   */
55  function browserSupportsNaCl(tool) {
56    // Assume host toolchains always work with the given browser.
57    // The below mime-type checking might not work with
58    // --register-pepper-plugins.
59    if (isHostToolchain(tool)) {
60      return true;
61    }
62    var mimetype = mimeTypeForTool(tool);
63    return navigator.mimeTypes[mimetype] !== undefined;
64  }
65
66  /**
67   * Inject a script into the DOM, and call a callback when it is loaded.
68   *
69   * @param {string} url The url of the script to load.
70   * @param {Function} onload The callback to call when the script is loaded.
71   * @param {Function} onerror The callback to call if the script fails to load.
72   */
73  function injectScript(url, onload, onerror) {
74    var scriptEl = document.createElement('script');
75    scriptEl.type = 'text/javascript';
76    scriptEl.src = url;
77    scriptEl.onload = onload;
78    if (onerror) {
79      scriptEl.addEventListener('error', onerror, false);
80    }
81    document.head.appendChild(scriptEl);
82  }
83
84  /**
85   * Run all tests for this example.
86   *
87   * @param {Object} moduleEl The module DOM element.
88   */
89  function runTests(moduleEl) {
90    console.log('runTests()');
91    common.tester = new Tester();
92
93    // All NaCl SDK examples are OK if the example exits cleanly; (i.e. the
94    // NaCl module returns 0 or calls exit(0)).
95    //
96    // Without this exception, the browser_tester thinks that the module
97    // has crashed.
98    common.tester.exitCleanlyIsOK();
99
100    common.tester.addAsyncTest('loaded', function(test) {
101      test.pass();
102    });
103
104    if (typeof window.addTests !== 'undefined') {
105      window.addTests();
106    }
107
108    common.tester.waitFor(moduleEl);
109    common.tester.run();
110  }
111
112  /**
113   * Create the Native Client <embed> element as a child of the DOM element
114   * named "listener".
115   *
116   * @param {string} name The name of the example.
117   * @param {string} tool The name of the toolchain, e.g. "glibc", "newlib" etc.
118   * @param {string} path Directory name where .nmf file can be found.
119   * @param {number} width The width to create the plugin.
120   * @param {number} height The height to create the plugin.
121   * @param {Object} attrs Dictionary of attributes to set on the module.
122   */
123  function createNaClModule(name, tool, path, width, height, attrs) {
124    var moduleEl = document.createElement('embed');
125    moduleEl.setAttribute('name', 'nacl_module');
126    moduleEl.setAttribute('id', 'nacl_module');
127    moduleEl.setAttribute('width', width);
128    moduleEl.setAttribute('height', height);
129    moduleEl.setAttribute('path', path);
130    moduleEl.setAttribute('src', path + '/' + name + '.nmf');
131
132    // Add any optional arguments
133    if (attrs) {
134      for (var key in attrs) {
135        moduleEl.setAttribute(key, attrs[key]);
136      }
137    }
138
139    var mimetype = mimeTypeForTool(tool);
140    moduleEl.setAttribute('type', mimetype);
141
142    // The <EMBED> element is wrapped inside a <DIV>, which has both a 'load'
143    // and a 'message' event listener attached.  This wrapping method is used
144    // instead of attaching the event listeners directly to the <EMBED> element
145    // to ensure that the listeners are active before the NaCl module 'load'
146    // event fires.
147    var listenerDiv = document.getElementById('listener');
148    listenerDiv.appendChild(moduleEl);
149
150    // Request the offsetTop property to force a relayout. As of Apr 10, 2014
151    // this is needed if the module is being loaded on a Chrome App's
152    // background page (see crbug.com/350445).
153    moduleEl.offsetTop;
154
155    // Host plugins don't send a moduleDidLoad message. We'll fake it here.
156    var isHost = isHostToolchain(tool);
157    if (isHost) {
158      window.setTimeout(function() {
159        moduleEl.readyState = 1;
160        moduleEl.dispatchEvent(new CustomEvent('loadstart'));
161        moduleEl.readyState = 4;
162        moduleEl.dispatchEvent(new CustomEvent('load'));
163        moduleEl.dispatchEvent(new CustomEvent('loadend'));
164      }, 100);  // 100 ms
165    }
166
167    // This is code that is only used to test the SDK.
168    if (isTest) {
169      var loadNaClTest = function() {
170        injectScript('nacltest.js', function() {
171          runTests(moduleEl);
172        });
173      };
174
175      // Try to load test.js for the example. Whether or not it exists, load
176      // nacltest.js.
177      injectScript('test.js', loadNaClTest, loadNaClTest);
178    }
179  }
180
181  /**
182   * Add the default "load" and "message" event listeners to the element with
183   * id "listener".
184   *
185   * The "load" event is sent when the module is successfully loaded. The
186   * "message" event is sent when the naclModule posts a message using
187   * PPB_Messaging.PostMessage() (in C) or pp::Instance().PostMessage() (in
188   * C++).
189   */
190  function attachDefaultListeners() {
191    var listenerDiv = document.getElementById('listener');
192    listenerDiv.addEventListener('load', moduleDidLoad, true);
193    listenerDiv.addEventListener('message', handleMessage, true);
194    listenerDiv.addEventListener('error', handleError, true);
195    listenerDiv.addEventListener('crash', handleCrash, true);
196    if (typeof window.attachListeners !== 'undefined') {
197      window.attachListeners();
198    }
199  }
200
201  /**
202   * Called when the NaCl module fails to load.
203   *
204   * This event listener is registered in createNaClModule above.
205   */
206  function handleError(event) {
207    // We can't use common.naclModule yet because the module has not been
208    // loaded.
209    var moduleEl = document.getElementById('nacl_module');
210    updateStatus('ERROR [' + moduleEl.lastError + ']');
211  }
212
213  /**
214   * Called when the Browser can not communicate with the Module
215   *
216   * This event listener is registered in attachDefaultListeners above.
217   */
218  function handleCrash(event) {
219    if (common.naclModule.exitStatus == -1) {
220      updateStatus('CRASHED');
221    } else {
222      updateStatus('EXITED [' + common.naclModule.exitStatus + ']');
223    }
224    if (typeof window.handleCrash !== 'undefined') {
225      window.handleCrash(common.naclModule.lastError);
226    }
227  }
228
229  /**
230   * Called when the NaCl module is loaded.
231   *
232   * This event listener is registered in attachDefaultListeners above.
233   */
234  function moduleDidLoad() {
235    common.naclModule = document.getElementById('nacl_module');
236    updateStatus('RUNNING');
237
238    if (typeof window.moduleDidLoad !== 'undefined') {
239      window.moduleDidLoad();
240    }
241  }
242
243  /**
244   * Hide the NaCl module's embed element.
245   *
246   * We don't want to hide by default; if we do, it is harder to determine that
247   * a plugin failed to load. Instead, call this function inside the example's
248   * "moduleDidLoad" function.
249   *
250   */
251  function hideModule() {
252    // Setting common.naclModule.style.display = "None" doesn't work; the
253    // module will no longer be able to receive postMessages.
254    common.naclModule.style.height = '0';
255  }
256
257  /**
258   * Remove the NaCl module from the page.
259   */
260  function removeModule() {
261    common.naclModule.parentNode.removeChild(common.naclModule);
262    common.naclModule = null;
263  }
264
265  /**
266   * Return true when |s| starts with the string |prefix|.
267   *
268   * @param {string} s The string to search.
269   * @param {string} prefix The prefix to search for in |s|.
270   */
271  function startsWith(s, prefix) {
272    // indexOf would search the entire string, lastIndexOf(p, 0) only checks at
273    // the first index. See: http://stackoverflow.com/a/4579228
274    return s.lastIndexOf(prefix, 0) === 0;
275  }
276
277  /** Maximum length of logMessageArray. */
278  var kMaxLogMessageLength = 20;
279
280  /** An array of messages to display in the element with id "log". */
281  var logMessageArray = [];
282
283  /**
284   * Add a message to an element with id "log".
285   *
286   * This function is used by the default "log:" message handler.
287   *
288   * @param {string} message The message to log.
289   */
290  function logMessage(message) {
291    logMessageArray.push(message);
292    if (logMessageArray.length > kMaxLogMessageLength)
293      logMessageArray.shift();
294
295    document.getElementById('log').textContent = logMessageArray.join('\n');
296    console.log(message);
297  }
298
299  /**
300   */
301  var defaultMessageTypes = {
302    'alert': alert,
303    'log': logMessage
304  };
305
306  /**
307   * Called when the NaCl module sends a message to JavaScript (via
308   * PPB_Messaging.PostMessage())
309   *
310   * This event listener is registered in createNaClModule above.
311   *
312   * @param {Event} message_event A message event. message_event.data contains
313   *     the data sent from the NaCl module.
314   */
315  function handleMessage(message_event) {
316    if (typeof message_event.data === 'string') {
317      for (var type in defaultMessageTypes) {
318        if (defaultMessageTypes.hasOwnProperty(type)) {
319          if (startsWith(message_event.data, type + ':')) {
320            func = defaultMessageTypes[type];
321            func(message_event.data.slice(type.length + 1));
322            return;
323          }
324        }
325      }
326    }
327
328    if (typeof window.handleMessage !== 'undefined') {
329      window.handleMessage(message_event);
330      return;
331    }
332
333    logMessage('Unhandled message: ' + message_event.data);
334  }
335
336  /**
337   * Called when the DOM content has loaded; i.e. the page's document is fully
338   * parsed. At this point, we can safely query any elements in the document via
339   * document.querySelector, document.getElementById, etc.
340   *
341   * @param {string} name The name of the example.
342   * @param {string} tool The name of the toolchain, e.g. "glibc", "newlib" etc.
343   * @param {string} path Directory name where .nmf file can be found.
344   * @param {number} width The width to create the plugin.
345   * @param {number} height The height to create the plugin.
346   * @param {Object} attrs Optional dictionary of additional attributes.
347   */
348  function domContentLoaded(name, tool, path, width, height, attrs) {
349    // If the page loads before the Native Client module loads, then set the
350    // status message indicating that the module is still loading.  Otherwise,
351    // do not change the status message.
352    updateStatus('Page loaded.');
353    if (!browserSupportsNaCl(tool)) {
354      updateStatus(
355          'Browser does not support NaCl (' + tool + '), or NaCl is disabled');
356    } else if (common.naclModule == null) {
357      updateStatus('Creating embed: ' + tool);
358
359      // We use a non-zero sized embed to give Chrome space to place the bad
360      // plug-in graphic, if there is a problem.
361      width = typeof width !== 'undefined' ? width : 200;
362      height = typeof height !== 'undefined' ? height : 200;
363      attachDefaultListeners();
364      createNaClModule(name, tool, path, width, height, attrs);
365    } else {
366      // It's possible that the Native Client module onload event fired
367      // before the page's onload event.  In this case, the status message
368      // will reflect 'SUCCESS', but won't be displayed.  This call will
369      // display the current message.
370      updateStatus('Waiting.');
371    }
372  }
373
374  /** Saved text to display in the element with id 'statusField'. */
375  var statusText = 'NO-STATUSES';
376
377  /**
378   * Set the global status message. If the element with id 'statusField'
379   * exists, then set its HTML to the status message as well.
380   *
381   * @param {string} opt_message The message to set. If null or undefined, then
382   *     set element 'statusField' to the message from the last call to
383   *     updateStatus.
384   */
385  function updateStatus(opt_message) {
386    if (opt_message) {
387      statusText = opt_message;
388    }
389    var statusField = document.getElementById('statusField');
390    if (statusField) {
391      statusField.innerHTML = statusText;
392    }
393  }
394
395  // The symbols to export.
396  return {
397    /** A reference to the NaCl module, once it is loaded. */
398    naclModule: null,
399
400    attachDefaultListeners: attachDefaultListeners,
401    domContentLoaded: domContentLoaded,
402    createNaClModule: createNaClModule,
403    hideModule: hideModule,
404    removeModule: removeModule,
405    logMessage: logMessage,
406    updateStatus: updateStatus
407  };
408
409}());
410
411// Listen for the DOM content to be loaded. This event is fired when parsing of
412// the page's document has finished.
413document.addEventListener('DOMContentLoaded', function() {
414  var body = document.body;
415
416  // The data-* attributes on the body can be referenced via body.dataset.
417  if (body.dataset) {
418    var loadFunction;
419    if (!body.dataset.customLoad) {
420      loadFunction = common.domContentLoaded;
421    } else if (typeof window.domContentLoaded !== 'undefined') {
422      loadFunction = window.domContentLoaded;
423    }
424
425    // From https://developer.mozilla.org/en-US/docs/DOM/window.location
426    var searchVars = {};
427    if (window.location.search.length > 1) {
428      var pairs = window.location.search.substr(1).split('&');
429      for (var key_ix = 0; key_ix < pairs.length; key_ix++) {
430        var keyValue = pairs[key_ix].split('=');
431        searchVars[unescape(keyValue[0])] =
432            keyValue.length > 1 ? unescape(keyValue[1]) : '';
433      }
434    }
435
436    if (loadFunction) {
437      var toolchains = body.dataset.tools.split(' ');
438      var configs = body.dataset.configs.split(' ');
439
440      var attrs = {};
441      if (body.dataset.attrs) {
442        var attr_list = body.dataset.attrs.split(' ');
443        for (var key in attr_list) {
444          var attr = attr_list[key].split('=');
445          var key = attr[0];
446          var value = attr[1];
447          attrs[key] = value;
448        }
449      }
450
451      var tc = toolchains.indexOf(searchVars.tc) !== -1 ?
452          searchVars.tc : toolchains[0];
453
454      // If the config value is included in the search vars, use that.
455      // Otherwise default to Release if it is valid, or the first value if
456      // Release is not valid.
457      if (configs.indexOf(searchVars.config) !== -1)
458        var config = searchVars.config;
459      else if (configs.indexOf('Release') !== -1)
460        var config = 'Release';
461      else
462        var config = configs[0];
463
464      var pathFormat = body.dataset.path;
465      var path = pathFormat.replace('{tc}', tc).replace('{config}', config);
466
467      isTest = searchVars.test === 'true';
468      isRelease = path.toLowerCase().indexOf('release') != -1;
469
470      loadFunction(body.dataset.name, tc, path, body.dataset.width,
471                   body.dataset.height, attrs);
472    }
473  }
474});
475