]> err.no Git - mapper/blob - src/map-download.c
Start to rewrite the GPS system to support location information from multiple sources.
[mapper] / src / map-download.c
1 /*
2  * This file is part of mapper
3  *
4  * Copyright (C) 2007 Kaj-Michael Lang
5  * Copyright (C) 2006-2007 John Costigan.
6  *
7  * POI and GPS-Info code originally written by Cezary Jackiewicz.
8  *
9  * Default map data provided by http://www.openstreetmap.org/
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License along
22  * with this program; if not, write to the Free Software Foundation, Inc.,
23  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24  */
25
26 #include "config.h"
27
28 #include <unistd.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <strings.h>
32 #include <stddef.h>
33 #include <locale.h>
34 #include <math.h>
35 #include <errno.h>
36 #include <sys/wait.h>
37 #include <glib/gstdio.h>
38 #include <fcntl.h>
39 #include <curl/multi.h>
40 #include <libintl.h>
41 #include <locale.h>
42
43 #include "hildon-mapper.h"
44
45 #include "utils.h"
46 #include "map.h"
47 #include "osm.h"
48 #include "db.h"
49 #include "osm-db.h"
50 #include "poi.h"
51 #include "route.h"
52 #include "gps.h"
53 #include "mapper-types.h"
54 #include "ui-common.h"
55 #include "settings.h"
56 #include "latlon.h"
57 #include "gpx.h"
58 #include "map-download.h"
59 #include "iap.h"
60
61 static guint _num_downloads=0;
62 static guint _curr_download=0;
63
64 static gchar *map_construct_url(guint tilex, guint tiley, guint zoom);
65
66 static gboolean 
67 get_next_pui(gpointer key, gpointer value, ProgressUpdateInfo ** data)
68 {
69 *data = key;
70 return TRUE;
71 }
72
73 static gint
74 download_comparefunc(const ProgressUpdateInfo * a, const ProgressUpdateInfo * b, gpointer user_data)
75 {
76 gint diff = (a->priority - b->priority);
77 if (diff)
78         return diff;
79 diff = (a->tilex - b->tilex);
80 if (diff)
81         return diff;
82 diff = (a->tiley - b->tiley);
83 if (diff)
84         return diff;
85 diff = (a->zoom - b->zoom);
86 if (diff)
87         return diff;
88 diff = (a->repo - b->repo);
89 if (diff)
90         return diff;
91 /* Otherwise, deletes are "greatest" (least priority). */
92 if (!a->retries)
93         return (b->retries ? -1 : 0);
94 else if (!b->retries)
95         return (a->retries ? 1 : 0);
96 /* Do updates after non-updates (because they'll both be done anyway). */
97 return (a->retries - b->retries);
98 }
99
100 /**
101  * Free a ProgressUpdateInfo data structure that was allocated during the
102  * auto-map-download process.
103  */
104 static void 
105 progress_update_info_free(ProgressUpdateInfo * pui)
106 {
107 g_free(pui->src_str);
108 g_free(pui->dest_str);
109 g_slice_free(ProgressUpdateInfo, pui);
110 }
111
112 gboolean 
113 map_download_timeout()
114 {
115 static guint destroy_counter = 50;
116 gint num_transfers = 0, num_msgs = 0;
117 gint deletes_left = 50; /* only do 50 deletes at a time. */
118 CURLMsg *msg;
119
120 if (_curl_multi && CURLM_CALL_MULTI_PERFORM == curl_multi_perform(_curl_multi, &num_transfers))
121         return TRUE;    /* Give UI a chance first. */
122
123 while (_curl_multi && (msg = curl_multi_info_read(_curl_multi, &num_msgs))) {
124         if (msg->msg == CURLMSG_DONE) {
125                 if (msg->easy_handle == _autoroute_data.curl_easy) {
126                         /* This is the autoroute download. */
127                         /* Now, parse the autoroute and update the display. */
128                         if (_autoroute_data.enabled && parse_gpx(&_route,
129                                          _autoroute_data.rdl_data.bytes,
130                                          _autoroute_data.rdl_data.bytes_read, 0)) {
131                                 /* Find the nearest route point, if we're connected. */
132                                 route_find_nearest_point();
133                                 map_force_redraw();
134                         }
135                         cancel_autoroute(TRUE); /* We're done. Clean up. */
136                 } else {
137                         ProgressUpdateInfo *pui = g_hash_table_lookup(_pui_by_easy, msg->easy_handle);
138                         g_queue_push_head(_curl_easy_queue, msg->easy_handle);
139                         g_hash_table_remove(_pui_by_easy, msg->easy_handle);
140                         fclose(pui->file);
141                         if (msg->data.result != CURLE_OK)
142                                 g_unlink(pui->dest_str);        /* Delete so we try again. */
143                         curl_multi_remove_handle(_curl_multi, msg->easy_handle);
144                         g_idle_add_full(G_PRIORITY_HIGH_IDLE, (GSourceFunc)map_download_idle_refresh, pui, NULL);
145                 }
146         }
147 }
148
149 /* Up to 1 transfer per tile. */
150 while (num_transfers < (BUF_WIDTH_TILES * BUF_HEIGHT_TILES) && g_tree_nnodes(_pui_tree)) {
151         ProgressUpdateInfo *pui;
152         g_tree_foreach(_pui_tree, (GTraverseFunc) get_next_pui, &pui);
153
154         if (pui->retries) {
155                 /* This is a download. */
156                 FILE *f;
157                 g_tree_steal(_pui_tree, pui);
158                 g_tree_insert(_downloading_tree, pui, pui);
159
160                 pui->src_str = map_construct_url(pui->tilex, pui->tiley, pui->zoom);
161                 pui->dest_str = g_strdup_printf("%s/%u/%u/%u.jpg",
162                                     pui->repo->cache_dir, pui->zoom,
163                                     pui->tilex, pui->tiley);
164
165                 if (!pui->src_str) {
166                         /* Failed to generate URL. */
167                         g_idle_add_full(G_PRIORITY_HIGH_IDLE,(GSourceFunc)map_download_idle_refresh, pui, NULL);
168                         continue;
169                 }
170
171                 /* Check to see if we need to overwrite. */
172                 if (pui->retries > 0) {
173                         /* We're not updating - check if file already exists. */
174                         if (g_file_test(pui->dest_str, G_FILE_TEST_EXISTS)) {
175                                 g_idle_add_full(G_PRIORITY_HIGH_IDLE, (GSourceFunc)map_download_idle_refresh, pui, NULL);
176                                 continue;
177                         }
178                 }
179
180                 /* Attempt to open the file for writing. */
181                 if (!(f = g_fopen(pui->dest_str, "w")) && errno == ENOENT) {
182                         /* Directory doesn't exist yet - create it, then we'll retry */
183                         gchar buffer[BUFFER_SIZE];
184                         g_snprintf(buffer, sizeof(buffer), "%s/%u/%u",
185                                  pui->repo->cache_dir, pui->zoom, pui->tilex);
186                         g_mkdir_with_parents(buffer, 0775);
187                         f = g_fopen(pui->dest_str, "w");
188                 }
189
190                 if (f) {
191                         CURL *curl_easy;
192                         pui->file = f;
193                         curl_easy = g_queue_pop_tail(_curl_easy_queue);
194                         if (!curl_easy) {
195                                 /* Need a new curl_easy. */
196                                 MACRO_CURL_EASY_INIT(curl_easy);
197                         }
198                         curl_easy_setopt(curl_easy, CURLOPT_URL, pui->src_str);
199                         curl_easy_setopt(curl_easy, CURLOPT_WRITEDATA, f);
200                         g_hash_table_insert(_pui_by_easy, curl_easy, pui);
201                         if (!_curl_multi) {
202                                 /* Initialize CURL. */
203                                 _curl_multi = curl_multi_init();
204                                 /*curl_multi_setopt(_curl_multi, CURLMOPT_PIPELINING, 1); */
205                         }
206                         curl_multi_add_handle(_curl_multi, curl_easy);
207                         num_transfers++;
208                 } else {
209                         /* Unable to open tile file for writing. */
210                         gchar buffer[BUFFER_SIZE];
211                         g_snprintf(buffer, sizeof(buffer), "%s:\n%s",
212                                  _("Failed to open file for writing"),
213                                  pui->dest_str);
214                         MACRO_BANNER_SHOW_INFO(_window, buffer);
215                         g_idle_add_full(G_PRIORITY_HIGH_IDLE, (GSourceFunc)map_download_idle_refresh, pui, NULL);
216                         continue;
217                 }
218         } else if (--deletes_left) {
219                 /* This is a delete. */
220                 gchar buffer[BUFFER_SIZE];
221                 g_tree_steal(_pui_tree, pui);
222                 g_tree_insert(_downloading_tree, pui, pui);
223
224                 g_snprintf(buffer, sizeof(buffer), "%s/%u/%u/%u.jpg",
225                         pui->repo->cache_dir, pui->zoom, 
226                         pui->tilex,     pui->tiley);
227                 g_unlink(buffer);
228                 g_idle_add_full(G_PRIORITY_HIGH_IDLE,(GSourceFunc)map_download_idle_refresh, pui, NULL);
229         } else
230                 break;
231 }
232
233 if (!(num_transfers || g_tree_nnodes(_pui_tree))) {
234         /* Destroy curl after 50 counts (5 seconds). */
235         if (--destroy_counter) {
236                 /* Clean up curl. */
237                 CURL *curr;
238                 while ((curr = g_queue_pop_tail(_curl_easy_queue)))
239                         curl_easy_cleanup(curr);
240
241                 curl_multi_cleanup(_curl_multi);
242                 _curl_multi = NULL;
243
244                 _curl_sid = 0;
245                 return FALSE;
246         }
247 } else
248         destroy_counter = 50;
249
250 return TRUE;
251 }
252
253 /**
254  * Given a wms uri pattern, compute the coordinate transformation and
255  * trimming.
256  * 'proj' is used for the conversion
257  */
258 static gchar *
259 map_convert_wms_to_wms(gint tilex, gint tiley, gint zoomlevel, gchar * uri)
260 {
261 gint system_retcode;
262 gchar cmd[BUFFER_SIZE], srs[BUFFER_SIZE];
263 gchar *ret = NULL;
264 FILE *in;
265 gdouble lon1, lat1, lon2, lat2;
266
267 gchar *widthstr = strcasestr(uri, "WIDTH=");
268 gchar *heightstr = strcasestr(uri, "HEIGHT=");
269 gchar *srsstr = strcasestr(uri, "SRS=EPSG");
270 gchar *srsstre = strchr(srsstr, '&');
271
272 /* missing: test if found */
273 strcpy(srs, "epsg");
274 strncpy(srs + 4, srsstr + 8, 256);
275 /* missing: test srsstre-srsstr < 526 */
276 srs[srsstre - srsstr - 4] = 0;
277 /* convert to lower, as WMC is EPSG and cs2cs is epsg */
278
279 gint dwidth = widthstr ? atoi(widthstr + 6) - TILE_SIZE_PIXELS : 0;
280 gint dheight = heightstr ? atoi(heightstr + 7) - TILE_SIZE_PIXELS : 0;
281
282 unit2latlon(tile2zunit(tilex, zoomlevel) - pixel2zunit(dwidth / 2, zoomlevel),
283             tile2zunit(tiley + 1, zoomlevel) + pixel2zunit((dheight + 1) / 2, zoomlevel), lat1, lon1);
284
285 unit2latlon(tile2zunit(tilex + 1, zoomlevel) + pixel2zunit((dwidth + 1) / 2, zoomlevel), 
286                 tile2zunit(tiley, zoomlevel) - pixel2zunit(dheight / 2, zoomlevel), lat2, lon2);
287
288 setlocale(LC_NUMERIC, "C");
289
290 g_snprintf(cmd, sizeof(cmd),
291          "(echo \"%.6f %.6f\"; echo \"%.6f %.6f\") | "
292          "/usr/bin/cs2cs +proj=longlat +datum=WGS84 +to +init=%s -f %%.6f "
293          " > /tmp/tmpcs2cs ", lon1, lat1, lon2, lat2, srs);
294 vprintf("Running command: %s\n", cmd);
295 system_retcode = system(cmd);
296
297 if (system_retcode)
298         g_printerr("cs2cs returned error code %d\n", WEXITSTATUS(system_retcode));
299 else if (!(in = g_fopen("/tmp/tmpcs2cs", "r")))
300         g_printerr("Cannot open results of conversion\n");
301 else if (5 != fscanf(in, "%lf %lf %s %lf %lf", &lon1, &lat1, cmd, &lon2, &lat2)) {
302         g_printerr("Wrong conversion\n");
303         fclose(in);
304 } else {
305         fclose(in);
306         ret = g_strdup_printf(uri, lon1, lat1, lon2, lat2);
307 }
308
309 setlocale(LC_NUMERIC, "");
310
311 return ret;
312 }
313
314
315 /**
316  * Given the xyz coordinates of our map coordinate system, write the qrst
317  * quadtree coordinates to buffer.
318  */
319 static void
320 map_convert_coords_to_quadtree_string(gint x, gint y, gint zoomlevel,
321                                       gchar * buffer, const gchar initial,
322                                       const gchar * const quadrant)
323 {
324 gchar *ptr = buffer;
325 gint n;
326
327 if (initial)
328         *ptr++ = initial;
329
330 for (n = 16 - zoomlevel; n >= 0; n--) {
331         gint xbit = (x >> n) & 1;
332         gint ybit = (y >> n) & 1;
333         *ptr++ = quadrant[xbit + 2 * ybit];
334 }
335 *ptr++ = '\0';
336 }
337
338 /**
339  * Construct the URL that we should fetch, based on the current URI format.
340  * This method works differently depending on if a "%s" string is present in
341  * the URI format, since that would indicate a quadtree-based map coordinate
342  * system.
343  */
344 static gchar *
345 map_construct_url(guint tilex, guint tiley, guint zoom)
346 {
347 switch (_curr_repo->type) {
348 case REPOTYPE_XYZ:
349         return g_strdup_printf(_curr_repo->url, tilex, tiley, zoom);
350
351 case REPOTYPE_XYZ_INV:
352         return g_strdup_printf(_curr_repo->url, 17 - zoom, tilex, tiley);
353
354 case REPOTYPE_QUAD_QRST:
355         {
356                 gchar location[MAX_ZOOM + 2];
357                 map_convert_coords_to_quadtree_string(tilex, tiley, zoom, location, 't', "qrts");
358                 return g_strdup_printf(_curr_repo->url, location);
359         }
360
361 case REPOTYPE_QUAD_ZERO:
362         {
363                 /* This is a zero-based quadtree URI. */
364                 gchar location[MAX_ZOOM + 2];
365                 map_convert_coords_to_quadtree_string(tilex, tiley, zoom, location, '\0', "0123");
366                 return g_strdup_printf(_curr_repo->url, location);
367         }
368
369 case REPOTYPE_WMS:
370         return map_convert_wms_to_wms(tilex, tiley, zoom, _curr_repo->url);
371
372 default:
373         return NULL;
374 }
375 return "";
376 }
377
378
379 gboolean 
380 map_download_idle_refresh(ProgressUpdateInfo * pui)
381 {
382 /* Test if download succeeded (only if retries != 0). */
383 if (!pui->retries || g_file_test(pui->dest_str, G_FILE_TEST_EXISTS)) {
384         gint zoom_diff = pui->zoom - _zoom;
385         /* Only refresh at same or "lower" (more detailed) zoom level. */
386         if (zoom_diff >= 0) {
387                 /* If zoom has changed since we first put in the request for
388                  * this tile, then we may have to update more than one tile. */
389                 guint tilex, tiley, tilex_end, tiley_end;
390                 for (tilex = pui->tilex << zoom_diff, tilex_end = tilex + (1 << zoom_diff); tilex < tilex_end; tilex++) {
391                         for (tiley = pui->tiley << zoom_diff, tiley_end = tiley + (1 << zoom_diff); tiley < tiley_end; tiley++) {
392                                 if ((tilex - _base_tilex) < BUF_WIDTH_TILES && (tiley - _base_tiley) < BUF_HEIGHT_TILES) {
393                                         map_render_tile(tilex, tiley, ((tilex - _base_tilex) << TILE_SIZE_P2), ((tiley - _base_tiley) << TILE_SIZE_P2), TRUE);
394                                         map_render_data();
395                                         gtk_widget_queue_draw_area
396                                             (_map_widget,
397                                              ((tilex - _base_tilex) << TILE_SIZE_P2) - _offsetx,
398                                              ((tiley - _base_tiley) << TILE_SIZE_P2) - _offsety,
399                                              TILE_SIZE_PIXELS, TILE_SIZE_PIXELS);
400                                 }
401                         }
402                 }
403         }
404 }
405 /* Else the download failed. Update retries and maybe try again. */
406 else {
407         if (pui->retries > 0)
408                 --pui->retries;
409         else if (pui->retries < 0)
410                 ++pui->retries;
411
412         if (pui->retries) {
413                 /* removal automatically calls progress_update_info_free(). */
414                 g_tree_steal(_downloading_tree, pui);
415                 g_tree_insert(_pui_tree, pui, pui);
416                 if (iap_is_connected() && !_curl_sid)
417                         _curl_sid = g_timeout_add(100,(GSourceFunc)map_download_timeout, NULL);
418                 /* Don't do anything else. */
419                 return FALSE;
420         } else {
421                 /* No more retries left - something must be wrong. */
422                 MACRO_BANNER_SHOW_INFO(_window, _("Error in download. Check internet connection and/or Map Repository URL Format."));
423         }
424 }
425
426 /* removal automatically calls progress_update_info_free(). */
427 g_tree_remove(_downloading_tree, pui);
428
429 if (++_curr_download == _num_downloads) {
430         _num_downloads = _curr_download = 0;
431         gtk_progress_bar_set_fraction(_progress_item, 0.0);
432         gtk_progress_bar_set_text(_progress_item, "");
433 } else {
434         gchar buffer[64];
435
436         g_snprintf(buffer, sizeof(buffer), _("Downloading maps (%d/%d)"), _curr_download, _num_downloads);
437         gtk_progress_bar_set_text(_progress_item, buffer);      
438         gtk_progress_bar_set_fraction(_progress_item, _curr_download / (double)_num_downloads);
439 }
440 return FALSE;
441 }
442
443 /**
444  * Initiate a download of the given xyz coordinates using the given buffer
445  * as the URL.  If the map already exists on disk, or if we are already
446  * downloading the map, then this method does nothing.
447  */
448 void 
449 map_initiate_download(guint tilex, guint tiley, guint zoom, gint retries)
450 {
451 ProgressUpdateInfo *pui;
452
453 iap_connect();
454
455 pui = g_slice_new(ProgressUpdateInfo);
456 pui->tilex = tilex;
457 pui->tiley = tiley;
458 pui->zoom = zoom;
459 pui->priority = (abs((gint) tilex - unit2tile(_center.unitx)) + abs((gint) tiley - unit2tile(_center.unity)));
460 if (!retries)
461         pui->priority = -pui->priority; /* "Negative" makes them lowest pri. */
462 pui->retries = retries;
463 pui->repo = _curr_repo;
464
465 if (g_tree_lookup(_pui_tree, pui) || g_tree_lookup(_downloading_tree, pui)) {
466         /* Already downloading. */
467         g_slice_free(ProgressUpdateInfo, pui);
468         return;
469 }
470 pui->src_str = NULL;
471 pui->dest_str = NULL;
472 pui->file = NULL;
473
474 g_tree_insert(_pui_tree, pui, pui);
475 if (iap_is_connected() && !_curl_sid)
476         _curl_sid = g_timeout_add(100, (GSourceFunc) map_download_timeout, NULL);
477
478 if (!_num_downloads++)
479         gtk_progress_bar_set_text(_progress_item, _("Downloading maps..."));    
480 }
481
482 void
483 map_download_init(void)
484 {
485 _curl_easy_queue = g_queue_new();
486 _pui_tree = g_tree_new_full((GCompareDataFunc) download_comparefunc, NULL, (GDestroyNotify) progress_update_info_free, NULL);
487 _downloading_tree = g_tree_new_full((GCompareDataFunc) download_comparefunc, NULL, (GDestroyNotify) progress_update_info_free, NULL);
488 _pui_by_easy = g_hash_table_new(g_direct_hash, g_direct_equal);
489 }
490
491 void
492 map_download_deinit(void) 
493 {
494 /* Clean up CURL. */
495 if (_curl_multi) {
496         CURL *curr;
497         CURLMsg *msg;
498         gint num_transfers, num_msgs;
499
500         /* First, remove all downloads from _pui_tree. */
501         g_tree_destroy(_pui_tree);
502
503         /* Finish up all downloads. */
504         while (CURLM_CALL_MULTI_PERFORM == curl_multi_perform(_curl_multi, &num_transfers) || num_transfers) {
505                 /* XXX: should inform the user why it's taking so damn long... */
506         }
507
508         /* Close all finished files. */
509         while ((msg = curl_multi_info_read(_curl_multi, &num_msgs))) {
510                 if (msg->msg == CURLMSG_DONE) {
511                         /* This is a map download. */
512                         ProgressUpdateInfo *pui = g_hash_table_lookup(_pui_by_easy, msg->easy_handle);
513                         g_queue_push_head(_curl_easy_queue, msg->easy_handle);
514                         g_hash_table_remove(_pui_by_easy, msg->easy_handle);
515                         fclose(pui->file);
516                         curl_multi_remove_handle(_curl_multi, msg->easy_handle);
517                 }
518         }
519
520         while ((curr = g_queue_pop_tail(_curl_easy_queue)))
521                 curl_easy_cleanup(curr);
522
523         curl_multi_cleanup(_curl_multi);
524         _curl_multi = NULL;
525
526         g_queue_free(_curl_easy_queue);
527         g_tree_destroy(_downloading_tree);
528         g_hash_table_destroy(_pui_by_easy);
529 }
530
531 if (_curl_sid) {
532     g_source_remove(_curl_sid);
533     _curl_sid = 0;
534 }  
535 }