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