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