move debug output to console.log; make DB upgrade work more reasonably
[lantea.git] / js / ui.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 // Get the best-available indexedDB object.
6 window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
7 var mainDB;
8
9 var gUIHideCountdown = 0;
10 var gWaitCounter = 0;
11
12 window.onload = function() {
13   var mSel = document.getElementById("mapSelector");
14   for (var mapStyle in gMapStyles) {
15     var opt = document.createElement("option");
16     opt.value = mapStyle;
17     opt.text = gMapStyles[mapStyle].name;
18     mSel.add(opt, null);
19   }
20
21   var areas = document.getElementsByClassName('overlayArea');
22   for (var i = 0; i <= areas.length - 1; i++) {
23     areas[i].addEventListener("mouseup", uiEvHandler, false);
24     areas[i].addEventListener("mousemove", uiEvHandler, false);
25     areas[i].addEventListener("mousedown", uiEvHandler, false);
26     areas[i].addEventListener("mouseout", uiEvHandler, false);
27
28     areas[i].addEventListener("touchstart", uiEvHandler, false);
29     areas[i].addEventListener("touchmove", uiEvHandler, false);
30     areas[i].addEventListener("touchend", uiEvHandler, false);
31     areas[i].addEventListener("touchcancel", uiEvHandler, false);
32     areas[i].addEventListener("touchleave", uiEvHandler, false);
33   }
34
35   if (navigator.platform.length == "") {
36     // For Firefox OS, don't display the "save" button.
37     // Do this by setting the debugHide class for testing in debug mode.
38     document.getElementById("saveTrackButton").classList.add("debugHide");
39   }
40
41   initDB();
42   initMap();
43
44   var loopCnt = 0;
45   var waitForInitAndDraw = function() {
46     if ((gWaitCounter <= 0) || (loopCnt > 100)) {
47       if (gWaitCounter <= 0)
48         gWaitCounter = 0;
49       else
50         console.log("Loading failed (waiting for init).");
51
52       gMapPrefsLoaded = true;
53       resizeAndDraw();
54       setTracking(document.getElementById("trackCheckbox"));
55     }
56     else
57       setTimeout(waitForInitAndDraw, 100);
58     loopCnt++;
59   };
60   waitForInitAndDraw();
61 }
62
63 window.onresize = function() {
64   resizeAndDraw();
65 }
66
67 function initDB() {
68   // Open DB.
69   var request = window.indexedDB.open("MainDB", 2);
70   request.onerror = function(event) {
71     // Errors can be handled here. Error codes explain in:
72     // https://developer.mozilla.org/en/IndexedDB/IDBDatabaseException#Constants
73     if (gDebug)
74       console.log("error opening mainDB: " + event.target.errorCode);
75   };
76   request.onsuccess = function(event) {
77     mainDB = request.result;
78   };
79   request.onupgradeneeded = function(event) {
80     mainDB = request.result;
81     var ver = mainDB.version || 0; // version is empty string for a new DB
82     if (gDebug)
83       console.log("mainDB has version " + ver + ", upgrade needed.");
84     if (!mainDB.objectStoreNames.contains("prefs")) {
85       // Create a "prefs" objectStore.
86       var prefsStore = mainDB.createObjectStore("prefs");
87     }
88     if (!mainDB.objectStoreNames.contains("track")) {
89       // Create a "track" objectStore.
90       var trackStore = mainDB.createObjectStore("track", {autoIncrement: true});
91     }
92     if (!mainDB.objectStoreNames.contains("tilecache")) {
93       // Create a "tilecache" objectStore.
94       var tilecacheStore = mainDB.createObjectStore("tilecache");
95     }
96     mainDB.onversionchange = function(event) {
97       mainDB.close();
98       mainDB = undefined;
99       initDB();
100     };
101   };
102 }
103
104 function showUI() {
105   if (gUIHideCountdown <= 0) {
106     var areas = document.getElementsByClassName('overlayArea');
107     for (var i = 0; i <= areas.length - 1; i++) {
108       areas[i].classList.remove("hidden");
109     }
110     setTimeout(maybeHideUI, 1000);
111   }
112   gUIHideCountdown = 5;
113 }
114
115 function maybeHideUI() {
116   gUIHideCountdown--;
117   if (gUIHideCountdown <= 0) {
118     var areas = document.getElementsByClassName('overlayArea');
119     for (var i = 0; i <= areas.length - 1; i++) {
120       areas[i].classList.add("hidden");
121     }
122   }
123   else {
124     setTimeout(maybeHideUI, 1000);
125   }
126 }
127
128 function toggleTrackArea() {
129   var fs = document.getElementById("trackArea");
130   if (fs.style.display != "block") {
131     fs.style.display = "block";
132     showUI();
133   }
134   else {
135     fs.style.display = "none";
136   }
137 }
138
139 function toggleSettings() {
140   var fs = document.getElementById("settingsArea");
141   if (fs.style.display != "block") {
142     fs.style.display = "block";
143     showUI();
144   }
145   else {
146     fs.style.display = "none";
147   }
148 }
149
150 function toggleFullscreen() {
151   if ((document.fullScreenElement && document.fullScreenElement !== null) ||
152       (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
153       (document.webkitFullScreenElement && document.webkitFullScreenElement !== null)) {
154     if (document.cancelFullScreen) {
155       document.cancelFullScreen();
156     } else if (document.mozCancelFullScreen) {
157       document.mozCancelFullScreen();
158     } else if (document.webkitCancelFullScreen) {
159       document.webkitCancelFullScreen();
160     }
161   }
162   else {
163     var elem = document.getElementById("body");
164     if (elem.requestFullScreen) {
165       elem.requestFullScreen();
166     } else if (elem.mozRequestFullScreen) {
167       elem.mozRequestFullScreen();
168     } else if (elem.webkitRequestFullScreen) {
169       elem.webkitRequestFullScreen();
170     }
171   }
172 }
173
174 var uiEvHandler = {
175   handleEvent: function(aEvent) {
176     var touchEvent = aEvent.type.indexOf('touch') != -1;
177
178     switch (aEvent.type) {
179       case "mousedown":
180       case "touchstart":
181       case "mousemove":
182       case "touchmove":
183       case "mouseup":
184       case "touchend":
185         showUI();
186         break;
187     }
188   }
189 };
190
191 function makeISOString(aTimestamp) {
192   // ISO time format is YYYY-MM-DDTHH:mm:ssZ
193   var tsDate = new Date(aTimestamp);
194   return tsDate.getUTCFullYear() + "-" +
195          (tsDate.getUTCMonth() < 10 ? "0" : "") + tsDate.getUTCMonth() + "-" +
196          (tsDate.getUTCDate() < 10 ? "0" : "") + tsDate.getUTCDate() + "T" +
197          (tsDate.getUTCHours() < 10 ? "0" : "") + tsDate.getUTCHours() + ":" +
198          (tsDate.getUTCMinutes() < 10 ? "0" : "") + tsDate.getUTCMinutes() + ":" +
199          (tsDate.getUTCSeconds() < 10 ? "0" : "") + tsDate.getUTCSeconds() + "Z";
200 }
201
202 function saveTrack() {
203   if (gTrack.length) {
204     var out = '<?xml version="1.0" encoding="UTF-8" ?>' + "\n\n";
205     out += '<gpx version="1.0" creator="Lantea" xmlns="http://www.topografix.com/GPX/1/0">' + "\n";
206     out += '  <trk>' + "\n";
207     out += '    <trkseg>' + "\n";
208     for (var i = 0; i < gTrack.length; i++) {
209       if (gTrack[i].beginSegment && i > 0) {
210         out += '    </trkseg>' + "\n";
211         out += '    <trkseg>' + "\n";
212       }
213       out += '      <trkpt lat="' + gTrack[i].coords.latitude + '" lon="' +
214                                     gTrack[i].coords.longitude + '">' + "\n";
215       if (gTrack[i].coords.altitude) {
216         out += '        <ele>' + gTrack[i].coords.altitude + '</ele>' + "\n";
217       }
218       out += '        <time>' + makeISOString(gTrack[i].time) + '</time>' + "\n";
219       out += '      </trkpt>' + "\n";
220     }
221     out += '    </trkseg>' + "\n";
222     out += '  </trk>' + "\n";
223     out += '</gpx>' + "\n";
224     var outDataURI = "data:application/gpx+xml," + encodeURIComponent(out);
225     window.open(outDataURI, 'GPX Track');
226   }
227 }
228
229 function saveTrackDump() {
230   if (gTrack.length) {
231     var out = JSON.stringify(gTrack);
232     var outDataURI = "data:application/json," + encodeURIComponent(out);
233     window.open(outDataURI, 'JSON dump');
234   }
235 }
236
237 var gPrefs = {
238   objStore: "prefs",
239
240   get: function(aKey, aCallback) {
241     if (!mainDB)
242       return;
243     var transaction = mainDB.transaction([this.objStore]);
244     var request = transaction.objectStore(this.objStore).get(aKey);
245     request.onsuccess = function(event) {
246       aCallback(request.result, event);
247     };
248     request.onerror = function(event) {
249       // Errors can be handled here.
250       aCallback(undefined, event);
251     };
252   },
253
254   set: function(aKey, aValue, aCallback) {
255     if (!mainDB)
256       return;
257     var success = false;
258     var transaction = mainDB.transaction([this.objStore], "readwrite");
259     var objStore = transaction.objectStore(this.objStore);
260     var request = objStore.put(aValue, aKey);
261     request.onsuccess = function(event) {
262       success = true;
263       if (aCallback)
264         aCallback(success, event);
265     };
266     request.onerror = function(event) {
267       // Errors can be handled here.
268       if (aCallback)
269         aCallback(success, event);
270     };
271   },
272
273   unset: function(aKey, aCallback) {
274     if (!mainDB)
275       return;
276     var success = false;
277     var transaction = mainDB.transaction([this.objStore], "readwrite");
278     var request = transaction.objectStore(this.objStore).delete(aKey);
279     request.onsuccess = function(event) {
280       success = true;
281       if (aCallback)
282         aCallback(success, event);
283     };
284     request.onerror = function(event) {
285       // Errors can be handled here.
286       if (aCallback)
287         aCallback(success, event);
288     }
289   }
290 };
291
292 var gTrackStore = {
293   objStore: "track",
294
295   getList: function(aCallback) {
296     if (!mainDB)
297       return;
298     var transaction = mainDB.transaction([this.objStore]);
299     var objStore = transaction.objectStore(this.objStore);
300     if (objStore.getAll) { // currently Mozilla-specific
301       objStore.getAll().onsuccess = function(event) {
302         aCallback(event.target.result);
303       };
304     }
305     else { // Use cursor (standard method).
306       var tPoints = [];
307       objStore.openCursor().onsuccess = function(event) {
308         var cursor = event.target.result;
309         if (cursor) {
310           tPoints.push(cursor.value);
311           cursor.continue();
312         }
313         else {
314           aCallback(tPoints);
315         }
316       };
317     }
318   },
319
320   push: function(aValue, aCallback) {
321     if (!mainDB)
322       return;
323     var transaction = mainDB.transaction([this.objStore], "readwrite");
324     var objStore = transaction.objectStore(this.objStore);
325     var request = objStore.add(aValue);
326     request.onsuccess = function(event) {
327       if (aCallback)
328         aCallback(request.result, event);
329     };
330     request.onerror = function(event) {
331       // Errors can be handled here.
332       if (aCallback)
333         aCallback(false, event);
334     };
335   },
336
337   clear: function(aCallback) {
338     if (!mainDB)
339       return;
340     var success = false;
341     var transaction = mainDB.transaction([this.objStore], "readwrite");
342     var request = transaction.objectStore(this.objStore).clear();
343     request.onsuccess = function(event) {
344       success = true;
345       if (aCallback)
346         aCallback(success, event);
347     };
348     request.onerror = function(event) {
349       // Errors can be handled here.
350       if (aCallback)
351         aCallback(success, event);
352     }
353   }
354 };