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