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.
39 #include <glib/gstdio.h>
41 #include <curl/multi.h>
45 #include "hildon-mapper.h"
56 #include "mapper-types.h"
57 #include "ui-common.h"
61 #include "map-download.h"
64 static guint _num_downloads=0;
65 static guint _curr_download=0;
67 static gchar *map_construct_url(guint tilex, guint tiley, guint zoom);
70 get_next_pui(gpointer key, gpointer value, ProgressUpdateInfo ** data)
77 download_comparefunc(const ProgressUpdateInfo * a, const ProgressUpdateInfo * b, gpointer user_data)
79 gint diff = (a->priority - b->priority);
82 diff = (a->tilex - b->tilex);
85 diff = (a->tiley - b->tiley);
88 diff = (a->zoom - b->zoom);
91 diff = (a->repo - b->repo);
94 /* Otherwise, deletes are "greatest" (least priority). */
96 return (b->retries ? -1 : 0);
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);
104 * Free a ProgressUpdateInfo data structure that was allocated during the
105 * auto-map-download process.
108 progress_update_info_free(ProgressUpdateInfo * pui)
110 g_free(pui->src_str);
111 g_free(pui->dest_str);
112 g_slice_free(ProgressUpdateInfo, pui);
116 map_download_timeout()
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. */
123 if (_curl_multi && CURLM_CALL_MULTI_PERFORM == curl_multi_perform(_curl_multi, &num_transfers))
124 return TRUE; /* Give UI a chance first. */
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();
138 cancel_autoroute(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 < (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);
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);
164 pui->dest_str = g_strdup_printf("%s/%u/%u/%u.jpg",
165 pui->repo->cache_dir, pui->zoom,
166 pui->tilex, pui->tiley);
169 /* Failed to generate URL. */
170 g_idle_add_full(G_PRIORITY_HIGH_IDLE,(GSourceFunc)map_download_idle_refresh, pui, NULL);
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",
188 pui->repo->cache_dir, pui->zoom, pui->tilex);
189 g_mkdir_with_parents(buffer, 0775);
190 f = g_fopen(pui->dest_str, "w");
196 curl_easy = g_queue_pop_tail(_curl_easy_queue);
198 /* Need a new curl_easy. */
199 MACRO_CURL_EASY_INIT(curl_easy);
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);
205 /* Initialize CURL. */
206 _curl_multi = curl_multi_init();
207 /*curl_multi_setopt(_curl_multi, CURLMOPT_PIPELINING, 1); */
209 curl_multi_add_handle(_curl_multi, curl_easy);
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"),
217 MACRO_BANNER_SHOW_INFO(_window, buffer);
218 g_idle_add_full(G_PRIORITY_HIGH_IDLE, (GSourceFunc)map_download_idle_refresh, pui, NULL);
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);
227 g_snprintf(buffer, sizeof(buffer), "%s/%u/%u/%u.jpg",
228 pui->repo->cache_dir, pui->zoom,
229 pui->tilex, pui->tiley);
231 g_idle_add_full(G_PRIORITY_HIGH_IDLE,(GSourceFunc)map_download_idle_refresh, pui, NULL);
236 if (!(num_transfers || g_tree_nnodes(_pui_tree))) {
237 /* Destroy curl after 50 counts (5 seconds). */
238 if (--destroy_counter) {
241 while ((curr = g_queue_pop_tail(_curl_easy_queue)))
242 curl_easy_cleanup(curr);
244 curl_multi_cleanup(_curl_multi);
251 destroy_counter = 50;
257 * Given a wms uri pattern, compute the coordinate transformation and
259 * 'proj' is used for the conversion
262 map_convert_wms_to_wms(gint tilex, gint tiley, gint zoomlevel, gchar * uri)
265 gchar cmd[BUFFER_SIZE], srs[BUFFER_SIZE];
268 gdouble lon1, lat1, lon2, lat2;
270 gchar *widthstr = strcasestr(uri, "WIDTH=");
271 gchar *heightstr = strcasestr(uri, "HEIGHT=");
272 gchar *srsstr = strcasestr(uri, "SRS=EPSG");
273 gchar *srsstre = strchr(srsstr, '&');
275 /* missing: test if found */
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 */
282 gint dwidth = widthstr ? atoi(widthstr + 6) - TILE_SIZE_PIXELS : 0;
283 gint dheight = heightstr ? atoi(heightstr + 7) - TILE_SIZE_PIXELS : 0;
285 unit2latlon(tile2zunit(tilex, zoomlevel) - pixel2zunit(dwidth / 2, zoomlevel),
286 tile2zunit(tiley + 1, zoomlevel) + pixel2zunit((dheight + 1) / 2, zoomlevel), lat1, lon1);
288 unit2latlon(tile2zunit(tilex + 1, zoomlevel) + pixel2zunit((dwidth + 1) / 2, zoomlevel),
289 tile2zunit(tiley, zoomlevel) - pixel2zunit(dheight / 2, zoomlevel), lat2, lon2);
291 setlocale(LC_NUMERIC, "C");
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);
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");
309 ret = g_strdup_printf(uri, lon1, lat1, lon2, lat2);
312 setlocale(LC_NUMERIC, "");
319 * Given the xyz coordinates of our map coordinate system, write the qrst
320 * quadtree coordinates to buffer.
323 map_convert_coords_to_quadtree_string(gint x, gint y, gint zoomlevel,
324 gchar * buffer, const gchar initial,
325 const gchar * const quadrant)
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];
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
348 map_construct_url(guint tilex, guint tiley, guint zoom)
350 switch (_curr_repo->type) {
352 return g_strdup_printf(_curr_repo->url, tilex, tiley, zoom);
354 case REPOTYPE_XYZ_INV:
355 return g_strdup_printf(_curr_repo->url, 17 - zoom, tilex, tiley);
357 case REPOTYPE_QUAD_QRST:
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);
364 case REPOTYPE_QUAD_ZERO:
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);
373 return map_convert_wms_to_wms(tilex, tiley, zoom, _curr_repo->url);
383 map_download_idle_refresh(ProgressUpdateInfo * pui)
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);
398 gtk_widget_queue_draw_area
400 ((tilex - _base_tilex) << TILE_SIZE_P2) - _offsetx,
401 ((tiley - _base_tiley) << TILE_SIZE_P2) - _offsety,
402 TILE_SIZE_PIXELS, TILE_SIZE_PIXELS);
408 /* Else the download failed. Update retries and maybe try again. */
410 if (pui->retries > 0)
412 else if (pui->retries < 0)
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. */
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."));
429 /* removal automatically calls progress_update_info_free(). */
430 g_tree_remove(_downloading_tree, pui);
432 if (++_curr_download == _num_downloads) {
434 gtk_widget_destroy(_download_banner);
435 _download_banner = NULL;
437 _num_downloads = _curr_download = 0;
438 hildon_banner_set_fraction(HILDON_BANNER(_download_banner), 0.0);
439 gtk_progress_bar_set_text(_progress_item, "");
444 g_snprintf(buffer, sizeof(buffer), _("Downloading maps (%d/%d)"), _curr_download, _num_downloads);
446 hildon_banner_set_text(HILDON_BANNER(_download_banner), buffer);
448 gtk_progress_bar_set_text(_progress_item, buffer);
450 hildon_banner_set_fraction(HILDON_BANNER(_download_banner), _curr_download / (double)_num_downloads);
456 * Initiate a download of the given xyz coordinates using the given buffer
457 * as the URL. If the map already exists on disk, or if we are already
458 * downloading the map, then this method does nothing.
461 map_initiate_download(guint tilex, guint tiley, guint zoom, gint retries)
463 ProgressUpdateInfo *pui;
467 pui = g_slice_new(ProgressUpdateInfo);
471 pui->priority = (abs((gint) tilex - unit2tile(_center.unitx)) + abs((gint) tiley - unit2tile(_center.unity)));
473 pui->priority = -pui->priority; /* "Negative" makes them lowest pri. */
474 pui->retries = retries;
475 pui->repo = _curr_repo;
477 if (g_tree_lookup(_pui_tree, pui) || g_tree_lookup(_downloading_tree, pui)) {
478 /* Already downloading. */
479 g_slice_free(ProgressUpdateInfo, pui);
483 pui->dest_str = NULL;
486 g_tree_insert(_pui_tree, pui, pui);
487 if (iap_is_connected() && !_curl_sid)
488 _curl_sid = g_timeout_add(100, (GSourceFunc) map_download_timeout, NULL);
490 if (!_num_downloads++ && !_download_banner) {
491 _download_banner = hildon_banner_show_progress(_window, NULL, _("Downloading maps..."));
496 map_download_init(void)
498 _curl_easy_queue = g_queue_new();
499 _pui_tree = g_tree_new_full((GCompareDataFunc) download_comparefunc, NULL, (GDestroyNotify) progress_update_info_free, NULL);
500 _downloading_tree = g_tree_new_full((GCompareDataFunc) download_comparefunc, NULL, (GDestroyNotify) progress_update_info_free, NULL);
501 _pui_by_easy = g_hash_table_new(g_direct_hash, g_direct_equal);
505 map_download_deinit(void)
511 gint num_transfers, num_msgs;
513 /* First, remove all downloads from _pui_tree. */
514 g_tree_destroy(_pui_tree);
516 /* Finish up all downloads. */
517 while (CURLM_CALL_MULTI_PERFORM == curl_multi_perform(_curl_multi, &num_transfers) || num_transfers) {
518 /* XXX: should inform the user why it's taking so damn long... */
521 /* Close all finished files. */
522 while ((msg = curl_multi_info_read(_curl_multi, &num_msgs))) {
523 if (msg->msg == CURLMSG_DONE) {
524 /* This is a map download. */
525 ProgressUpdateInfo *pui = g_hash_table_lookup(_pui_by_easy, msg->easy_handle);
526 g_queue_push_head(_curl_easy_queue, msg->easy_handle);
527 g_hash_table_remove(_pui_by_easy, msg->easy_handle);
529 curl_multi_remove_handle(_curl_multi, msg->easy_handle);
533 while ((curr = g_queue_pop_tail(_curl_easy_queue)))
534 curl_easy_cleanup(curr);
536 curl_multi_cleanup(_curl_multi);
539 g_queue_free(_curl_easy_queue);
540 g_tree_destroy(_downloading_tree);
541 g_hash_table_destroy(_pui_by_easy);