common.js 16 KB

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