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"
53 #include "mapper-types.h"
54 #include "ui-common.h"
58 #include "map-download.h"
61 static guint _num_downloads=0;
62 static guint _curr_download=0;
64 static gchar *map_construct_url(guint tilex, guint tiley, guint zoom);
67 get_next_pui(gpointer key, gpointer value, ProgressUpdateInfo ** data)
74 download_comparefunc(const ProgressUpdateInfo * a, const ProgressUpdateInfo * b, gpointer user_data)
76 gint diff = (a->priority - b->priority);
79 diff = (a->tilex - b->tilex);
82 diff = (a->tiley - b->tiley);
85 diff = (a->zoom - b->zoom);
88 diff = (a->repo - b->repo);
91 /* Otherwise, deletes are "greatest" (least priority). */
93 return (b->retries ? -1 : 0);
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);
101 * Free a ProgressUpdateInfo data structure that was allocated during the
102 * auto-map-download process.
105 progress_update_info_free(ProgressUpdateInfo * pui)
107 g_free(pui->src_str);
108 g_free(pui->dest_str);
109 g_slice_free(ProgressUpdateInfo, pui);
113 map_download_timeout()
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. */
120 if (_curl_multi && CURLM_CALL_MULTI_PERFORM == curl_multi_perform(_curl_multi, &num_transfers))
121 return TRUE; /* Give UI a chance first. */
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();
135 cancel_autoroute(TRUE); /* We're done. Clean up. */
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);
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);
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);
155 /* This is a download. */
157 g_tree_steal(_pui_tree, pui);
158 g_tree_insert(_downloading_tree, pui, pui);
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);
166 /* Failed to generate URL. */
167 g_idle_add_full(G_PRIORITY_HIGH_IDLE,(GSourceFunc)map_download_idle_refresh, pui, NULL);
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);
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");
193 curl_easy = g_queue_pop_tail(_curl_easy_queue);
195 /* Need a new curl_easy. */
196 MACRO_CURL_EASY_INIT(curl_easy);
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);
202 /* Initialize CURL. */
203 _curl_multi = curl_multi_init();
204 /*curl_multi_setopt(_curl_multi, CURLMOPT_PIPELINING, 1); */
206 curl_multi_add_handle(_curl_multi, curl_easy);
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"),
214 MACRO_BANNER_SHOW_INFO(_window, buffer);
215 g_idle_add_full(G_PRIORITY_HIGH_IDLE, (GSourceFunc)map_download_idle_refresh, pui, NULL);
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);
224 g_snprintf(buffer, sizeof(buffer), "%s/%u/%u/%u.jpg",
225 pui->repo->cache_dir, pui->zoom,
226 pui->tilex, pui->tiley);
228 g_idle_add_full(G_PRIORITY_HIGH_IDLE,(GSourceFunc)map_download_idle_refresh, pui, NULL);
233 if (!(num_transfers || g_tree_nnodes(_pui_tree))) {
234 /* Destroy curl after 50 counts (5 seconds). */
235 if (--destroy_counter) {
238 while ((curr = g_queue_pop_tail(_curl_easy_queue)))
239 curl_easy_cleanup(curr);
241 curl_multi_cleanup(_curl_multi);
248 destroy_counter = 50;
254 * Given a wms uri pattern, compute the coordinate transformation and
256 * 'proj' is used for the conversion
259 map_convert_wms_to_wms(gint tilex, gint tiley, gint zoomlevel, gchar * uri)
262 gchar cmd[BUFFER_SIZE], srs[BUFFER_SIZE];
265 gdouble lon1, lat1, lon2, lat2;
267 gchar *widthstr = strcasestr(uri, "WIDTH=");
268 gchar *heightstr = strcasestr(uri, "HEIGHT=");
269 gchar *srsstr = strcasestr(uri, "SRS=EPSG");
270 gchar *srsstre = strchr(srsstr, '&');
272 /* missing: test if found */
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 */
279 gint dwidth = widthstr ? atoi(widthstr + 6) - TILE_SIZE_PIXELS : 0;
280 gint dheight = heightstr ? atoi(heightstr + 7) - TILE_SIZE_PIXELS : 0;
282 unit2latlon(tile2zunit(tilex, zoomlevel) - pixel2zunit(dwidth / 2, zoomlevel),
283 tile2zunit(tiley + 1, zoomlevel) + pixel2zunit((dheight + 1) / 2, zoomlevel), lat1, lon1);
285 unit2latlon(tile2zunit(tilex + 1, zoomlevel) + pixel2zunit((dwidth + 1) / 2, zoomlevel),
286 tile2zunit(tiley, zoomlevel) - pixel2zunit(dheight / 2, zoomlevel), lat2, lon2);
288 setlocale(LC_NUMERIC, "C");
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);
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");
306 ret = g_strdup_printf(uri, lon1, lat1, lon2, lat2);
309 setlocale(LC_NUMERIC, "");
316 * Given the xyz coordinates of our map coordinate system, write the qrst
317 * quadtree coordinates to buffer.
320 map_convert_coords_to_quadtree_string(gint x, gint y, gint zoomlevel,
321 gchar * buffer, const gchar initial,
322 const gchar * const quadrant)
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];
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
345 map_construct_url(guint tilex, guint tiley, guint zoom)
347 switch (_curr_repo->type) {
349 return g_strdup_printf(_curr_repo->url, tilex, tiley, zoom);
351 case REPOTYPE_XYZ_INV:
352 return g_strdup_printf(_curr_repo->url, 17 - zoom, tilex, tiley);
354 case REPOTYPE_QUAD_QRST:
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);
361 case REPOTYPE_QUAD_ZERO:
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);
370 return map_convert_wms_to_wms(tilex, tiley, zoom, _curr_repo->url);
380 map_download_idle_refresh(ProgressUpdateInfo * pui)
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);
395 gtk_widget_queue_draw_area
397 ((tilex - _base_tilex) << TILE_SIZE_P2) - _offsetx,
398 ((tiley - _base_tiley) << TILE_SIZE_P2) - _offsety,
399 TILE_SIZE_PIXELS, TILE_SIZE_PIXELS);
405 /* Else the download failed. Update retries and maybe try again. */
407 if (pui->retries > 0)
409 else if (pui->retries < 0)
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. */
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."));
426 /* removal automatically calls progress_update_info_free(). */
427 g_tree_remove(_downloading_tree, pui);
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, "");
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);
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.
449 map_initiate_download(guint tilex, guint tiley, guint zoom, gint retries)
451 ProgressUpdateInfo *pui;
455 pui = g_slice_new(ProgressUpdateInfo);
459 pui->priority = (abs((gint) tilex - unit2tile(_center.unitx)) + abs((gint) tiley - unit2tile(_center.unity)));
461 pui->priority = -pui->priority; /* "Negative" makes them lowest pri. */
462 pui->retries = retries;
463 pui->repo = _curr_repo;
465 if (g_tree_lookup(_pui_tree, pui) || g_tree_lookup(_downloading_tree, pui)) {
466 /* Already downloading. */
467 g_slice_free(ProgressUpdateInfo, pui);
471 pui->dest_str = NULL;
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);
478 if (!_num_downloads++)
479 gtk_progress_bar_set_text(_progress_item, _("Downloading maps..."));
483 map_download_init(void)
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);
492 map_download_deinit(void)
498 gint num_transfers, num_msgs;
500 /* First, remove all downloads from _pui_tree. */
501 g_tree_destroy(_pui_tree);
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... */
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);
516 curl_multi_remove_handle(_curl_multi, msg->easy_handle);
520 while ((curr = g_queue_pop_tail(_curl_easy_queue)))
521 curl_easy_cleanup(curr);
523 curl_multi_cleanup(_curl_multi);
526 g_queue_free(_curl_easy_queue);
527 g_tree_destroy(_downloading_tree);
528 g_hash_table_destroy(_pui_by_easy);
532 g_source_remove(_curl_sid);