common.js 15 KB

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