Merge branch 'master' of linz:/srv/git/lantea
[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 objects for indexedDB and requestAnimationFrame.
6 window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
7 window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
8
9 var mainDB;
10 var gUIHideCountdown = 0;
11 var gWaitCounter = 0;
12 var gAction, gActionLabel;
13 var gOSMAPIURL = "http://api.openstreetmap.org/";
14
15 window.onload = function() {
16   gAction = document.getElementById("action");
17   gActionLabel = document.getElementById("actionlabel");
18
19   var mSel = document.getElementById("mapSelector");
20   for (var mapStyle in gMapStyles) {
21     var opt = document.createElement("option");
22     opt.value = mapStyle;
23     opt.text = gMapStyles[mapStyle].name;
24     mSel.add(opt, null);
25   }
26
27   var areas = document.getElementsByClassName("overlayArea");
28   for (var i = 0; i <= areas.length - 1; i++) {
29     areas[i].addEventListener("mouseup", uiEvHandler, false);
30     areas[i].addEventListener("mousemove", uiEvHandler, false);
31     areas[i].addEventListener("mousedown", uiEvHandler, false);
32     areas[i].addEventListener("mouseout", uiEvHandler, false);
33
34     areas[i].addEventListener("touchstart", uiEvHandler, false);
35     areas[i].addEventListener("touchmove", uiEvHandler, false);
36     areas[i].addEventListener("touchend", uiEvHandler, false);
37     areas[i].addEventListener("touchcancel", uiEvHandler, false);
38     areas[i].addEventListener("touchleave", uiEvHandler, false);
39   }
40
41   document.getElementById("body").addEventListener("keydown", uiEvHandler, false);
42
43   if (navigator.platform.length == "") {
44     // For Firefox OS, don't display the "save" button.
45     // Do this by setting the debugHide class for testing in debug mode.
46     document.getElementById("saveTrackButton").classList.add("debugHide");
47   }
48
49   // Without OAuth, the login data is useless
50   //document.getElementById("uploadSettingsArea").classList.remove("debugHide");
51   // As login data is useless for now, always enable upload button
52   document.getElementById("uploadTrackButton").disabled = false;
53
54   if (gDebug) {
55     // Note that GPX upload returns an error 500 on the dev API right now.
56     gOSMAPIURL = "http://api06.dev.openstreetmap.org/";
57   }
58
59   gAction.addEventListener("dbinit-done", initMap, false);
60   gAction.addEventListener("mapinit-done", postInit, false);
61   console.log("starting DB init...");
62   initDB();
63 }
64
65 function postInit(aEvent) {
66   gAction.removeEventListener(aEvent.type, postInit, false);
67   console.log("init done, draw map.");
68   gMapPrefsLoaded = true;
69   //gMap.resizeAndDraw();  <-- HACK: This triggers bug 1001853, work around with a delay.
70   window.setTimeout(gMap.resizeAndDraw, 100);
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
87 window.onresize = function() {
88   gMap.resizeAndDraw();
89 }
90
91 function initDB(aEvent) {
92   // Open DB.
93   if (aEvent)
94     gAction.removeEventListener(aEvent.type, initDB, false);
95   var request = window.indexedDB.open("MainDB-lantea", 2);
96   request.onerror = function(event) {
97     // Errors can be handled here. Error codes explain in:
98     // https://developer.mozilla.org/en/IndexedDB/IDBDatabaseException#Constants
99     if (gDebug)
100       console.log("error opening mainDB: " + event.target.errorCode);
101   };
102   request.onsuccess = function(event) {
103     mainDB = request.result;
104     var throwEv = new CustomEvent("dbinit-done");
105     gAction.dispatchEvent(throwEv);
106   };
107   request.onupgradeneeded = function(event) {
108     mainDB = request.result;
109     var ver = mainDB.version || 0; // version is empty string for a new DB
110     if (gDebug)
111       console.log("mainDB has version " + ver + ", upgrade needed.");
112     if (!mainDB.objectStoreNames.contains("prefs")) {
113       // Create a "prefs" objectStore.
114       var prefsStore = mainDB.createObjectStore("prefs");
115     }
116     if (!mainDB.objectStoreNames.contains("track")) {
117       // Create a "track" objectStore.
118       var trackStore = mainDB.createObjectStore("track", {autoIncrement: true});
119     }
120     if (!mainDB.objectStoreNames.contains("tilecache")) {
121       // Create a "tilecache" objectStore.
122       var tilecacheStore = mainDB.createObjectStore("tilecache");
123     }
124     mainDB.onversionchange = function(event) {
125       mainDB.close();
126       mainDB = undefined;
127       initDB();
128     };
129   };
130 }
131
132 function showUI() {
133   if (gUIHideCountdown <= 0) {
134     var areas = document.getElementsByClassName('overlayArea');
135     for (var i = 0; i <= areas.length - 1; i++) {
136       areas[i].classList.remove("hidden");
137     }
138     setTimeout(maybeHideUI, 1000);
139   }
140   gUIHideCountdown = 5;
141 }
142
143 function maybeHideUI() {
144   gUIHideCountdown--;
145   if (gUIHideCountdown <= 0) {
146     var areas = document.getElementsByClassName('overlayArea');
147     for (var i = 0; i <= areas.length - 1; i++) {
148       areas[i].classList.add("hidden");
149     }
150   }
151   else {
152     setTimeout(maybeHideUI, 1000);
153   }
154 }
155
156 function toggleTrackArea() {
157   var fs = document.getElementById("trackArea");
158   if (fs.style.display != "block") {
159     fs.style.display = "block";
160     showUI();
161   }
162   else {
163     fs.style.display = "none";
164   }
165 }
166
167 function toggleSettings() {
168   var fs = document.getElementById("settingsArea");
169   if (fs.style.display != "block") {
170     fs.style.display = "block";
171     showUI();
172   }
173   else {
174     fs.style.display = "none";
175   }
176 }
177
178 function toggleFullscreen() {
179   if ((document.fullScreenElement && document.fullScreenElement !== null) ||
180       (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
181       (document.webkitFullScreenElement && document.webkitFullScreenElement !== null)) {
182     if (document.cancelFullScreen) {
183       document.cancelFullScreen();
184     } else if (document.mozCancelFullScreen) {
185       document.mozCancelFullScreen();
186     } else if (document.webkitCancelFullScreen) {
187       document.webkitCancelFullScreen();
188     }
189   }
190   else {
191     var elem = document.getElementById("body");
192     if (elem.requestFullScreen) {
193       elem.requestFullScreen();
194     } else if (elem.mozRequestFullScreen) {
195       elem.mozRequestFullScreen();
196     } else if (elem.webkitRequestFullScreen) {
197       elem.webkitRequestFullScreen();
198     }
199   }
200 }
201
202 function showUploadDialog() {
203   var dia = document.getElementById("dialogArea");
204   var areas = dia.children;
205   for (var i = 0; i <= areas.length - 1; i++) {
206     areas[i].style.display = "none";
207   }
208   document.getElementById("uploadDialog").style.display = "block";
209   document.getElementById("uploadTrackButton").disabled = true;
210   dia.classList.remove("hidden");
211 }
212
213 function showGLWarningDialog() {
214   var dia = document.getElementById("dialogArea");
215   var areas = dia.children;
216   for (var i = 0; i <= areas.length - 1; i++) {
217     areas[i].style.display = "none";
218   }
219   document.getElementById("noGLwarning").style.display = "block";
220   dia.classList.remove("hidden");
221 }
222
223 function cancelDialog() {
224   document.getElementById("dialogArea").classList.add("hidden");
225   document.getElementById("uploadTrackButton").disabled = false;
226 }
227
228 var uiEvHandler = {
229   handleEvent: function(aEvent) {
230     var touchEvent = aEvent.type.indexOf('touch') != -1;
231
232     switch (aEvent.type) {
233       case "mousedown":
234       case "touchstart":
235       case "mousemove":
236       case "touchmove":
237       case "mouseup":
238       case "touchend":
239       case "keydown":
240         showUI();
241         break;
242     }
243   }
244 };
245
246 function setUploadField(aField) {
247   switch (aField.id) {
248     case "uploadUser":
249       gPrefs.set(gDebug ? "osm_dev_user" : "osm_user", aField.value);
250       document.getElementById("uploadTrackButton").disabled = !aField.value.length;
251       break;
252     case "uploadPwd":
253       gPrefs.set(gDebug ? "osm_dev_pwd" : "osm_pwd", aField.value);
254       break;
255   }
256 }
257
258 function makeISOString(aTimestamp) {
259   // ISO time format is YYYY-MM-DDTHH:mm:ssZ
260   var tsDate = new Date(aTimestamp);
261   // Note that .getUTCMonth() returns a number between 0 and 11 (0 for January)!
262   return tsDate.getUTCFullYear() + "-" +
263          (tsDate.getUTCMonth() < 9 ? "0" : "") + (tsDate.getUTCMonth() + 1 ) + "-" +
264          (tsDate.getUTCDate() < 10 ? "0" : "") + tsDate.getUTCDate() + "T" +
265          (tsDate.getUTCHours() < 10 ? "0" : "") + tsDate.getUTCHours() + ":" +
266          (tsDate.getUTCMinutes() < 10 ? "0" : "") + tsDate.getUTCMinutes() + ":" +
267          (tsDate.getUTCSeconds() < 10 ? "0" : "") + tsDate.getUTCSeconds() + "Z";
268 }
269
270 function convertTrack(aTargetFormat) {
271   var out = "";
272   switch (aTargetFormat) {
273     case "gpx":
274       out += '<?xml version="1.0" encoding="UTF-8" ?>' + "\n\n";
275       out += '<gpx version="1.0" creator="Lantea" xmlns="http://www.topografix.com/GPX/1/0">' + "\n";
276       if (gTrack.length) {
277         out += '  <trk>' + "\n";
278         out += '    <trkseg>' + "\n";
279         for (var i = 0; i < gTrack.length; i++) {
280           if (gTrack[i].beginSegment && i > 0) {
281             out += '    </trkseg>' + "\n";
282             out += '    <trkseg>' + "\n";
283           }
284           out += '      <trkpt lat="' + gTrack[i].coords.latitude + '" lon="' +
285                                         gTrack[i].coords.longitude + '">' + "\n";
286           if (gTrack[i].coords.altitude) {
287             out += '        <ele>' + gTrack[i].coords.altitude + '</ele>' + "\n";
288           }
289           out += '        <time>' + makeISOString(gTrack[i].time) + '</time>' + "\n";
290           out += '      </trkpt>' + "\n";
291         }
292         out += '    </trkseg>' + "\n";
293         out += '  </trk>' + "\n";
294       }
295       out += '</gpx>' + "\n";
296       break;
297     case "json":
298       out = JSON.stringify(gTrack);
299       break;
300     default:
301       break;
302   }
303   return out;
304 }
305
306 function saveTrack() {
307   if (gTrack.length) {
308     var outDataURI = "data:application/gpx+xml," +
309                      encodeURIComponent(convertTrack("gpx"));
310     window.open(outDataURI, 'GPX Track');
311   }
312 }
313
314 function saveTrackDump() {
315   if (gTrack.length) {
316     var outDataURI = "data:application/json," +
317                      encodeURIComponent(convertTrack("json"));
318     window.open(outDataURI, 'JSON dump');
319   }
320 }
321
322 function uploadTrack() {
323   // Hide all areas in the dialog.
324   var dia = document.getElementById("dialogArea");
325   var areas = dia.children;
326   for (var i = 0; i <= areas.length - 1; i++) {
327     areas[i].style.display = "none";
328   }
329   // Reset all the fields in the status area.
330   document.getElementById("uploadStatusCloseButton").disabled = true;
331   document.getElementById("uploadInProgress").style.display = "block";
332   document.getElementById("uploadSuccess").style.display = "none";
333   document.getElementById("uploadFailed").style.display = "none";
334   document.getElementById("uploadError").style.display = "none";
335   document.getElementById("uploadErrorMsg").textContent = "";
336   // Now show the status area.
337   document.getElementById("uploadStatus").style.display = "block";
338
339   // See http://wiki.openstreetmap.org/wiki/Api06#Uploading_traces
340   var trackBlob = new Blob([convertTrack("gpx")],
341                            { "type" : "application/gpx+xml" });
342   var formData = new FormData();
343   formData.append("file", trackBlob);
344   var desc = document.getElementById("uploadDesc").value;
345   formData.append("description",
346                   desc.length ? desc : "Track recorded via Lantea Maps");
347   //formData.append("tags", "");
348   formData.append("visibility",
349                   document.getElementById("uploadVisibility").value);
350   // Do an empty POST request first, so that we don't send everything,
351   // then ask for credentials, and then send again.
352   var hXHR = new XMLHttpRequest();
353   hXHR.onreadystatechange = function() {
354     if (hXHR.readyState == 4 && (hXHR.status == 200 || hXHR.status == 400)) {
355       // 400 is Bad Request, but that's expected as this was empty.
356       // So far so good, init actual upload.
357       var XHR = new XMLHttpRequest();
358       XHR.onreadystatechange = function() {
359         if (XHR.readyState == 4 && XHR.status == 200) {
360           // Everthing looks fine.
361           reportUploadStatus(true);
362         } else if (XHR.readyState == 4 && XHR.status != 200) {
363           // Fetched the wrong page or network error...
364           reportUploadStatus(false);
365         }
366       };
367       XHR.open("POST", gOSMAPIURL + "api/0.6/gpx/create", true);
368       // Cross-Origin XHR doesn't allow username/password (HTTP Auth).
369       // So, we'll ask the user for entering credentials with rather ugly UI.
370       XHR.withCredentials = true;
371       try {
372         XHR.send(formData); // Send actual form data.
373       }
374       catch (e) {
375         reportUploadStatus(false, e);
376       }
377     } else if (hXHR.readyState == 4 && hXHR.status != 200) {
378       // Fetched the wrong page or network error...
379       reportUploadStatus(false);
380     }
381   };
382   hXHR.open("POST", gOSMAPIURL + "api/0.6/gpx/create", true);
383   // Cross-Origin XHR doesn't allow username/password (HTTP Auth).
384   // So, we'll ask the user for entering credentials with rather ugly UI.
385   hXHR.withCredentials = true;
386   try {
387     hXHR.send(); // Empty request, see above.
388   }
389   catch (e) {
390     reportUploadStatus(false, e);
391   }
392 }
393
394 function reportUploadStatus(aSuccess, aMessage) {
395   document.getElementById("uploadStatusCloseButton").disabled = false;
396   document.getElementById("uploadInProgress").style.display = "none";
397   if (aSuccess) {
398     document.getElementById("uploadSuccess").style.display = "block";
399   }
400   else if (aMessage) {
401     document.getElementById("uploadErrorMsg").textContent = aMessage;
402     document.getElementById("uploadError").style.display = "block";
403   }
404   else {
405     document.getElementById("uploadFailed").style.display = "block";
406   }
407 }
408
409 var gPrefs = {
410   objStore: "prefs",
411
412   get: function(aKey, aCallback) {
413     if (!mainDB)
414       return;
415     var transaction = mainDB.transaction([this.objStore]);
416     var request = transaction.objectStore(this.objStore).get(aKey);
417     request.onsuccess = function(event) {
418       aCallback(request.result, event);
419     };
420     request.onerror = function(event) {
421       // Errors can be handled here.
422       aCallback(undefined, event);
423     };
424   },
425
426   set: function(aKey, aValue, aCallback) {
427     if (!mainDB)
428       return;
429     var success = false;
430     var transaction = mainDB.transaction([this.objStore], "readwrite");
431     var objStore = transaction.objectStore(this.objStore);
432     var request = objStore.put(aValue, aKey);
433     request.onsuccess = function(event) {
434       success = true;
435       if (aCallback)
436         aCallback(success, event);
437     };
438     request.onerror = function(event) {
439       // Errors can be handled here.
440       if (aCallback)
441         aCallback(success, event);
442     };
443   },
444
445   unset: function(aKey, aCallback) {
446     if (!mainDB)
447       return;
448     var success = false;
449     var transaction = mainDB.transaction([this.objStore], "readwrite");
450     var request = transaction.objectStore(this.objStore).delete(aKey);
451     request.onsuccess = function(event) {
452       success = true;
453       if (aCallback)
454         aCallback(success, event);
455     };
456     request.onerror = function(event) {
457       // Errors can be handled here.
458       if (aCallback)
459         aCallback(success, event);
460     }
461   }
462 };
463
464 var gTrackStore = {
465   objStore: "track",
466
467   getList: function(aCallback) {
468     if (!mainDB)
469       return;
470     var transaction = mainDB.transaction([this.objStore]);
471     var objStore = transaction.objectStore(this.objStore);
472     if (objStore.getAll) { // currently Mozilla-specific
473       objStore.getAll().onsuccess = function(event) {
474         aCallback(event.target.result);
475       };
476     }
477     else { // Use cursor (standard method).
478       var tPoints = [];
479       objStore.openCursor().onsuccess = function(event) {
480         var cursor = event.target.result;
481         if (cursor) {
482           tPoints.push(cursor.value);
483           cursor.continue();
484         }
485         else {
486           aCallback(tPoints);
487         }
488       };
489     }
490   },
491
492   getListStepped: function(aCallback) {
493     if (!mainDB)
494       return;
495     var transaction = mainDB.transaction([this.objStore]);
496     var objStore = transaction.objectStore(this.objStore);
497     // Use cursor in reverse direction (so we get the most recent position first)
498     objStore.openCursor(null, "prev").onsuccess = function(event) {
499       var cursor = event.target.result;
500       if (cursor) {
501         aCallback(cursor.value);
502         cursor.continue();
503       }
504       else {
505         aCallback(null);
506       }
507     };
508   },
509
510   push: function(aValue, aCallback) {
511     if (!mainDB)
512       return;
513     var transaction = mainDB.transaction([this.objStore], "readwrite");
514     var objStore = transaction.objectStore(this.objStore);
515     var request = objStore.add(aValue);
516     request.onsuccess = function(event) {
517       if (aCallback)
518         aCallback(request.result, event);
519     };
520     request.onerror = function(event) {
521       // Errors can be handled here.
522       if (aCallback)
523         aCallback(false, event);
524     };
525   },
526
527   clear: function(aCallback) {
528     if (!mainDB)
529       return;
530     var success = false;
531     var transaction = mainDB.transaction([this.objStore], "readwrite");
532     var request = transaction.objectStore(this.objStore).clear();
533     request.onsuccess = function(event) {
534       success = true;
535       if (aCallback)
536         aCallback(success, event);
537     };
538     request.onerror = function(event) {
539       // Errors can be handled here.
540       if (aCallback)
541         aCallback(success, event);
542     }
543   }
544 };