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