9bf8d288b1ef254fa030ed1ed847d0efd35369a6
[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 var gOSMAPIURL = "http://api.openstreetmap.org/";
13
14 window.onload = function() {
15   gAction = document.getElementById("action");
16   gActionLabel = document.getElementById("actionlabel");
17
18   var mSel = document.getElementById("mapSelector");
19   for (var mapStyle in gMapStyles) {
20     var opt = document.createElement("option");
21     opt.value = mapStyle;
22     opt.text = gMapStyles[mapStyle].name;
23     mSel.add(opt, null);
24   }
25
26   var areas = document.getElementsByClassName('overlayArea');
27   for (var i = 0; i <= areas.length - 1; i++) {
28     areas[i].addEventListener("mouseup", uiEvHandler, false);
29     areas[i].addEventListener("mousemove", uiEvHandler, false);
30     areas[i].addEventListener("mousedown", uiEvHandler, false);
31     areas[i].addEventListener("mouseout", uiEvHandler, false);
32
33     areas[i].addEventListener("touchstart", uiEvHandler, false);
34     areas[i].addEventListener("touchmove", uiEvHandler, false);
35     areas[i].addEventListener("touchend", uiEvHandler, false);
36     areas[i].addEventListener("touchcancel", uiEvHandler, false);
37     areas[i].addEventListener("touchleave", uiEvHandler, false);
38   }
39
40   document.getElementById("body").addEventListener("keydown", uiEvHandler, false);
41
42   if (navigator.platform.length == "") {
43     // For Firefox OS, don't display the "save" button.
44     // Do this by setting the debugHide class for testing in debug mode.
45     document.getElementById("saveTrackButton").classList.add("debugHide");
46     // For now, only show the upload UI on Firefox OS.
47     document.getElementById("uploadTrackButton").classList.remove("debugHide");
48     // Without OAuth, the login data is useless
49     //document.getElementById("uploadSettingsArea").classList.remove("debugHide");
50     // As login data is useless for now, always enable upload button
51     document.getElementById("uploadTrackButton").disabled = true;
52   }
53
54   if (gDebug) {
55     gOSMAPIURL = "http://api06.dev.openstreetmap.org/";
56   }
57
58   initDB();
59   initMap();
60
61   var loopCnt = 0;
62   var waitForInitAndDraw = function() {
63     if ((gWaitCounter <= 0) || (loopCnt > 100)) {
64       if (gWaitCounter <= 0)
65         gWaitCounter = 0;
66       else
67         console.log("Loading failed (waiting for init).");
68
69       gMapPrefsLoaded = true;
70       resizeAndDraw();
71       gActionLabel.textContent = "";
72       gAction.style.display = "none";
73       setTracking(document.getElementById("trackCheckbox"));
74       gPrefs.get(gDebug ? "osm_dev_user" : "osm_user", function(aValue) {
75         if (aValue) {
76           document.getElementById("uploadUser").value = aValue;
77           document.getElementById("uploadTrackButton").disabled = false;
78         }
79       });
80       gPrefs.get(gDebug ? "osm_dev_pwd" : "osm_pwd", function(aValue) {
81         var upwd = document.getElementById("uploadPwd");
82         if (aValue)
83           document.getElementById("uploadPwd").value = aValue;
84       });
85     }
86     else
87       setTimeout(waitForInitAndDraw, 100);
88     loopCnt++;
89   };
90   waitForInitAndDraw();
91 }
92
93 window.onresize = function() {
94   resizeAndDraw();
95 }
96
97 function initDB() {
98   // Open DB.
99   var request = window.indexedDB.open("MainDB-lantea", 2);
100   request.onerror = function(event) {
101     // Errors can be handled here. Error codes explain in:
102     // https://developer.mozilla.org/en/IndexedDB/IDBDatabaseException#Constants
103     if (gDebug)
104       console.log("error opening mainDB: " + event.target.errorCode);
105   };
106   request.onsuccess = function(event) {
107     mainDB = request.result;
108   };
109   request.onupgradeneeded = function(event) {
110     mainDB = request.result;
111     var ver = mainDB.version || 0; // version is empty string for a new DB
112     if (gDebug)
113       console.log("mainDB has version " + ver + ", upgrade needed.");
114     if (!mainDB.objectStoreNames.contains("prefs")) {
115       // Create a "prefs" objectStore.
116       var prefsStore = mainDB.createObjectStore("prefs");
117     }
118     if (!mainDB.objectStoreNames.contains("track")) {
119       // Create a "track" objectStore.
120       var trackStore = mainDB.createObjectStore("track", {autoIncrement: true});
121     }
122     if (!mainDB.objectStoreNames.contains("tilecache")) {
123       // Create a "tilecache" objectStore.
124       var tilecacheStore = mainDB.createObjectStore("tilecache");
125     }
126     mainDB.onversionchange = function(event) {
127       mainDB.close();
128       mainDB = undefined;
129       initDB();
130     };
131   };
132 }
133
134 function showUI() {
135   if (gUIHideCountdown <= 0) {
136     var areas = document.getElementsByClassName('overlayArea');
137     for (var i = 0; i <= areas.length - 1; i++) {
138       areas[i].classList.remove("hidden");
139     }
140     setTimeout(maybeHideUI, 1000);
141   }
142   gUIHideCountdown = 5;
143 }
144
145 function maybeHideUI() {
146   gUIHideCountdown--;
147   if (gUIHideCountdown <= 0) {
148     var areas = document.getElementsByClassName('overlayArea');
149     for (var i = 0; i <= areas.length - 1; i++) {
150       areas[i].classList.add("hidden");
151     }
152   }
153   else {
154     setTimeout(maybeHideUI, 1000);
155   }
156 }
157
158 function toggleTrackArea() {
159   var fs = document.getElementById("trackArea");
160   if (fs.style.display != "block") {
161     fs.style.display = "block";
162     showUI();
163   }
164   else {
165     fs.style.display = "none";
166   }
167 }
168
169 function toggleSettings() {
170   var fs = document.getElementById("settingsArea");
171   if (fs.style.display != "block") {
172     fs.style.display = "block";
173     showUI();
174   }
175   else {
176     fs.style.display = "none";
177   }
178 }
179
180 function toggleFullscreen() {
181   if ((document.fullScreenElement && document.fullScreenElement !== null) ||
182       (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
183       (document.webkitFullScreenElement && document.webkitFullScreenElement !== null)) {
184     if (document.cancelFullScreen) {
185       document.cancelFullScreen();
186     } else if (document.mozCancelFullScreen) {
187       document.mozCancelFullScreen();
188     } else if (document.webkitCancelFullScreen) {
189       document.webkitCancelFullScreen();
190     }
191   }
192   else {
193     var elem = document.getElementById("body");
194     if (elem.requestFullScreen) {
195       elem.requestFullScreen();
196     } else if (elem.mozRequestFullScreen) {
197       elem.mozRequestFullScreen();
198     } else if (elem.webkitRequestFullScreen) {
199       elem.webkitRequestFullScreen();
200     }
201   }
202 }
203
204 var uiEvHandler = {
205   handleEvent: function(aEvent) {
206     var touchEvent = aEvent.type.indexOf('touch') != -1;
207
208     switch (aEvent.type) {
209       case "mousedown":
210       case "touchstart":
211       case "mousemove":
212       case "touchmove":
213       case "mouseup":
214       case "touchend":
215       case "keydown":
216         showUI();
217         break;
218     }
219   }
220 };
221
222 function setUploadField(aField) {
223   switch (aField.id) {
224     case "uploadUser":
225       gPrefs.set(gDebug ? "osm_dev_user" : "osm_user", aField.value);
226       document.getElementById("uploadTrackButton").disabled = !aField.value.length;
227       break;
228     case "uploadPwd":
229       gPrefs.set(gDebug ? "osm_dev_pwd" : "osm_pwd", aField.value);
230       break;
231   }
232 }
233
234 function makeISOString(aTimestamp) {
235   // ISO time format is YYYY-MM-DDTHH:mm:ssZ
236   var tsDate = new Date(aTimestamp);
237   return tsDate.getUTCFullYear() + "-" +
238          (tsDate.getUTCMonth() < 10 ? "0" : "") + tsDate.getUTCMonth() + "-" +
239          (tsDate.getUTCDate() < 10 ? "0" : "") + tsDate.getUTCDate() + "T" +
240          (tsDate.getUTCHours() < 10 ? "0" : "") + tsDate.getUTCHours() + ":" +
241          (tsDate.getUTCMinutes() < 10 ? "0" : "") + tsDate.getUTCMinutes() + ":" +
242          (tsDate.getUTCSeconds() < 10 ? "0" : "") + tsDate.getUTCSeconds() + "Z";
243 }
244
245 function convertTrack(aTargetFormat) {
246   var out = "";
247   switch (aTargetFormat) {
248     case "gpx":
249       out += '<?xml version="1.0" encoding="UTF-8" ?>' + "\n\n";
250       out += '<gpx version="1.0" creator="Lantea" xmlns="http://www.topografix.com/GPX/1/0">' + "\n";
251       if (gTrack.length) {
252         out += '  <trk>' + "\n";
253         out += '    <trkseg>' + "\n";
254         for (var i = 0; i < gTrack.length; i++) {
255           if (gTrack[i].beginSegment && i > 0) {
256             out += '    </trkseg>' + "\n";
257             out += '    <trkseg>' + "\n";
258           }
259           out += '      <trkpt lat="' + gTrack[i].coords.latitude + '" lon="' +
260                                         gTrack[i].coords.longitude + '">' + "\n";
261           if (gTrack[i].coords.altitude) {
262             out += '        <ele>' + gTrack[i].coords.altitude + '</ele>' + "\n";
263           }
264           out += '        <time>' + makeISOString(gTrack[i].time) + '</time>' + "\n";
265           out += '      </trkpt>' + "\n";
266         }
267         out += '    </trkseg>' + "\n";
268         out += '  </trk>' + "\n";
269       }
270       out += '</gpx>' + "\n";
271       break;
272     case "json":
273       out = JSON.stringify(gTrack);
274       break;
275     default:
276       break;
277   }
278   return out;
279 }
280
281 function saveTrack() {
282   if (gTrack.length) {
283     var outDataURI = "data:application/gpx+xml," +
284                      encodeURIComponent(convertTrack("gpx"));
285     window.open(outDataURI, 'GPX Track');
286   }
287 }
288
289 function saveTrackDump() {
290   if (gTrack.length) {
291     var outDataURI = "data:application/json," +
292                      encodeURIComponent(convertTrack("json"));
293     window.open(outDataURI, 'JSON dump');
294   }
295 }
296
297 function uploadTrack() {
298   // See http://wiki.openstreetmap.org/wiki/Api06#Uploading_traces
299   var trackBlob = new Blob([convertTrack("gpx")], { "type" : "application/gpx+xml" });
300   var formData = new FormData();
301   formData.append("file", trackBlob);
302   formData.append("description", "Track recorded via Lantea Maps");
303   //formData.append("tags", "");
304   formData.append("visibility", "private");
305   var XHR = new XMLHttpRequest();
306   XHR.onreadystatechange = function() {
307     if (XHR.readyState == 4 && XHR.status == 200) {
308       // so far so good
309       reportUploadStatus(true);
310     } else if (XHR.readyState == 4 && XHR.status != 200) {
311       // fetched the wrong page or network error...
312       reportUploadStatus(false);
313     }
314   };
315   XHR.open("POST", gOSMAPIURL + "api/0.6/gpx/create", true);
316   // Cross-Origin XHR doesn't allow username/password (HTTP Auth), so need to look into OAuth.
317   // But for now, we'll ask the user for entering credentials with this.
318   XHR.withCredentials = true;
319   try {
320     XHR.send(formData);
321   }
322   catch (e) {
323     reportUploadStatus(false, e);
324   }
325 }
326
327 function reportUploadStatus(aSuccess, aMessage) {
328   alert(aMessage ? aMessage : (aSuccess ? "success" : "failure"));
329 }
330
331 var gPrefs = {
332   objStore: "prefs",
333
334   get: function(aKey, aCallback) {
335     if (!mainDB)
336       return;
337     var transaction = mainDB.transaction([this.objStore]);
338     var request = transaction.objectStore(this.objStore).get(aKey);
339     request.onsuccess = function(event) {
340       aCallback(request.result, event);
341     };
342     request.onerror = function(event) {
343       // Errors can be handled here.
344       aCallback(undefined, event);
345     };
346   },
347
348   set: function(aKey, aValue, aCallback) {
349     if (!mainDB)
350       return;
351     var success = false;
352     var transaction = mainDB.transaction([this.objStore], "readwrite");
353     var objStore = transaction.objectStore(this.objStore);
354     var request = objStore.put(aValue, aKey);
355     request.onsuccess = function(event) {
356       success = true;
357       if (aCallback)
358         aCallback(success, event);
359     };
360     request.onerror = function(event) {
361       // Errors can be handled here.
362       if (aCallback)
363         aCallback(success, event);
364     };
365   },
366
367   unset: function(aKey, aCallback) {
368     if (!mainDB)
369       return;
370     var success = false;
371     var transaction = mainDB.transaction([this.objStore], "readwrite");
372     var request = transaction.objectStore(this.objStore).delete(aKey);
373     request.onsuccess = function(event) {
374       success = true;
375       if (aCallback)
376         aCallback(success, event);
377     };
378     request.onerror = function(event) {
379       // Errors can be handled here.
380       if (aCallback)
381         aCallback(success, event);
382     }
383   }
384 };
385
386 var gTrackStore = {
387   objStore: "track",
388
389   getList: function(aCallback) {
390     if (!mainDB)
391       return;
392     var transaction = mainDB.transaction([this.objStore]);
393     var objStore = transaction.objectStore(this.objStore);
394     if (objStore.getAll) { // currently Mozilla-specific
395       objStore.getAll().onsuccess = function(event) {
396         aCallback(event.target.result);
397       };
398     }
399     else { // Use cursor (standard method).
400       var tPoints = [];
401       objStore.openCursor().onsuccess = function(event) {
402         var cursor = event.target.result;
403         if (cursor) {
404           tPoints.push(cursor.value);
405           cursor.continue();
406         }
407         else {
408           aCallback(tPoints);
409         }
410       };
411     }
412   },
413
414   push: function(aValue, aCallback) {
415     if (!mainDB)
416       return;
417     var transaction = mainDB.transaction([this.objStore], "readwrite");
418     var objStore = transaction.objectStore(this.objStore);
419     var request = objStore.add(aValue);
420     request.onsuccess = function(event) {
421       if (aCallback)
422         aCallback(request.result, event);
423     };
424     request.onerror = function(event) {
425       // Errors can be handled here.
426       if (aCallback)
427         aCallback(false, event);
428     };
429   },
430
431   clear: function(aCallback) {
432     if (!mainDB)
433       return;
434     var success = false;
435     var transaction = mainDB.transaction([this.objStore], "readwrite");
436     var request = transaction.objectStore(this.objStore).clear();
437     request.onsuccess = function(event) {
438       success = true;
439       if (aCallback)
440         aCallback(success, event);
441     };
442     request.onerror = function(event) {
443       // Errors can be handled here.
444       if (aCallback)
445         aCallback(success, event);
446     }
447   }
448 };