cscg22-gearboy

CSCG 2022 Challenge 'Gearboy'
git clone https://git.sinitax.com/sinitax/cscg22-gearboy
Log | Files | Refs | sfeed.txt

common.js (15782B)


      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' && isRelease) {
     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    // Host plugins don't send a moduleDidLoad message. We'll fake it here.
    151    var isHost = isHostToolchain(tool);
    152    if (isHost) {
    153      window.setTimeout(function() {
    154        moduleEl.readyState = 1;
    155        moduleEl.dispatchEvent(new CustomEvent('loadstart'));
    156        moduleEl.readyState = 4;
    157        moduleEl.dispatchEvent(new CustomEvent('load'));
    158        moduleEl.dispatchEvent(new CustomEvent('loadend'));
    159      }, 100);  // 100 ms
    160    }
    161
    162    // This is code that is only used to test the SDK.
    163    if (isTest) {
    164      var loadNaClTest = function() {
    165        injectScript('nacltest.js', function() {
    166          runTests(moduleEl);
    167        });
    168      };
    169
    170      // Try to load test.js for the example. Whether or not it exists, load
    171      // nacltest.js.
    172      injectScript('test.js', loadNaClTest, loadNaClTest);
    173    }
    174  }
    175
    176  /**
    177   * Add the default "load" and "message" event listeners to the element with
    178   * id "listener".
    179   *
    180   * The "load" event is sent when the module is successfully loaded. The
    181   * "message" event is sent when the naclModule posts a message using
    182   * PPB_Messaging.PostMessage() (in C) or pp::Instance().PostMessage() (in
    183   * C++).
    184   */
    185  function attachDefaultListeners() {
    186    var listenerDiv = document.getElementById('listener');
    187    listenerDiv.addEventListener('load', moduleDidLoad, true);
    188    listenerDiv.addEventListener('message', handleMessage, true);
    189    listenerDiv.addEventListener('error', handleError, true);
    190    listenerDiv.addEventListener('crash', handleCrash, true);
    191    if (typeof window.attachListeners !== 'undefined') {
    192      window.attachListeners();
    193    }
    194  }
    195
    196  /**
    197   * Called when the NaCl module fails to load.
    198   *
    199   * This event listener is registered in createNaClModule above.
    200   */
    201  function handleError(event) {
    202    // We can't use common.naclModule yet because the module has not been
    203    // loaded.
    204    var moduleEl = document.getElementById('nacl_module');
    205    updateStatus('ERROR [' + moduleEl.lastError + ']');
    206  }
    207
    208  /**
    209   * Called when the Browser can not communicate with the Module
    210   *
    211   * This event listener is registered in attachDefaultListeners above.
    212   */
    213  function handleCrash(event) {
    214    if (common.naclModule.exitStatus == -1) {
    215      updateStatus('CRASHED');
    216    } else {
    217      updateStatus('EXITED [' + common.naclModule.exitStatus + ']');
    218    }
    219    if (typeof window.handleCrash !== 'undefined') {
    220      window.handleCrash(common.naclModule.lastError);
    221    }
    222  }
    223
    224  /**
    225   * Called when the NaCl module is loaded.
    226   *
    227   * This event listener is registered in attachDefaultListeners above.
    228   */
    229  function moduleDidLoad() {
    230    common.naclModule = document.getElementById('nacl_module');
    231    updateStatus('RUNNING');
    232
    233    if (typeof window.moduleDidLoad !== 'undefined') {
    234      window.moduleDidLoad();
    235    }
    236  }
    237
    238  /**
    239   * Hide the NaCl module's embed element.
    240   *
    241   * We don't want to hide by default; if we do, it is harder to determine that
    242   * a plugin failed to load. Instead, call this function inside the example's
    243   * "moduleDidLoad" function.
    244   *
    245   */
    246  function hideModule() {
    247    // Setting common.naclModule.style.display = "None" doesn't work; the
    248    // module will no longer be able to receive postMessages.
    249    common.naclModule.style.height = '0';
    250  }
    251
    252  /**
    253   * Remove the NaCl module from the page.
    254   */
    255  function removeModule() {
    256    common.naclModule.parentNode.removeChild(common.naclModule);
    257    common.naclModule = null;
    258  }
    259
    260  /**
    261   * Return true when |s| starts with the string |prefix|.
    262   *
    263   * @param {string} s The string to search.
    264   * @param {string} prefix The prefix to search for in |s|.
    265   */
    266  function startsWith(s, prefix) {
    267    // indexOf would search the entire string, lastIndexOf(p, 0) only checks at
    268    // the first index. See: http://stackoverflow.com/a/4579228
    269    return s.lastIndexOf(prefix, 0) === 0;
    270  }
    271
    272  /** Maximum length of logMessageArray. */
    273  var kMaxLogMessageLength = 20;
    274
    275  /** An array of messages to display in the element with id "log". */
    276  var logMessageArray = [];
    277
    278  /**
    279   * Add a message to an element with id "log".
    280   *
    281   * This function is used by the default "log:" message handler.
    282   *
    283   * @param {string} message The message to log.
    284   */
    285  function logMessage(message) {
    286    logMessageArray.push(message);
    287    if (logMessageArray.length > kMaxLogMessageLength)
    288      logMessageArray.shift();
    289
    290    document.getElementById('log').textContent = logMessageArray.join('\n');
    291    console.log(message);
    292  }
    293
    294  /**
    295   */
    296  var defaultMessageTypes = {
    297    'alert': alert,
    298    'log': logMessage
    299  };
    300
    301  /**
    302   * Called when the NaCl module sends a message to JavaScript (via
    303   * PPB_Messaging.PostMessage())
    304   *
    305   * This event listener is registered in createNaClModule above.
    306   *
    307   * @param {Event} message_event A message event. message_event.data contains
    308   *     the data sent from the NaCl module.
    309   */
    310  function handleMessage(message_event) {
    311    if (typeof message_event.data === 'string') {
    312      for (var type in defaultMessageTypes) {
    313        if (defaultMessageTypes.hasOwnProperty(type)) {
    314          if (startsWith(message_event.data, type + ':')) {
    315            func = defaultMessageTypes[type];
    316            func(message_event.data.slice(type.length + 1));
    317            return;
    318          }
    319        }
    320      }
    321    }
    322
    323    if (typeof window.handleMessage !== 'undefined') {
    324      window.handleMessage(message_event);
    325      return;
    326    }
    327
    328    logMessage('Unhandled message: ' + message_event.data);
    329  }
    330
    331  /**
    332   * Called when the DOM content has loaded; i.e. the page's document is fully
    333   * parsed. At this point, we can safely query any elements in the document via
    334   * document.querySelector, document.getElementById, etc.
    335   *
    336   * @param {string} name The name of the example.
    337   * @param {string} tool The name of the toolchain, e.g. "glibc", "newlib" etc.
    338   * @param {string} path Directory name where .nmf file can be found.
    339   * @param {number} width The width to create the plugin.
    340   * @param {number} height The height to create the plugin.
    341   * @param {Object} attrs Optional dictionary of additional attributes.
    342   */
    343  function domContentLoaded(name, tool, path, width, height, attrs) {
    344    // If the page loads before the Native Client module loads, then set the
    345    // status message indicating that the module is still loading.  Otherwise,
    346    // do not change the status message.
    347    updateStatus('Page loaded.');
    348    if (!browserSupportsNaCl(tool)) {
    349      updateStatus(
    350          'Browser does not support NaCl (' + tool + '), or NaCl is disabled');
    351    } else if (common.naclModule == null) {
    352      updateStatus('Creating embed: ' + tool);
    353
    354      // We use a non-zero sized embed to give Chrome space to place the bad
    355      // plug-in graphic, if there is a problem.
    356      width = typeof width !== 'undefined' ? width : 200;
    357      height = typeof height !== 'undefined' ? height : 200;
    358      attachDefaultListeners();
    359      createNaClModule(name, tool, path, width, height, attrs);
    360    } else {
    361      // It's possible that the Native Client module onload event fired
    362      // before the page's onload event.  In this case, the status message
    363      // will reflect 'SUCCESS', but won't be displayed.  This call will
    364      // display the current message.
    365      updateStatus('Waiting.');
    366    }
    367  }
    368
    369  /** Saved text to display in the element with id 'statusField'. */
    370  var statusText = 'NO-STATUSES';
    371
    372  /**
    373   * Set the global status message. If the element with id 'statusField'
    374   * exists, then set its HTML to the status message as well.
    375   *
    376   * @param {string} opt_message The message to set. If null or undefined, then
    377   *     set element 'statusField' to the message from the last call to
    378   *     updateStatus.
    379   */
    380  function updateStatus(opt_message) {
    381    if (opt_message) {
    382      statusText = opt_message;
    383    }
    384    var statusField = document.getElementById('statusField');
    385    if (statusField) {
    386      statusField.innerHTML = statusText;
    387    }
    388  }
    389
    390  // The symbols to export.
    391  return {
    392    /** A reference to the NaCl module, once it is loaded. */
    393    naclModule: null,
    394
    395    attachDefaultListeners: attachDefaultListeners,
    396    domContentLoaded: domContentLoaded,
    397    createNaClModule: createNaClModule,
    398    hideModule: hideModule,
    399    removeModule: removeModule,
    400    logMessage: logMessage,
    401    updateStatus: updateStatus
    402  };
    403
    404}());
    405
    406// Listen for the DOM content to be loaded. This event is fired when parsing of
    407// the page's document has finished.
    408document.addEventListener('DOMContentLoaded', function() {
    409  var body = document.body;
    410
    411  // The data-* attributes on the body can be referenced via body.dataset.
    412  if (body.dataset) {
    413    var loadFunction;
    414    if (!body.dataset.customLoad) {
    415      loadFunction = common.domContentLoaded;
    416    } else if (typeof window.domContentLoaded !== 'undefined') {
    417      loadFunction = window.domContentLoaded;
    418    }
    419
    420    // From https://developer.mozilla.org/en-US/docs/DOM/window.location
    421    var searchVars = {};
    422    if (window.location.search.length > 1) {
    423      var pairs = window.location.search.substr(1).split('&');
    424      for (var key_ix = 0; key_ix < pairs.length; key_ix++) {
    425        var keyValue = pairs[key_ix].split('=');
    426        searchVars[unescape(keyValue[0])] =
    427            keyValue.length > 1 ? unescape(keyValue[1]) : '';
    428      }
    429    }
    430
    431    if (loadFunction) {
    432      var toolchains = body.dataset.tools.split(' ');
    433      var configs = body.dataset.configs.split(' ');
    434
    435      var attrs = {};
    436      if (body.dataset.attrs) {
    437        var attr_list = body.dataset.attrs.split(' ');
    438        for (var key in attr_list) {
    439          var attr = attr_list[key].split('=');
    440          var key = attr[0];
    441          var value = attr[1];
    442          attrs[key] = value;
    443        }
    444      }
    445
    446      var tc = toolchains.indexOf(searchVars.tc) !== -1 ?
    447          searchVars.tc : toolchains[0];
    448
    449      // If the config value is included in the search vars, use that.
    450      // Otherwise default to Release if it is valid, or the first value if
    451      // Release is not valid.
    452      if (configs.indexOf(searchVars.config) !== -1)
    453        var config = searchVars.config;
    454      else if (configs.indexOf('Release') !== -1)
    455        var config = 'Release';
    456      else
    457        var config = configs[0];
    458
    459      var pathFormat = body.dataset.path;
    460      var path = pathFormat.replace('{tc}', tc).replace('{config}', config);
    461
    462      isTest = searchVars.test === 'true';
    463      isRelease = path.toLowerCase().indexOf('release') != -1;
    464
    465      loadFunction(body.dataset.name, tc, path, body.dataset.width,
    466                   body.dataset.height, attrs);
    467    }
    468  }
    469});