1 // Copyright (c) 2013 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.
10 * A helper function to abbreviate getElementById.
12 * @param {string} elementId The id to get.
15 function $(elementId) {
16 return document.getElementById(elementId);
22 * @return {string} MIME type
24 function PNaClmimeType() {
25 return 'application/x-pnacl';
29 * Check if the browser supports PNaCl.
33 function browserSupportsPNaCl() {
34 var mimetype = PNaClmimeType();
35 return navigator.mimeTypes[mimetype] !== undefined;
39 * Get the URL for Google Cloud Storage.
41 * @param {string} name The relative path to the file.
44 function getDataURL(name) {
45 var revision = 232423;
46 var baseUrl = 'http://commondatastorage.googleapis.com/gonacl/demos/publish/';
47 return baseUrl + revision + '/cube/' + name;
51 * Create the Native Client <embed> element as a child of the DOM element
54 * @param {string} name The name of the example.
55 * @param {number} width The width to create the plugin.
56 * @param {number} height The height to create the plugin.
57 * @param {Object} attrs Dictionary of attributes to set on the module.
59 function createNaClModule(name, width, height, attrs) {
60 var moduleEl = document.createElement('embed');
61 moduleEl.setAttribute('name', 'nacl_module');
62 moduleEl.setAttribute('id', 'nacl_module');
63 moduleEl.setAttribute('width', width);
64 moduleEl.setAttribute('height', height);
65 moduleEl.setAttribute('path', '');
66 moduleEl.setAttribute('src', getDataURL(name + '.nmf'));
67 moduleEl.setAttribute('type', PNaClmimeType());
69 // Add any optional arguments
71 for (var key in attrs) {
72 moduleEl.setAttribute(key, attrs[key]);
76 // The <EMBED> element is wrapped inside a <DIV>, which has both a 'load'
77 // and a 'message' event listener attached. This wrapping method is used
78 // instead of attaching the event listeners directly to the <EMBED> element
79 // to ensure that the listeners are active before the NaCl module 'load'
81 var listenerDiv = $('listener');
82 listenerDiv.appendChild(moduleEl);
86 * Add the default event listeners to the element with id "listener".
88 function attachDefaultListeners() {
89 var listenerDiv = $('listener');
90 listenerDiv.addEventListener('load', moduleDidLoad, true);
91 listenerDiv.addEventListener('error', moduleLoadError, true);
92 listenerDiv.addEventListener('progress', moduleLoadProgress, true);
93 listenerDiv.addEventListener('message', handleMessage, true);
94 listenerDiv.addEventListener('crash', handleCrash, true);
99 * Called when the Browser can not communicate with the Module
101 * This event listener is registered in attachDefaultListeners above.
103 * @param {Object} event
105 function handleCrash(event) {
106 if (naclModule.exitStatus == -1) {
107 updateStatus('CRASHED');
109 updateStatus('EXITED [' + naclModule.exitStatus + ']');
114 * Called when the NaCl module is loaded.
116 * This event listener is registered in attachDefaultListeners above.
118 function moduleDidLoad() {
119 var bar = $('progress');
122 naclModule = $('nacl_module');
127 * Hide the status field and progress bar.
129 function hideStatus() {
130 $('statusField').style.display = 'none';
131 $('progress').style.display = 'none';
135 * Called when the plugin fails to load.
137 * @param {Object} event
139 function moduleLoadError(event) {
140 updateStatus('Load failed.');
144 * Called when the plugin reports progress events.
146 * @param {Object} event
148 function moduleLoadProgress(event) {
149 $('progress').style.display = 'block';
151 var loadPercent = 0.0;
152 var bar = $('progress');
154 if (event.lengthComputable && event.total > 0) {
155 loadPercent = event.loaded / event.total * 100.0;
157 // The total length is not yet known.
160 bar.value = loadPercent;
164 * If the element with id 'statusField' exists, then set its HTML to the status
167 * @param {string} opt_message The message to set.
169 function updateStatus(opt_message) {
170 var statusField = $('statusField');
172 statusField.style.display = 'block';
173 statusField.textContent = opt_message;
178 * Add event listeners after the NaCl module has loaded. These listeners will
179 * forward messages to the NaCl module via postMessage()
181 function attachListeners() {
182 $('xAngle').addEventListener('change', postAngleMessage);
183 $('yAngle').addEventListener('change', postAngleMessage);
184 $('animateOff').addEventListener('click', function() {
185 $('animateOn').checked = '';
186 naclModule.postMessage(false);
188 $('animateOn').addEventListener('click', function() {
189 $('animateOff').checked = '';
190 naclModule.postMessage(true);
194 function postAngleMessage() {
195 var xAngle = parseFloat($('xAngle').value);
196 var yAngle = parseFloat($('yAngle').value);
197 naclModule.postMessage([xAngle, yAngle]);
201 * Load a texture and send pixel data down to NaCl module.
202 * @param {string} name
204 function loadTexture(name) {
205 // Load image from jpg, decompress into canvas.
206 var img = new Image();
207 img.onload = function() {
208 var graph = document.createElement('canvas');
209 graph.width = img.width;
210 graph.height = img.height;
211 var context = graph.getContext('2d');
212 context.drawImage(img, 0, 0);
213 var imageData = context.getImageData(0, 0, img.width, img.height);
214 // Send NaCl module the raw image data obtained from canvas.
215 naclModule.postMessage({'message' : 'texture',
218 'height' : img.height,
219 'data' : imageData.data.buffer});
221 // A cross-origin request to an image is "tainted", and cannot be read into a
222 // canvas without specifying this. See
223 // https://developer.mozilla.org/en-US/docs/HTML/CORS_Enabled_Image
224 img.crossOrigin = 'Anonymous';
225 img.src = getDataURL(name);
229 * Handle a message coming from the NaCl module.
230 * @param {Object} message_event
232 function handleMessage(message_event) {
233 if (!(event.data instanceof Array))
235 if (event.data.length != 2)
238 var xAngle = event.data[0];
239 var yAngle = event.data[1];
240 $('xAngle').value = xAngle;
241 $('yAngle').value = yAngle;
245 * Listen for the DOM content to be loaded. This event is fired when parsing of
246 * the page's document has finished.
248 document.addEventListener('DOMContentLoaded', function() {
249 updateStatus('Loading...');
250 if (!browserSupportsPNaCl()) {
251 updateStatus('Browser does not support PNaCl or PNaCl is disabled');
252 } else if (naclModule == null) {
253 createNaClModule('cube', 480, 480);
254 attachDefaultListeners();
256 // It's possible that the Native Client module onload event fired
257 // before the page's onload event. In this case, the status message
258 // will reflect 'SUCCESS', but won't be displayed. This call will
259 // display the current message.
260 updateStatus('Waiting.');