2 * This file is part of mapper
4 * Copyright (C) 2007 Kaj-Michael Lang
5 * Copyright (C) 2006-2007 John Costigan.
7 * POI and GPS-Info code originally written by Cezary Jackiewicz.
9 * Default map data provided by http://www.openstreetmap.org/
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.
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.
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.
37 #include <glib/gstdio.h>
39 #include <curl/multi.h>
43 #include "hildon-mapper.h"
52 #include "mapper-types.h"
53 #include "ui-common.h"
57 #include "map-download.h"
62 static guint _num_downloads=0;
63 static guint _curr_download=0;
65 static GQueue *curl_easy_queue=NULL;
66 static GTree *pui_tree=NULL;
67 static GTree *downloading_tree=NULL;
68 static GHashTable *pui_by_easy=NULL;
70 static gchar *map_construct_url(guint tilex, guint tiley, guint zoom);
73 get_next_pui(gpointer key, gpointer value, ProgressUpdateInfo ** data)
80 download_comparefunc(const ProgressUpdateInfo * a, const ProgressUpdateInfo * b, gpointer user_data)
82 gint diff = (a->priority - b->priority);
85 diff = (a->tilex - b->tilex);
88 diff = (a->tiley - b->tiley);
91 diff = (a->zoom - b->zoom);
94 diff = (a->repo - b->repo);
97 /* Otherwise, deletes are "greatest" (least priority). */
99 return (b->retries ? -1 : 0);
100 else if (!b->retries)
101 return (a->retries ? 1 : 0);
102 /* Do updates after non-updates (because they'll both be done anyway). */
103 return (a->retries - b->retries);
107 * Free a ProgressUpdateInfo data structure that was allocated during the
108 * auto-map-download process.
111 progress_update_info_free(ProgressUpdateInfo * pui)
113 g_free(pui->src_str);
114 g_free(pui->dest_str);
115 g_slice_free(ProgressUpdateInfo, pui);
119 map_download_timeout()
121 static guint destroy_counter = 50;
122 gint num_transfers = 0, num_msgs = 0;
123 gint deletes_left = 50; /* only do 50 deletes at a time. */
126 if (_curl_multi && CURLM_CALL_MULTI_PERFORM == curl_multi_perform(_curl_multi, &num_transfers))
127 return TRUE; /* Give UI a chance first. */
129 while (_curl_multi && (msg = curl_multi_info_read(_curl_multi, &num_msgs))) {
130 if (msg->msg == CURLMSG_DONE) {
131 if (msg->easy_handle == _autoroute_data.curl_easy) {
132 /* This is the autoroute download. */
133 /* Now, parse the autoroute and update the display. */
134 if (_autoroute_data.enabled && gpx_parse(&_route, _autoroute_data.rdl_data.bytes, _autoroute_data.rdl_data.bytes_read, 0)) {
135 /* Find the nearest route point, if we're connected. */
136 path_find_nearest_point(_route);
138 route_cancel_autoroute(_route, TRUE); /* We're done. Clean up. */
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);
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);
152 /* Up to 1 transfer per tile. */
153 while (num_transfers < (4*4) && g_tree_nnodes(pui_tree)) {
154 ProgressUpdateInfo *pui;
155 g_tree_foreach(pui_tree, (GTraverseFunc)get_next_pui, &pui);
158 /* This is a download. */
160 g_tree_steal(pui_tree, pui);
161 g_tree_insert(downloading_tree, pui, pui);
163 pui->src_str=map_construct_url(pui->tilex, pui->tiley, pui->zoom);
166 /* Failed to generate URL. */
167 g_debug("Failed to generate tile download URL");
168 g_idle_add_full(G_PRIORITY_HIGH_IDLE,(GSourceFunc)map_download_idle_refresh, pui, NULL);
172 pui->dest_str=g_strdup_printf("%s/%u/%u/%u.jpg", pui->repo->cache_dir, pui->zoom, pui->tilex, pui->tiley);
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);
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", pui->repo->cache_dir, pui->zoom, pui->tilex);
188 g_mkdir_with_parents(buffer, 0775);
189 f=g_fopen(pui->dest_str, "w");
195 curl_easy = g_queue_pop_tail(curl_easy_queue);
197 /* Need a new curl_easy. */
198 MACRO_CURL_EASY_INIT(curl_easy);
200 curl_easy_setopt(curl_easy, CURLOPT_URL, pui->src_str);
201 curl_easy_setopt(curl_easy, CURLOPT_WRITEDATA, f);
202 g_hash_table_insert(pui_by_easy, curl_easy, pui);
203 curl_multi_add_handle(_curl_multi, curl_easy);
206 /* Unable to open tile file for writing. */
207 gchar buffer[BUFFER_SIZE];
208 g_snprintf(buffer, sizeof(buffer), "%s:\n%s", _("Failed to open file for writing"), pui->dest_str);
209 MACRO_BANNER_SHOW_INFO(_window, buffer);
210 g_idle_add_full(G_PRIORITY_HIGH_IDLE, (GSourceFunc)map_download_idle_refresh, pui, NULL);
213 } else if (--deletes_left) {
214 /* This is a delete. */
215 gchar buffer[BUFFER_SIZE];
216 g_tree_steal(pui_tree, pui);
217 g_tree_insert(downloading_tree, pui, pui);
219 g_snprintf(buffer, sizeof(buffer), "%s/%u/%u/%u.jpg", pui->repo->cache_dir, pui->zoom, pui->tilex, pui->tiley);
221 g_idle_add_full(G_PRIORITY_HIGH_IDLE,(GSourceFunc)map_download_idle_refresh, pui, NULL);
226 if (!(num_transfers || g_tree_nnodes(pui_tree))) {
227 /* Destroy curl after 50 counts (5 seconds). */
228 if (--destroy_counter) {
231 while ((curr = g_queue_pop_tail(curl_easy_queue)))
232 curl_easy_cleanup(curr);
238 destroy_counter = 50;
243 #ifdef MAP_DOWNLOAD_WMS
245 * Given a wms uri pattern, compute the coordinate transformation and
247 * 'proj' is used for the conversion
250 #define WMS_TILE_SIZE_PIXELS (256)
253 map_convert_wms_to_wms(gint tilex, gint tiley, gint zoomlevel, gchar * uri)
256 gchar cmd[BUFFER_SIZE], srs[BUFFER_SIZE];
259 gdouble lon1, lat1, lon2, lat2;
261 gchar *widthstr = strcasestr(uri, "WIDTH=");
262 gchar *heightstr = strcasestr(uri, "HEIGHT=");
263 gchar *srsstr = strcasestr(uri, "SRS=EPSG");
264 gchar *srsstre = strchr(srsstr, '&');
266 /* missing: test if found */
268 strncpy(srs + 4, srsstr + 8, 256);
269 /* missing: test srsstre-srsstr < 526 */
270 srs[srsstre - srsstr - 4] = 0;
271 /* convert to lower, as WMC is EPSG and cs2cs is epsg */
273 gint dwidth = widthstr ? atoi(widthstr + 6) - WMS_TILE_SIZE_PIXELS : 0;
274 gint dheight = heightstr ? atoi(heightstr + 7) - WMS_TILE_SIZE_PIXELS : 0;
276 unit2latlon(tile2zunit(tilex, zoomlevel) - pixel2zunit(dwidth / 2, zoomlevel),
277 tile2zunit(tiley + 1, zoomlevel) + pixel2zunit((dheight + 1) / 2, zoomlevel), &lat1, &lon1);
279 unit2latlon(tile2zunit(tilex + 1, zoomlevel) + pixel2zunit((dwidth + 1) / 2, zoomlevel),
280 tile2zunit(tiley, zoomlevel) - pixel2zunit(dheight / 2, zoomlevel), &lat2, &lon2);
282 setlocale(LC_NUMERIC, "C");
284 g_snprintf(cmd, sizeof(cmd),
285 "(echo \"%.6f %.6f\"; echo \"%.6f %.6f\") | "
286 "/usr/bin/cs2cs +proj=longlat +datum=WGS84 +to +init=%s -f %%.6f "
287 " > /tmp/tmpcs2cs ", lon1, lat1, lon2, lat2, srs);
288 vprintf("Running command: %s\n", cmd);
289 system_retcode = system(cmd);
292 g_printerr("cs2cs returned error code %d\n", WEXITSTATUS(system_retcode));
293 else if (!(in = g_fopen("/tmp/tmpcs2cs", "r")))
294 g_printerr("Cannot open results of conversion\n");
295 else if (5 != fscanf(in, "%lf %lf %s %lf %lf", &lon1, &lat1, cmd, &lon2, &lat2)) {
296 g_printerr("Wrong conversion\n");
300 ret = g_strdup_printf(uri, lon1, lat1, lon2, lat2);
303 setlocale(LC_NUMERIC, "");
310 * Given the xyz coordinates of our map coordinate system, write the qrst
311 * quadtree coordinates to buffer.
314 map_convert_coords_to_quadtree_string(gint x, gint y, gint zoomlevel,
315 gchar * buffer, const gchar initial,
316 const gchar * const quadrant)
324 for (n = 16 - zoomlevel; n >= 0; n--) {
325 gint xbit = (x >> n) & 1;
326 gint ybit = (y >> n) & 1;
327 *ptr++ = quadrant[xbit + 2 * ybit];
333 * Construct the URL that we should fetch, based on the current URI format.
334 * This method works differently depending on if a "%s" string is present in
335 * the URI format, since that would indicate a quadtree-based map coordinate
339 map_construct_url(guint tilex, guint tiley, guint zoom)
341 switch (_curr_repo->type) {
343 return g_strdup_printf(_curr_repo->url, tilex, tiley, zoom);
344 case REPOTYPE_XYZ_INV:
345 return g_strdup_printf(_curr_repo->url, 17 - zoom, tilex, tiley);
346 case REPOTYPE_QUAD_QRST: {
348 map_convert_coords_to_quadtree_string(tilex, tiley, zoom, location, 't', "qrts");
349 return g_strdup_printf(_curr_repo->url, location);
351 case REPOTYPE_QUAD_ZERO: {
352 /* This is a zero-based quadtree URI. */
354 map_convert_coords_to_quadtree_string(tilex, tiley, zoom, location, '\0', "0123");
355 return g_strdup_printf(_curr_repo->url, location);
357 #ifdef MAP_DOWNLOAD_WMD
359 return map_convert_wms_to_wms(tilex, tiley, zoom, _curr_repo->url);
368 map_download_progress_clear(void)
370 g_assert(_progress_item);
371 gtk_progress_bar_set_fraction(_progress_item, 0.0);
372 gtk_progress_bar_set_text(_progress_item, "");
376 map_download_progress_set(gint currd, gint numd)
380 g_assert(_progress_item);
381 g_snprintf(buffer, sizeof(buffer), _("Downloading maps (%d/%d)"), currd, numd);
382 gtk_progress_bar_set_text(_progress_item, buffer);
383 gtk_progress_bar_set_fraction(_progress_item, currd/(double)numd);
387 map_download_idle_refresh(ProgressUpdateInfo * pui)
390 /* Test if download succeeded (only if retries != 0). */
391 if (!pui->retries || g_file_test(pui->dest_str, G_FILE_TEST_EXISTS)) {
392 gint zoom_diff = pui->zoom - gtk_map_get_zoom(_map);
395 /* Only refresh at same or "lower" (more detailed) zoom level. */
396 if (zoom_diff >= 0) {
397 guint tilex, tiley, tilex_end, tiley_end;
399 /* If zoom has changed since we first put in the request for
400 * this tile, then we may have to update more than one tile. */
401 for (tilex = pui->tilex << zoom_diff, tilex_end = tilex + (1 << zoom_diff); tilex < tilex_end; tilex++) {
402 for (tiley = pui->tiley << zoom_diff, tiley_end = tiley + (1 << zoom_diff); tiley < tiley_end; tiley++) {
404 if (map_render_tile(tilex, tiley, ((tilex - _base_tilex) << TILE_SIZE_P2), ((tiley - _base_tiley) << TILE_SIZE_P2), TRUE)==TRUE) {
406 gtk_widget_queue_draw_area(_map_widget,
407 ((tilex - _base_tilex) << TILE_SIZE_P2) - _offsetx,
408 ((tiley - _base_tiley) << TILE_SIZE_P2) - _offsety,
409 TILE_SIZE_PIXELS, TILE_SIZE_PIXELS);
413 g_debug("*** MDIR LOOP: %u", tmp);
416 g_debug("XXX: Add cb or signal or something to inform map widget about fresh tile");
419 /* Else the download failed. Update retries and maybe try again. */
421 if (pui->retries > 0)
423 else if (pui->retries < 0)
427 /* removal automatically calls progress_update_info_free(). */
428 g_tree_steal(downloading_tree, pui);
429 g_tree_insert(pui_tree, pui, pui);
430 if (iap_is_connected() && !_curl_sid)
431 _curl_sid = g_timeout_add(100,(GSourceFunc)map_download_timeout, NULL);
432 /* Don't do anything else. */
435 /* No more retries left - something must be wrong. */
436 MACRO_BANNER_SHOW_INFO(_window, _("Error in download. Check internet connection and/or Map Repository URL Format."));
440 /* removal automatically calls progress_update_info_free(). */
441 g_tree_remove(downloading_tree, pui);
443 if (++_curr_download == _num_downloads) {
444 _num_downloads = _curr_download = 0;
445 map_download_progress_clear();
447 map_download_progress_set(_curr_download, _num_downloads);
453 * Initiate a download of the given xyz coordinates using the given buffer
454 * as the URL. If the map already exists on disk, or if we are already
455 * downloading the map, then this method does nothing.
458 map_initiate_download(guint tilex, guint tiley, guint zoom, gint retries)
460 ProgressUpdateInfo *pui;
464 pui = g_slice_new(ProgressUpdateInfo);
470 pui->priority = -pui->priority; /* "Negative" makes them lowest pri. */
471 pui->retries = retries;
472 pui->repo = _curr_repo;
474 if (g_tree_lookup(pui_tree, pui) || g_tree_lookup(downloading_tree, pui)) {
475 /* Already downloading. */
476 g_slice_free(ProgressUpdateInfo, pui);
480 pui->dest_str = NULL;
483 g_tree_insert(pui_tree, pui, pui);
484 if (iap_is_connected() && !_curl_sid)
485 _curl_sid = g_timeout_add(100, (GSourceFunc) map_download_timeout, NULL);
487 if (!_num_downloads++)
488 gtk_progress_bar_set_text(_progress_item, _("Downloading maps..."));
492 map_download_init(void)
494 curl_easy_queue = g_queue_new();
495 pui_tree = g_tree_new_full((GCompareDataFunc)download_comparefunc, NULL, (GDestroyNotify) progress_update_info_free, NULL);
496 downloading_tree = g_tree_new_full((GCompareDataFunc)download_comparefunc, NULL, (GDestroyNotify) progress_update_info_free, NULL);
497 pui_by_easy = g_hash_table_new(g_direct_hash, g_direct_equal);
498 _curl_multi = curl_multi_init();
499 /* curl_multi_setopt(_curl_multi, CURLMOPT_PIPELINING, 1); */
503 map_download_stop(void)
510 /* Clear the tree and create it again */
512 g_tree_destroy(pui_tree);
513 pui_tree = g_tree_new_full((GCompareDataFunc)download_comparefunc, NULL, (GDestroyNotify) progress_update_info_free, NULL);
516 /* Close all finished files. */
517 while ((msg = curl_multi_info_read(_curl_multi, &num_msgs))) {
518 if (msg->msg == CURLMSG_DONE) {
519 /* This is a map download. */
520 ProgressUpdateInfo *pui = g_hash_table_lookup(pui_by_easy, msg->easy_handle);
521 g_queue_push_head(curl_easy_queue, msg->easy_handle);
522 g_hash_table_remove(pui_by_easy, msg->easy_handle);
525 curl_multi_remove_handle(_curl_multi, msg->easy_handle);
529 g_debug("Stopping downloads");
530 while ((curr = g_queue_pop_tail(curl_easy_queue)))
531 curl_easy_cleanup(curr);
534 g_debug("No downloads to stop");
539 * Clean up CURL and structures
542 map_download_deinit(void)
548 /* Finish up all downloads. */
549 while (CURLM_CALL_MULTI_PERFORM == curl_multi_perform(_curl_multi, &num_transfers) || num_transfers) {
550 g_debug("NT: %d", num_transfers);
553 /* Stop all transfers and cleanup */
557 g_tree_destroy(pui_tree);
558 if (downloading_tree)
559 g_tree_destroy(downloading_tree);
561 g_hash_table_destroy(pui_by_easy);
563 g_queue_free(curl_easy_queue);
564 curl_multi_cleanup(_curl_multi);
569 g_source_remove(_curl_sid);