fix nits: break some long lines, correctly use 'a' prefix for all function arguments
[tricorder.git] / js / tricorder.js
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3  * You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 var gStardate, gSDBase;
6 var gSounds = {};
7
8 navigator.getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia ||
9                           navigator.mozGetUserMedia || navigator.msGetUserMedia);
10
11 window.onload = function() {
12   setTimeout(updateStardate, 0);
13   gSounds.scan = new Audio("sound/scan.opus");
14   gSounds.scan.loop = true;
15   gSounds.launch = new Audio("sound/launch.opus");
16   gSounds.shutdown = new Audio("sound/shutdown.opus");
17   gSounds.keyaction = new Audio("sound/key-action.opus");
18   gSounds.keypress = new Audio("sound/key-press.opus");
19
20   document.getElementById("fullScreenButton").addEventListener("click",
21       function(aEvent) { toggleFullscreen(); }, false);
22
23   var navItems = document.getElementById("navlist").children;
24   for (var i = 0; i <= navItems.length - 1; i++) {
25     navItems[i].addEventListener("click",
26         function(aEvent) {
27           switchModule(aEvent.target.id.replace("nav", ""));
28         }, false);
29   }
30
31   gSounds.launch.play();
32   window.addEventListener("beforeunload",
33       function(aEvent) { gSounds.shutdown.play(); }, false);
34 }
35
36 window.onresize = function() {
37   if (document.getElementById("sectSound").classList.contains("active")) {
38     gModSound.resize();
39   }
40 }
41
42 function updateStardate() {
43   // Stardate rules foggy at best. See http://en.wikipedia.org/wiki/Stardate
44   // and the Memory Alpha article linked there for more details.
45   // We roughly lean on TNG scale by splitting an Earth year into exactly 1000
46   // units, but we put the 0 point at the TV premiere of The Original Series.
47   if (!gStardate)
48     gStardate = document.getElementById("stardate");
49
50   var curDate = new Date();
51
52   // Star Trek famously premiered on Thursday, September 8, 1966, at 8:30 p.m.
53   // See http://www.startrek.com/article/what-if-the-original-star-trek-had-debuted-on-friday-nights
54   if (!gSDBase)
55     gSDBase = new Date("September 8, 1966 20:30:00 EST");
56
57   var sdateval = (curDate - gSDBase) / (86400 * 365.2425);
58   gStardate.textContent = sdateval.toFixed(1);
59
60   setTimeout(updateStardate, 5*60*1000);
61 }
62
63 function toggleFullscreen() {
64   gSounds.keyaction.play();
65   if ((document.fullScreenElement && document.fullScreenElement !== null) ||
66       (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
67       (document.webkitFullScreenElement && document.webkitFullScreenElement !== null)) {
68     if (document.cancelFullScreen) {
69       document.cancelFullScreen();
70     } else if (document.mozCancelFullScreen) {
71       document.mozCancelFullScreen();
72     } else if (document.webkitCancelFullScreen) {
73       document.webkitCancelFullScreen();
74     }
75   }
76   else {
77     var elem = document.getElementById("body");
78     if (elem.requestFullScreen) {
79       elem.requestFullScreen();
80     } else if (elem.mozRequestFullScreen) {
81       elem.mozRequestFullScreen();
82     } else if (elem.webkitRequestFullScreen) {
83       elem.webkitRequestFullScreen();
84     }
85   }
86 }
87
88 function switchModule(aModname) {
89   gSounds.keyaction.play();
90   var sections = document.getElementsByTagName('section');
91   for (var i = 0; i <= sections.length - 1; i++) {
92     if (sections[i].classList.contains("active")) {
93       window["gMod" + sections[i].id.replace("sect", "")].deactivate();
94       sections[i].classList.remove("active");
95     }
96   }
97   var navs = document.getElementById('navlist').children;
98   for (var i = 0; i <= navs.length - 1; i++) {
99     navs[i].classList.remove("active");
100   }
101
102   var navItem = document.getElementById("nav" + aModname);
103   navItem.classList.add("active");
104   document.getElementById("sect" + aModname).classList.add("active");
105   document.getElementById("mainHeader").textContent =
106       (aModname == "Other") ? "Web Tricorder" : navItem.textContent;
107
108   window["gMod" + aModname].activate();
109 }
110
111 var gModPos = {
112   activate: function() {
113     if (navigator.geolocation) {
114       gSounds.scan.play();
115       document.getElementById("posunavail").style.display = "none";
116       document.getElementById("posavail").style.display = "block";
117       this.watchID = navigator.geolocation.watchPosition(
118         function(aPosition) {
119            document.getElementById("posLat").textContent =
120                aPosition.coords.latitude + "°";
121            document.getElementById("posLong").textContent =
122                aPosition.coords.longitude + "°";
123            document.getElementById("posAlt").textContent =
124                aPosition.coords.altitude.toFixed(0) + " m";
125            document.getElementById("posAcc").textContent =
126                aPosition.coords.accuracy.toFixed(0) + " m";
127            document.getElementById("posAltAcc").textContent =
128                aPosition.coords.altitudeAccuracy.toFixed(0) + " m";
129            document.getElementById("posHead").textContent =
130                aPosition.coords.heading ? aPosition.coords.heading.toFixed(0) + "°" : "---";
131            document.getElementById("posSpd").textContent =
132                aPosition.coords.speed ? aPosition.coords.speed.toFixed(1) + " m/s" : "---";
133            var locTime = new Date(aPosition.timestamp);
134            document.getElementById("posTime").textContent = locTime.toISOString();
135         },
136         function(aError) {
137           // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
138           if (aError.message) {
139             document.getElementById("posLat").textContent = aError.message;
140             document.getElementById("posLong").textContent = "...";
141             document.getElementById("posAlt").textContent = "...";
142             document.getElementById("posAcc").textContent = "...";
143             document.getElementById("posAltAcc").textContent = "...";
144             document.getElementById("posHead").textContent = "...";
145             document.getElementById("posSpd").textContent = "...";
146             document.getElementById("posTime").textContent = "...";
147             setTimeout(function() { gModPos.deactivate(); }, 5000);
148           }
149           else {
150             document.getElementById("posunavail").style.display = "block";
151             document.getElementById("posavail").style.display = "none";
152           }
153           gSounds.scan.pause();
154         },
155         {enableHighAccuracy: true, maximumAge: 10000, timeout: 60000}
156       );
157     }
158     else {
159       document.getElementById("posunavail").style.display = "block";
160       document.getElementById("posavail").style.display = "none";
161     }
162   },
163   deactivate: function() {
164     gSounds.scan.pause();
165     if (this.watchID) {
166       navigator.geolocation.clearWatch(this.watchID);
167     }
168     document.getElementById("posunavail").style.display = "block";
169     document.getElementById("posavail").style.display = "none";
170     document.getElementById("posLat").textContent = "...";
171     document.getElementById("posLong").textContent = "...";
172     document.getElementById("posAlt").textContent = "...";
173     document.getElementById("posAcc").textContent = "...";
174     document.getElementById("posAltAcc").textContent = "...";
175     document.getElementById("posHead").textContent = "...";
176     document.getElementById("posSpd").textContent = "...";
177     document.getElementById("posTime").textContent = "...";
178   },
179   watchID: null,
180 }
181
182 var gModGrav = {
183   activate: function() {
184     gSounds.scan.play();
185     document.getElementById("gravunavail").style.display = "none";
186     document.getElementById("gravavail").style.display = "block";
187     window.addEventListener("deviceorientation", this.orientEvent, true);
188     window.addEventListener("devicemotion", this.motionEvent, true);
189     setTimeout(function() {
190       if ((document.getElementById("gravAlpha").textContent == "...") &&
191           (document.getElementById("gravX").textContent == "...")) {
192         gModGrav.deactivate();
193       }
194     }, 3000);
195   },
196   deactivate: function() {
197     gSounds.scan.pause();
198     window.removeEventListener("deviceorientation", this.orientEvent, true);
199     window.removeEventListener("devicemotion", this.motionEvent, true);
200     document.getElementById("gravunavail").style.display = "block";
201     document.getElementById("gravavail").style.display = "none";
202     //document.getElementById("gravAbs").textContent = "...";
203     document.getElementById("gravAlpha").textContent = "...";
204     document.getElementById("gravBeta").textContent = "...";
205     document.getElementById("gravGamma").textContent = "...";
206     document.getElementById("gravTotal").textContent = "...";
207     document.getElementById("gravX").textContent = "...";
208     document.getElementById("gravY").textContent = "...";
209     document.getElementById("gravZ").textContent = "...";
210     //document.getElementById("gravRot").textContent = "...";
211   },
212   orientEvent: function(aOrientData) {
213     //document.getElementById("gravAbs").textContent = aOrientData.absolute;
214     document.getElementById("gravAlpha").textContent =
215         aOrientData.alpha.toFixed(1) + "°";
216     document.getElementById("gravBeta").textContent =
217         aOrientData.beta.toFixed(1) + "°";
218     document.getElementById("gravGamma").textContent =
219         aOrientData.gamma.toFixed(1) + "°";
220   },
221   motionEvent: function(aEvent) {
222     var gravTotal =
223         Math.sqrt(Math.pow(aEvent.accelerationIncludingGravity.x, 2) +
224                   Math.pow(aEvent.accelerationIncludingGravity.y, 2) +
225                   Math.pow(aEvent.accelerationIncludingGravity.z, 2));
226     document.getElementById("gravTotal").textContent =
227         gravTotal.toFixed(2) + " m/s²";
228     document.getElementById("gravX").textContent =
229         aEvent.accelerationIncludingGravity.x.toFixed(2) + " m/s²";
230     document.getElementById("gravY").textContent =
231         aEvent.accelerationIncludingGravity.y.toFixed(2) + " m/s²";
232     document.getElementById("gravZ").textContent =
233         aEvent.accelerationIncludingGravity.z.toFixed(2) + " m/s²";
234     //document.getElementById("gravRot").textContent = aEvent.rotationRate;
235   },
236 }
237
238 var gModSound = {
239   activate: function() {
240     //gSounds.scan.play();
241     if (navigator.getUserMedia &&
242         (window.AudioContext || window.webkitAudioContext)) {
243       document.getElementById("soundunavail").style.display = "none";
244       document.getElementById("soundavail").style.display = "block";
245       navigator.getUserMedia({ audio: true },
246          function(aLocalMediaStream) {
247            gModSound.mAudio.stream = aLocalMediaStream;
248            gModSound.mAudio.context = new (window.AudioContext ||
249                                            window.webkitAudioContext)();
250            gModSound.mAudio.input =
251                gModSound.mAudio.context.createMediaStreamSource(gModSound.mAudio.stream);
252            // Could put a filter in between like in http://webaudioapi.com/samples/microphone/
253            gModSound.mDisplay.canvas = document.getElementById("soundcanvas");
254            gModSound.mDisplay.context = gModSound.mDisplay.canvas.getContext("2d");
255            gModSound.rebuildCanvas();
256          },
257          function(aError) {
258            document.getElementById("soundunavail").style.display = "block";
259            document.getElementById("soundavail").style.display = "none";
260            console.log(aError);
261          }
262       );
263     }
264     else {
265       document.getElementById("soundunavail").style.display = "block";
266       document.getElementById("soundavail").style.display = "none";
267     }
268   },
269   rebuildCanvas: function() {
270     if (gModSound.mDisplay.AFRequestID) {
271       window.cancelAnimationFrame(gModSound.mDisplay.AFRequestID);
272       gModSound.mDisplay.AFRequestID = 0;
273     }
274     gModSound.mDisplay.canvas.height =
275         document.getElementById("soundavail").clientHeight - 4;
276     gModSound.mDisplay.canvas.width =
277         document.getElementById("soundavail").clientWidth;
278     gModSound.mAudio.frequencySlices = (gModSound.mDisplay.canvas.width > 512) ?
279         512 :
280         Math.pow(2, Math.floor(Math.log(gModSound.mDisplay.canvas.width) / Math.LN2));
281     //console.log("slices: " + gModSound.mAudio.frequencySlices);
282     gModSound.mAudio.analyzer = gModSound.mAudio.context.createAnalyser();
283     // Make the FFT four times as large as needed as the upper three quarters turn out to be useless.
284     gModSound.mAudio.analyzer.fftSize = gModSound.mAudio.frequencySlices * 4;
285     //console.log("FFT: " + gModSound.mAudio.analyzer.fftSize);
286     gModSound.mAudio.input.connect(gModSound.mAudio.analyzer);
287     gModSound.mDisplay.context.setTransform(1, 0, 0,
288                                             -(gModSound.mDisplay.canvas.height/256),
289                                             0, gModSound.mDisplay.canvas.height);
290     gModSound.mDisplay.active = true;
291     gModSound.mDisplay.AFRequestID =
292         window.requestAnimationFrame(gModSound.paintAnalyzerFrame);
293   },
294   mAudio: {
295     frequencySlices: 32, // Must be a multiple of 2 (see AnalyserNode.fftSize)
296   },
297   mDisplay: {
298     active: false,
299   },
300   paintAnalyzerFrame: function(aTimestamp) {
301     var data = new Uint8Array(gModSound.mAudio.frequencySlices);
302     gModSound.mAudio.analyzer.getByteFrequencyData(data);
303     gModSound.mDisplay.context.clearRect(0, 0, gModSound.mDisplay.canvas.width,
304                                          gModSound.mDisplay.canvas.height);
305     // Out of experience, only the first half of the slices are actually useful.
306     var wid = gModSound.mDisplay.canvas.width / gModSound.mAudio.frequencySlices;
307     var fill = "#9C9CFF";
308     for (var i = 0; i < gModSound.mAudio.frequencySlices; ++i) {
309       var newFill = (data[i] > 200) ? "#FF0000" :
310                                       ((data[i] > 100) ? "#FFCF00" : "#9C9CFF");
311       if (fill != newFill) {
312         gModSound.mDisplay.context.fillStyle = newFill; fill = newFill;
313       }
314       gModSound.mDisplay.context.fillRect(i*wid, 0, wid, data[i]);
315     }
316     if (gModSound.mDisplay.active)
317       gModSound.mDisplay.AFRequestID =
318           window.requestAnimationFrame(gModSound.paintAnalyzerFrame);
319   },
320   resize: function() {
321     gModSound.rebuildCanvas();
322   },
323   deactivate: function() {
324     if (gModSound.mDisplay.active) {
325       gModSound.mAudio.stream.stop();
326       gModSound.mDisplay.active = false;
327     }
328     gSounds.scan.pause();
329   },
330 }
331
332 var gModEnv = {
333   activate: function() {
334     gSounds.scan.play();
335     document.getElementById("envunavail").style.display = "none";
336     document.getElementById("envavail").style.display = "block";
337     window.addEventListener("devicelight", this.lightEvent, true);
338     window.addEventListener("deviceproximity", this.proxEvent, true);
339     setTimeout(function() {
340       if ((document.getElementById("envLight").textContent == "...") &&
341           (document.getElementById("envDistance").textContent == "...")) {
342         gModEnv.deactivate();
343       }
344     }, 5000);
345     try {
346       var cameras = navigator.mozCameras.getListOfCameras();
347       for (i = 0; i < cameras.length; i++) {
348         var promise = navigator.mozCameras.getCamera(cameras[i], {},
349           function(aCamera) {
350             if (aCamera.capabilities.flashModes.indexOf('torch') !== -1) {
351               gModEnv.foundFlashCamera(aCamera);
352             }
353           },
354           function(aError) { console.log("camera error: " + aError); }
355         );
356       }
357     } catch (e) {
358       // camera api not supported
359       document.getElementById("envFlashUnavail").style.display = "block";
360       document.getElementById("envFlashAvail").style.display = "none";
361     }
362   },
363   foundFlashCamera: function(aCamera) {
364     this.flashCamera = aCamera;
365     document.getElementById("envFlashOn").onclick =
366         function() { console.log("on"); gModEnv.switchFlashlight(true); };
367     document.getElementById("envFlashOff").onclick =
368         function() { console.log("off"); gModEnv.switchFlashlight(false); };
369     document.getElementById("envFlashUnavail").style.display = "none";
370     document.getElementById("envFlashAvail").style.display = "block";
371   },
372   deactivate: function() {
373     gSounds.scan.pause();
374     window.removeEventListener("devicelight", this.lightEvent, true);
375     window.removeEventListener("deviceproximity", this.proxEvent, true);
376     document.getElementById("envunavail").style.display = "block";
377     document.getElementById("envavail").style.display = "none";
378     document.getElementById("envLight").textContent = "...";
379     document.getElementById("envDistance").textContent = "...";
380   },
381   lightEvent: function(aLightData) {
382     // See http://www.w3.org/TR/ambient-light/
383     document.getElementById("envLight").textContent = aLightData.value + " lux";
384   },
385   proxEvent: function(aProxData) {
386     // See http://www.w3.org/TR/2012/WD-proximity-20120712/
387     if (aProxData.value >= aProxData.max) {
388       document.getElementById("envDistance").textContent =
389           "(maximum, >= " + aProxData.value + " cm)";
390     }
391     else if (aProxData.value <= aProxData.min) {
392       document.getElementById("envDistance").textContent =
393           "(minimum, <= " + aProxData.value + " cm)";
394     }
395     else {
396       document.getElementById("envDistance").textContent =
397           aProxData.value + " cm";
398     }
399   },
400   flashCamera: null,
401   switchFlashlight: function(aEnabled) {
402     if (this.flashCamera) {
403       this.flashCamera.flashMode = aEnabled ? 'torch' : 'off';
404       document.getElementById("envFlashOn").disabled = aEnabled;
405       document.getElementById("envFlashOff").disabled = !aEnabled;
406     }
407   }
408 }
409
410 var gModDev = {
411   activate: function() {
412     gSounds.scan.play();
413     this.batteryTimer =
414         setInterval(function () { gModDev.updateBattery(); }, 100);
415   },
416   deactivate: function() {
417     clearTimeout(this.batteryTimer);
418     gSounds.scan.pause();
419   },
420   updateBattery: function() {
421     document.getElementById("devBattLevel").textContent =
422         (navigator.battery.level * 100).toFixed(1) + "%";
423     if (navigator.battery.charging) {
424       if (navigator.battery.chargingTime == 0 ||
425           navigator.battery.chargingTime == Infinity) {
426         document.getElementById("devBattStatus").textContent = "charging";
427       }
428       else {
429         document.getElementById("devBattStatus").textContent =
430             "charging, " + navigator.battery.chargingTime + "s remaining";
431       }
432     }
433     else {
434       if (navigator.battery.dischargingTime == 0 ||
435           navigator.battery.dischargingTime == Infinity) {
436         document.getElementById("devBattStatus").textContent = "discharging";
437       }
438       else {
439         document.getElementById("devBattStatus").textContent =
440             navigator.battery.dischargingTime + "s usage remaining";
441       }
442     }
443   },
444   batteryTimer: null,
445 }
446
447 var gModOther = {
448   activate: function() {
449     //gSounds.scan.play();
450   },
451   deactivate: function() {
452     gSounds.scan.pause();
453   },
454 }
455
456 var gModNull = {
457   activate: function() {
458     //gSounds.scan.play();
459   },
460   deactivate: function() {
461     gSounds.scan.pause();
462   },
463 }