remove the failed messages as well
[lantea.git] / js / ui.js
... / ...
CommitLineData
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.
6window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
7var mainDB;
8
9var gUIHideCountdown = 0;
10var gWaitCounter = 0;
11var gAction, gActionLabel;
12var gOSMAPIURL = "http://api.openstreetmap.org/";
13
14window.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
64function postInit(aEvent) {
65 gAction.removeEventListener(aEvent.type, postInit, false);
66 console.log("init done, draw map.");
67 gMapPrefsLoaded = true;
68 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
85window.onresize = function() {
86 resizeAndDraw();
87}
88
89function 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
130function 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
141function 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
154function 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
165function 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
176function 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
200function 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
211function cancelDialog() {
212 document.getElementById("dialogArea").classList.add("hidden");
213 document.getElementById("uploadTrackButton").disabled = false;
214}
215
216var uiEvHandler = {
217 handleEvent: function(aEvent) {
218 var touchEvent = aEvent.type.indexOf('touch') != -1;
219
220 switch (aEvent.type) {
221 case "mousedown":
222 case "touchstart":
223 case "mousemove":
224 case "touchmove":
225 case "mouseup":
226 case "touchend":
227 case "keydown":
228 showUI();
229 break;
230 }
231 }
232};
233
234function setUploadField(aField) {
235 switch (aField.id) {
236 case "uploadUser":
237 gPrefs.set(gDebug ? "osm_dev_user" : "osm_user", aField.value);
238 document.getElementById("uploadTrackButton").disabled = !aField.value.length;
239 break;
240 case "uploadPwd":
241 gPrefs.set(gDebug ? "osm_dev_pwd" : "osm_pwd", aField.value);
242 break;
243 }
244}
245
246function makeISOString(aTimestamp) {
247 // ISO time format is YYYY-MM-DDTHH:mm:ssZ
248 var tsDate = new Date(aTimestamp);
249 // Note that .getUTCMonth() returns a number between 0 and 11 (0 for January)!
250 return tsDate.getUTCFullYear() + "-" +
251 (tsDate.getUTCMonth() < 9 ? "0" : "") + (tsDate.getUTCMonth() + 1 ) + "-" +
252 (tsDate.getUTCDate() < 10 ? "0" : "") + tsDate.getUTCDate() + "T" +
253 (tsDate.getUTCHours() < 10 ? "0" : "") + tsDate.getUTCHours() + ":" +
254 (tsDate.getUTCMinutes() < 10 ? "0" : "") + tsDate.getUTCMinutes() + ":" +
255 (tsDate.getUTCSeconds() < 10 ? "0" : "") + tsDate.getUTCSeconds() + "Z";
256}
257
258function convertTrack(aTargetFormat) {
259 var out = "";
260 switch (aTargetFormat) {
261 case "gpx":
262 out += '<?xml version="1.0" encoding="UTF-8" ?>' + "\n\n";
263 out += '<gpx version="1.0" creator="Lantea" xmlns="http://www.topografix.com/GPX/1/0">' + "\n";
264 if (gTrack.length) {
265 out += ' <trk>' + "\n";
266 out += ' <trkseg>' + "\n";
267 for (var i = 0; i < gTrack.length; i++) {
268 if (gTrack[i].beginSegment && i > 0) {
269 out += ' </trkseg>' + "\n";
270 out += ' <trkseg>' + "\n";
271 }
272 out += ' <trkpt lat="' + gTrack[i].coords.latitude + '" lon="' +
273 gTrack[i].coords.longitude + '">' + "\n";
274 if (gTrack[i].coords.altitude) {
275 out += ' <ele>' + gTrack[i].coords.altitude + '</ele>' + "\n";
276 }
277 out += ' <time>' + makeISOString(gTrack[i].time) + '</time>' + "\n";
278 out += ' </trkpt>' + "\n";
279 }
280 out += ' </trkseg>' + "\n";
281 out += ' </trk>' + "\n";
282 }
283 out += '</gpx>' + "\n";
284 break;
285 case "json":
286 out = JSON.stringify(gTrack);
287 break;
288 default:
289 break;
290 }
291 return out;
292}
293
294function saveTrack() {
295 if (gTrack.length) {
296 var outDataURI = "data:application/gpx+xml," +
297 encodeURIComponent(convertTrack("gpx"));
298 window.open(outDataURI, 'GPX Track');
299 }
300}
301
302function saveTrackDump() {
303 if (gTrack.length) {
304 var outDataURI = "data:application/json," +
305 encodeURIComponent(convertTrack("json"));
306 window.open(outDataURI, 'JSON dump');
307 }
308}
309
310function uploadTrack() {
311 // Hide all areas in the dialog.
312 var dia = document.getElementById("dialogArea");
313 var areas = dia.children;
314 for (var i = 0; i <= areas.length - 1; i++) {
315 areas[i].style.display = "none";
316 }
317 // Reset all the fields in the status area.
318 document.getElementById("uploadStatusCloseButton").disabled = true;
319 document.getElementById("uploadInProgress").style.display = "block";
320 document.getElementById("uploadSuccess").style.display = "none";
321 document.getElementById("uploadFailed").style.display = "none";
322 document.getElementById("uploadError").style.display = "none";
323 document.getElementById("uploadErrorMsg").textContent = "";
324 // Now show the status area.
325 document.getElementById("uploadStatus").style.display = "block";
326
327 // See http://wiki.openstreetmap.org/wiki/Api06#Uploading_traces
328 var trackBlob = new Blob([convertTrack("gpx")],
329 { "type" : "application/gpx+xml" });
330 var formData = new FormData();
331 formData.append("file", trackBlob);
332 var desc = document.getElementById("uploadDesc").value;
333 formData.append("description",
334 desc.length ? desc : "Track recorded via Lantea Maps");
335 //formData.append("tags", "");
336 formData.append("visibility",
337 document.getElementById("uploadVisibility").value);
338 // Do an empty POST request first, so that we don't send everything,
339 // then ask for credentials, and then send again.
340 var hXHR = new XMLHttpRequest();
341 hXHR.onreadystatechange = function() {
342 if (hXHR.readyState == 4 && (hXHR.status == 200 || hXHR.status == 400)) {
343 // 400 is Bad Request, but that's expected as this was empty.
344 // So far so good, init actual upload.
345 var XHR = new XMLHttpRequest();
346 XHR.onreadystatechange = function() {
347 if (XHR.readyState == 4 && XHR.status == 200) {
348 // Everthing looks fine.
349 reportUploadStatus(true);
350 } else if (XHR.readyState == 4 && XHR.status != 200) {
351 // Fetched the wrong page or network error...
352 reportUploadStatus(false);
353 }
354 };
355 XHR.open("POST", gOSMAPIURL + "api/0.6/gpx/create", true);
356 // Cross-Origin XHR doesn't allow username/password (HTTP Auth).
357 // So, we'll ask the user for entering credentials with rather ugly UI.
358 XHR.withCredentials = true;
359 try {
360 XHR.send(formData); // Send actual form data.
361 }
362 catch (e) {
363 reportUploadStatus(false, e);
364 }
365 } else if (hXHR.readyState == 4 && hXHR.status != 200) {
366 // Fetched the wrong page or network error...
367 reportUploadStatus(false);
368 }
369 };
370 hXHR.open("POST", gOSMAPIURL + "api/0.6/gpx/create", true);
371 // Cross-Origin XHR doesn't allow username/password (HTTP Auth).
372 // So, we'll ask the user for entering credentials with rather ugly UI.
373 hXHR.withCredentials = true;
374 try {
375 hXHR.send(); // Empty request, see above.
376 }
377 catch (e) {
378 reportUploadStatus(false, e);
379 }
380}
381
382function reportUploadStatus(aSuccess, aMessage) {
383 document.getElementById("uploadStatusCloseButton").disabled = false;
384 document.getElementById("uploadInProgress").style.display = "none";
385 if (aSuccess) {
386 document.getElementById("uploadSuccess").style.display = "block";
387 }
388 else if (aMessage) {
389 document.getElementById("uploadErrorMsg").textContent = aMessage;
390 document.getElementById("uploadError").style.display = "block";
391 }
392 else {
393 document.getElementById("uploadFailed").style.display = "block";
394 }
395}
396
397var gPrefs = {
398 objStore: "prefs",
399
400 get: function(aKey, aCallback) {
401 if (!mainDB)
402 return;
403 var transaction = mainDB.transaction([this.objStore]);
404 var request = transaction.objectStore(this.objStore).get(aKey);
405 request.onsuccess = function(event) {
406 aCallback(request.result, event);
407 };
408 request.onerror = function(event) {
409 // Errors can be handled here.
410 aCallback(undefined, event);
411 };
412 },
413
414 set: function(aKey, aValue, aCallback) {
415 if (!mainDB)
416 return;
417 var success = false;
418 var transaction = mainDB.transaction([this.objStore], "readwrite");
419 var objStore = transaction.objectStore(this.objStore);
420 var request = objStore.put(aValue, aKey);
421 request.onsuccess = function(event) {
422 success = true;
423 if (aCallback)
424 aCallback(success, event);
425 };
426 request.onerror = function(event) {
427 // Errors can be handled here.
428 if (aCallback)
429 aCallback(success, event);
430 };
431 },
432
433 unset: function(aKey, aCallback) {
434 if (!mainDB)
435 return;
436 var success = false;
437 var transaction = mainDB.transaction([this.objStore], "readwrite");
438 var request = transaction.objectStore(this.objStore).delete(aKey);
439 request.onsuccess = function(event) {
440 success = true;
441 if (aCallback)
442 aCallback(success, event);
443 };
444 request.onerror = function(event) {
445 // Errors can be handled here.
446 if (aCallback)
447 aCallback(success, event);
448 }
449 }
450};
451
452var gTrackStore = {
453 objStore: "track",
454
455 getList: function(aCallback) {
456 if (!mainDB)
457 return;
458 var transaction = mainDB.transaction([this.objStore]);
459 var objStore = transaction.objectStore(this.objStore);
460 if (objStore.getAll) { // currently Mozilla-specific
461 objStore.getAll().onsuccess = function(event) {
462 aCallback(event.target.result);
463 };
464 }
465 else { // Use cursor (standard method).
466 var tPoints = [];
467 objStore.openCursor().onsuccess = function(event) {
468 var cursor = event.target.result;
469 if (cursor) {
470 tPoints.push(cursor.value);
471 cursor.continue();
472 }
473 else {
474 aCallback(tPoints);
475 }
476 };
477 }
478 },
479
480 getListStepped: function(aCallback) {
481 if (!mainDB)
482 return;
483 var transaction = mainDB.transaction([this.objStore]);
484 var objStore = transaction.objectStore(this.objStore);
485 // Use cursor in reverse direction (so we get the most recent position first)
486 objStore.openCursor(null, "prev").onsuccess = function(event) {
487 var cursor = event.target.result;
488 if (cursor) {
489 aCallback(cursor.value);
490 cursor.continue();
491 }
492 else {
493 aCallback(null);
494 }
495 };
496 },
497
498 push: function(aValue, aCallback) {
499 if (!mainDB)
500 return;
501 var transaction = mainDB.transaction([this.objStore], "readwrite");
502 var objStore = transaction.objectStore(this.objStore);
503 var request = objStore.add(aValue);
504 request.onsuccess = function(event) {
505 if (aCallback)
506 aCallback(request.result, event);
507 };
508 request.onerror = function(event) {
509 // Errors can be handled here.
510 if (aCallback)
511 aCallback(false, event);
512 };
513 },
514
515 clear: function(aCallback) {
516 if (!mainDB)
517 return;
518 var success = false;
519 var transaction = mainDB.transaction([this.objStore], "readwrite");
520 var request = transaction.objectStore(this.objStore).clear();
521 request.onsuccess = function(event) {
522 success = true;
523 if (aCallback)
524 aCallback(success, event);
525 };
526 request.onerror = function(event) {
527 // Errors can be handled here.
528 if (aCallback)
529 aCallback(success, event);
530 }
531 }
532};