]> git.street.me.uk Git - andy/viking.git/blob - src/datasource_osm_my_traces.c
When adding layers insert 'Base' layers (i.e Maps/GeoRef/DEM) below the selected...
[andy/viking.git] / src / datasource_osm_my_traces.c
1 /* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
2 /*
3  * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
4  *
5  * Copyright (C) 2012, Rob Norris <rw_norris@hotmail.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  */
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif
25
26 #include <glib/gprintf.h>
27 #include <glib/gi18n.h>
28 #include <glib/gstdio.h>
29
30 #include <expat.h>
31
32 #include "viking.h"
33 #include "gpx.h"
34 #include "acquire.h"
35 #include "osm-traces.h"
36 #include "datasource_gps.h"
37 #include "bbox.h"
38
39 /**
40  * See http://wiki.openstreetmap.org/wiki/API_v0.6#GPS_Traces
41  */
42 #define DS_OSM_TRACES_GPX_URL_FMT "api.openstreetmap.org/api/0.6/gpx/%d/data"
43 #define DS_OSM_TRACES_GPX_FILES "api.openstreetmap.org/api/0.6/user/gpx_files"
44
45 typedef struct {
46         GtkWidget *user_entry;
47         GtkWidget *password_entry;
48         // NB actual user and password values are stored in oms-traces.c
49         VikViewport *vvp;
50 } datasource_osm_my_traces_t;
51
52 static gpointer datasource_osm_my_traces_init( );
53 static void datasource_osm_my_traces_add_setup_widgets ( GtkWidget *dialog, VikViewport *vvp, gpointer user_data );
54 static void datasource_osm_my_traces_get_cmd_string ( gpointer user_data, gchar **args, gchar **extra, DownloadMapOptions *options );
55 static gboolean datasource_osm_my_traces_process  ( VikTrwLayer *vtl, const gchar *cmd, const gchar *extra, BabelStatusFunc status_cb, acq_dialog_widgets_t *adw, DownloadMapOptions *options_unused );
56 static void datasource_osm_my_traces_cleanup ( gpointer data );
57
58 VikDataSourceInterface vik_datasource_osm_my_traces_interface = {
59   N_("OSM My Traces"),
60   N_("OSM My Traces"),
61   VIK_DATASOURCE_MANUAL_LAYER_MANAGEMENT, // we'll do this ourselves
62   VIK_DATASOURCE_INPUTTYPE_NONE,
63   TRUE,
64   TRUE,
65   FALSE, // Don't use thread method
66   (VikDataSourceInitFunc)                   datasource_osm_my_traces_init,
67   (VikDataSourceCheckExistenceFunc)     NULL,
68   (VikDataSourceAddSetupWidgetsFunc)datasource_osm_my_traces_add_setup_widgets,
69   (VikDataSourceGetCmdStringFunc)       datasource_osm_my_traces_get_cmd_string,
70   (VikDataSourceProcessFunc)            datasource_osm_my_traces_process,
71   (VikDataSourceProgressFunc)           NULL,
72   (VikDataSourceAddProgressWidgetsFunc) NULL,
73   (VikDataSourceCleanupFunc)            datasource_osm_my_traces_cleanup,
74   (VikDataSourceOffFunc)            NULL,
75
76   NULL,
77   0,
78   NULL,
79   NULL,
80   0
81 };
82
83 static gpointer datasource_osm_my_traces_init ( )
84 {
85   datasource_osm_my_traces_t *data = g_malloc(sizeof(*data));
86   // Reuse GPS functions
87   // Haven't been able to get the thread method to work reliably (or get progress feedback)
88   // So thread version is disabled ATM
89   /*
90   if ( vik_datasource_osm_my_traces_interface.is_thread ) {
91           vik_datasource_osm_my_traces_interface.progress_func = datasource_gps_progress;
92           vik_datasource_osm_my_traces_interface.add_progress_widgets_func = datasource_gps_add_progress_widgets;
93   }
94   */
95   return data;
96 }
97
98 static void datasource_osm_my_traces_add_setup_widgets ( GtkWidget *dialog, VikViewport *vvp, gpointer user_data )
99 {
100         datasource_osm_my_traces_t *data = (datasource_osm_my_traces_t *)user_data;
101
102         GtkWidget *user_label;
103         GtkWidget *password_label;
104         user_label = gtk_label_new(_("Username:"));
105         data->user_entry = gtk_entry_new();
106
107         gtk_box_pack_start ( GTK_BOX(GTK_DIALOG(dialog)->vbox), user_label, FALSE, FALSE, 0 );
108         gtk_box_pack_start ( GTK_BOX(GTK_DIALOG(dialog)->vbox), data->user_entry, FALSE, FALSE, 0 );
109         gtk_widget_set_tooltip_markup ( GTK_WIDGET(data->user_entry), _("The email or username used to login to OSM") );
110
111         password_label = gtk_label_new ( _("Password:") );
112         data->password_entry = gtk_entry_new ();
113
114         gtk_box_pack_start ( GTK_BOX(GTK_DIALOG(dialog)->vbox), password_label, FALSE, FALSE, 0 );
115         gtk_box_pack_start ( GTK_BOX(GTK_DIALOG(dialog)->vbox), data->password_entry, FALSE, FALSE, 0 );
116         gtk_widget_set_tooltip_markup ( GTK_WIDGET(data->password_entry), _("The password used to login to OSM") );
117
118         osm_login_widgets (data->user_entry, data->password_entry);
119         gtk_widget_show_all ( dialog );
120
121         /* Keep reference to viewport */
122         data->vvp = vvp;
123 }
124
125 static void datasource_osm_my_traces_get_cmd_string ( gpointer user_data, gchar **args, gchar **extra, DownloadMapOptions *options )
126 {
127         datasource_osm_my_traces_t *data = (datasource_osm_my_traces_t*) user_data;
128
129     /* overwrite authentication info */
130         osm_set_login ( gtk_entry_get_text ( GTK_ENTRY(data->user_entry) ),
131                         gtk_entry_get_text ( GTK_ENTRY(data->password_entry) ) );
132
133         // If going to use the values passed back into the process function parameters then these need to be set.
134         // But ATM we aren't
135         *args = NULL;
136         *extra = NULL;
137         options = NULL;
138 }
139
140 typedef enum {
141         tt_unknown = 0,
142         tt_osm,
143         tt_gpx_file,
144         tt_gpx_file_desc,
145         tt_gpx_file_tag,
146 } xtag_type;
147
148 typedef struct {
149         xtag_type tag_type;              /* enum from above for this tag */
150         const char *tag_name;           /* xpath-ish tag name */
151 } xtag_mapping;
152
153 typedef struct {
154         guint id;
155         gchar *name;
156         gchar *vis;
157         gchar *desc;
158         struct LatLon ll;
159         gboolean in_current_view; // Is the track LatLon start within the current viewport
160                               // This is useful in deciding whether to download a track or not
161         // ATM Only used for display - may want to convert to a time_t for other usage
162         gchar *timestamp;
163         // user made up tags - not being used yet - would be nice to sort/select on these but display will get complicated
164         // GList *tag_list;
165 } gpx_meta_data_t;
166
167 static gpx_meta_data_t *new_gpx_meta_data_t()
168 {
169         gpx_meta_data_t *ret;
170
171         ret = (gpx_meta_data_t *)g_malloc(sizeof(gpx_meta_data_t));
172         ret->id = 0;
173         ret->name = NULL;
174         ret->vis  = NULL;
175         ret->desc = NULL;
176         ret->ll.lat = 0.0;
177         ret->ll.lon = 0.0;
178         ret->in_current_view = FALSE;
179         ret->timestamp = NULL;
180
181         return ret;
182 }
183
184 static void free_gpx_meta_data ( gpx_meta_data_t *data, gpointer userdata )
185 {
186         g_free(data->name);
187         g_free(data->vis);
188         g_free(data->desc);
189         g_free(data->timestamp);
190 }
191
192 static void free_gpx_meta_data_list (GList *list)
193 {
194         g_list_foreach (list, (GFunc)free_gpx_meta_data, NULL);
195         g_list_free (list);
196 }
197
198 static gpx_meta_data_t *copy_gpx_meta_data_t (gpx_meta_data_t *src)
199 {
200         gpx_meta_data_t *dest = new_gpx_meta_data_t();
201
202         dest->id = src->id;
203         dest->name = g_strdup(src->name);
204         dest->vis  = g_strdup(src->vis);
205         dest->desc = g_strdup(src->desc);
206         dest->ll.lat = src->ll.lat;
207         dest->ll.lon = src->ll.lon;
208         dest->in_current_view = src->in_current_view;
209         dest->timestamp = g_strdup(src->timestamp);
210
211         return dest;
212 }
213
214 typedef struct {
215         //GString *xpath;
216         GString *c_cdata;
217         xtag_type current_tag;
218         gpx_meta_data_t *current_gpx_meta_data;
219         GList *list_of_gpx_meta_data;
220 } xml_data;
221
222 // Same as the gpx.c function
223 static const char *get_attr ( const char **attr, const char *key )
224 {
225   while ( *attr ) {
226     if ( strcmp(*attr,key) == 0 )
227       return *(attr + 1);
228     attr += 2;
229   }
230   return NULL;
231 }
232
233 // ATM don't care about actual path as tags are all unique
234 static xtag_mapping xtag_path_map[] = {
235         { tt_osm,           "osm" },
236         { tt_gpx_file,      "gpx_file" },
237         { tt_gpx_file_desc, "description" },
238         { tt_gpx_file_tag,  "tag" },
239 };
240
241 static xtag_type get_tag ( const char *t )
242 {
243         xtag_mapping *tm;
244         for (tm = xtag_path_map; tm->tag_type != 0; tm++)
245                 if (0 == strcmp(tm->tag_name, t))
246                         return tm->tag_type;
247         return tt_unknown;
248 }
249
250 static void gpx_meta_data_start ( xml_data *xd, const char *el, const char **attr )
251 {
252         const gchar *tmp;
253         gchar buf[G_ASCII_DTOSTR_BUF_SIZE];
254         buf[0] = '\0';
255
256         // Don't need to build a path - we can use the tag directly
257         //g_string_append_c ( xd->xpath, '/' );
258         //g_string_append ( xd->xpath, el );
259         //xd->current_tag = get_tag ( xd->xpath->str );
260         xd->current_tag = get_tag ( el );
261         switch ( xd->current_tag ) {
262         case tt_gpx_file:
263                 if ( xd->current_gpx_meta_data )
264                         free_gpx_meta_data ( xd->current_gpx_meta_data, NULL );
265                 xd->current_gpx_meta_data = new_gpx_meta_data_t();
266
267                 if ( ( tmp = get_attr ( attr, "id" ) ) )
268                         xd->current_gpx_meta_data->id = atoi ( tmp );
269
270                 if ( ( tmp = get_attr ( attr, "name" ) ) )
271                         xd->current_gpx_meta_data->name = g_strdup ( tmp );
272
273                 if ( ( tmp = get_attr ( attr, "lat" ) ) ) {
274                         g_strlcpy ( buf, tmp, sizeof (buf) );
275                         xd->current_gpx_meta_data->ll.lat = g_ascii_strtod ( buf, NULL );
276                 }
277
278                 if ( ( tmp = get_attr ( attr, "lon" ) ) ) {
279                         g_strlcpy ( buf, tmp, sizeof (buf) );
280                         xd->current_gpx_meta_data->ll.lon = g_ascii_strtod ( buf, NULL );
281                 }
282
283                 if ( ( tmp = get_attr ( attr, "visibility" ) ) )
284                         xd->current_gpx_meta_data->vis = g_strdup ( tmp );
285
286                 if ( ( tmp = get_attr ( attr, "timestamp" ) ) )
287                         xd->current_gpx_meta_data->timestamp = g_strdup ( tmp );
288
289                 g_string_erase ( xd->c_cdata, 0, -1 ); // clear the cdata buffer
290                 break;
291         case tt_gpx_file_desc:
292         case tt_gpx_file_tag:
293                 g_string_erase ( xd->c_cdata, 0, -1 ); // clear the cdata buffer
294                 break;
295         default:
296                 g_string_erase ( xd->c_cdata, 0, -1 ); // clear the cdata buffer
297                 break;
298         }
299 }
300
301 static void gpx_meta_data_end ( xml_data *xd, const char *el )
302 {
303         //g_string_truncate ( xd->xpath, xd->xpath->len - strlen(el) - 1 );
304         //switch ( xd->current_tag ) {
305         switch ( get_tag ( el ) ) {
306         case tt_gpx_file: {
307                 // End of the individual file metadata, thus save what we have read in to the list
308                 // Copy it so we can reference it
309                 gpx_meta_data_t *current = copy_gpx_meta_data_t ( xd->current_gpx_meta_data );
310                 // Stick in the list
311                 xd->list_of_gpx_meta_data = g_list_prepend(xd->list_of_gpx_meta_data, current);
312                 g_string_erase ( xd->c_cdata, 0, -1 );
313                 break;
314         }
315         case tt_gpx_file_desc:
316                 // Store the description:
317                 if ( xd->current_gpx_meta_data ) {
318                         // NB Limit description size as it's displayed on a single line
319                         // Hopefully this will prevent the dialog getting too wide...
320                         xd->current_gpx_meta_data->desc = g_strndup ( xd->c_cdata->str, 63 );
321                 }
322                 g_string_erase ( xd->c_cdata, 0, -1 );
323                 break;
324         case tt_gpx_file_tag:
325                 // One day do something with this...
326                 g_string_erase ( xd->c_cdata, 0, -1 );
327                 break;
328         default:
329                 break;
330         }
331 }
332
333 static void gpx_meta_data_cdata ( xml_data *xd, const XML_Char *s, int len )
334 {
335         switch ( xd->current_tag ) {
336     case tt_gpx_file_desc:
337     case tt_gpx_file_tag:
338                 g_string_append_len ( xd->c_cdata, s, len );
339                 break;
340         default: break;  // ignore cdata from other things
341         }
342 }
343
344 static gboolean read_gpx_files_metadata_xml ( gchar *tmpname, xml_data *xd )
345 {
346         FILE *ff = g_fopen (tmpname, "r");
347         if ( !ff )
348                 return FALSE;
349
350         XML_Parser parser = XML_ParserCreate(NULL);
351         enum XML_Status status = XML_STATUS_ERROR;
352
353         XML_SetElementHandler(parser, (XML_StartElementHandler) gpx_meta_data_start, (XML_EndElementHandler) gpx_meta_data_end);
354         XML_SetUserData(parser, xd);
355         XML_SetCharacterDataHandler(parser, (XML_CharacterDataHandler) gpx_meta_data_cdata);
356
357         gchar buf[4096];
358
359         int done=0, len;
360         while (!done) {
361                 len = fread(buf, 1, sizeof(buf)-7, ff);
362                 done = feof(ff) || !len;
363                 status = XML_Parse(parser, buf, len, done);
364         }
365
366         XML_ParserFree (parser);
367
368         fclose  ( ff );
369
370         return status != XML_STATUS_ERROR;
371 }
372
373 static GList *select_from_list (GtkWindow *parent, GList *list, const gchar *title, const gchar *msg )
374 {
375         GtkTreeIter iter;
376         GtkCellRenderer *renderer;
377         GtkWidget *view;
378         gchar *latlon_string;
379         int column_runner;
380
381         GtkWidget *dialog = gtk_dialog_new_with_buttons (title,
382                                                                                                          parent,
383                                                                                                          GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
384                                                                                                          GTK_STOCK_CANCEL,
385                                                                                                          GTK_RESPONSE_REJECT,
386                                                                                                          GTK_STOCK_OK,
387                                                                                                          GTK_RESPONSE_ACCEPT,
388                                                                                                          NULL);
389         /* When something is selected then OK */
390         gtk_dialog_set_default_response ( GTK_DIALOG(dialog), GTK_RESPONSE_ACCEPT );
391         GtkWidget *response_w = NULL;
392 #if GTK_CHECK_VERSION (2, 20, 0)
393         /* Default to not apply - as initially nothing is selected! */
394         response_w = gtk_dialog_get_widget_for_response ( GTK_DIALOG(dialog), GTK_RESPONSE_REJECT );
395 #endif
396         GtkWidget *label = gtk_label_new ( msg );
397         GtkTreeStore *store = gtk_tree_store_new ( 6, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_BOOLEAN );
398         GList *list_runner = list;
399         while (list_runner) {
400                 gpx_meta_data_t *gpx_meta_data = (gpx_meta_data_t *)list_runner->data;
401                 // To keep display compact three digits of precision for lat/lon should be plenty
402                 latlon_string = g_strdup_printf("(%.3f,%.3f)", gpx_meta_data->ll.lat, gpx_meta_data->ll.lon);
403                 gtk_tree_store_append(store, &iter, NULL);
404                 gtk_tree_store_set ( store, &iter,
405                                      0, gpx_meta_data->name,
406                                      1, gpx_meta_data->desc,
407                                      2, gpx_meta_data->timestamp,
408                                      3, latlon_string,
409                                      4, gpx_meta_data->vis,
410                                      5, gpx_meta_data->in_current_view,
411                                      -1 );
412                 list_runner = g_list_next ( list_runner );
413                 g_free ( latlon_string );
414         }
415
416         view = gtk_tree_view_new();
417         renderer = gtk_cell_renderer_text_new();
418         column_runner = 0;
419         GtkTreeViewColumn *column;
420
421         column = gtk_tree_view_column_new_with_attributes ( _("Name"), renderer, "text", column_runner, NULL);
422         gtk_tree_view_column_set_sort_column_id (column, column_runner);
423         gtk_tree_view_append_column (GTK_TREE_VIEW (view), column);
424
425         column_runner++;
426         column = gtk_tree_view_column_new_with_attributes ( _("Description"), renderer, "text", column_runner, NULL);
427         gtk_tree_view_column_set_sort_column_id (column, column_runner);
428         gtk_tree_view_append_column (GTK_TREE_VIEW (view), column);
429
430         column_runner++;
431         column = gtk_tree_view_column_new_with_attributes ( _("Time"), renderer, "text", column_runner, NULL);
432         gtk_tree_view_column_set_sort_column_id (column, column_runner);
433         gtk_tree_view_append_column (GTK_TREE_VIEW (view), column);
434
435         column_runner++;
436         column = gtk_tree_view_column_new_with_attributes ( _("Lat/Lon"), renderer, "text", column_runner, NULL);
437         gtk_tree_view_column_set_sort_column_id (column, column_runner);
438         gtk_tree_view_append_column (GTK_TREE_VIEW (view), column);
439
440         column_runner++;
441         column = gtk_tree_view_column_new_with_attributes ( _("Privacy"), renderer, "text", column_runner, NULL); // AKA Visibility
442         gtk_tree_view_column_set_sort_column_id (column, column_runner);
443         gtk_tree_view_append_column (GTK_TREE_VIEW (view), column);
444
445         GtkCellRenderer *renderer_toggle = gtk_cell_renderer_toggle_new ();
446         g_object_set (G_OBJECT (renderer_toggle), "activatable", FALSE, NULL); // No user action - value is just for display
447         column_runner++;
448         column = gtk_tree_view_column_new_with_attributes ( _("Within Current View"), renderer_toggle, "active", column_runner, NULL);
449         gtk_tree_view_column_set_sort_column_id (column, column_runner);
450         gtk_tree_view_append_column (GTK_TREE_VIEW (view), column);
451
452         gtk_tree_view_set_model(GTK_TREE_VIEW(view), GTK_TREE_MODEL(store));
453         gtk_tree_selection_set_mode( gtk_tree_view_get_selection(GTK_TREE_VIEW(view)), GTK_SELECTION_MULTIPLE );
454         g_object_unref(store);
455
456         GtkWidget *scrolledwindow = gtk_scrolled_window_new ( NULL, NULL );
457         gtk_scrolled_window_set_policy ( GTK_SCROLLED_WINDOW(scrolledwindow), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC );
458         gtk_container_add ( GTK_CONTAINER(scrolledwindow), view );
459
460         gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), label, FALSE, FALSE, 0);
461         gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), scrolledwindow, TRUE, TRUE, 0);
462
463         // Ensure a reasonable number of items are shown, but let the width be automatically sized
464         gtk_widget_set_size_request ( dialog, -1, 400) ;
465         gtk_widget_show_all ( dialog );
466
467         if ( response_w )
468                 gtk_widget_grab_focus ( response_w );
469
470         while ( gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT ) {
471
472                 // Possibily not the fastest method but we don't have thousands of entries to process...
473                 GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(view));
474                 GList *selected = NULL;
475
476                 //  because we don't store the full data in the gtk model, we have to scan & look it up
477                 if ( gtk_tree_model_get_iter_first( GTK_TREE_MODEL(store), &iter) ) {
478                         do {
479                                 if ( gtk_tree_selection_iter_is_selected ( selection, &iter ) ) {
480                                         // For every selected item,
481                                         // compare the name from the displayed view to every gpx entry to find the gpx this selection represents
482                                         gchar* name;
483                                         gtk_tree_model_get (GTK_TREE_MODEL(store), &iter, 0, &name, -1 );
484                                         // I believe the name of these items to be always unique
485                                         list_runner = list;
486                                         while (list_runner) {
487                                                 if ( !strcmp ( ((gpx_meta_data_t*)list_runner->data)->name, name ) ) {
488                                                         gpx_meta_data_t *copied = copy_gpx_meta_data_t (list_runner->data);
489                                                         selected = g_list_prepend (selected, copied);
490                                                         break;
491                                                 }
492                                                 list_runner = g_list_next ( list_runner );
493                                         }
494                                 }
495                         }
496                         while ( gtk_tree_model_iter_next ( GTK_TREE_MODEL(store), &iter ) );
497                 }
498
499                 if ( selected ) {
500                         gtk_widget_destroy ( dialog );
501                         return selected;
502                 }
503                 a_dialog_error_msg(parent, _("Nothing was selected"));
504         }
505         gtk_widget_destroy ( dialog );
506         return NULL;
507 }
508
509 static void none_found ( GtkWindow *gw )
510 {
511         GtkWidget *dialog = NULL;
512
513         dialog = gtk_dialog_new_with_buttons ( "", gw, 0, GTK_STOCK_OK, GTK_RESPONSE_ACCEPT, NULL );
514         gtk_window_set_title(GTK_WINDOW(dialog), _("GPS Traces"));
515
516         GtkWidget *search_label = gtk_label_new(_("None found!"));
517         gtk_box_pack_start ( GTK_BOX(GTK_DIALOG(dialog)->vbox), search_label, FALSE, FALSE, 5 );
518         gtk_dialog_set_default_response ( GTK_DIALOG(dialog), GTK_RESPONSE_ACCEPT );
519         gtk_widget_show_all(dialog);
520
521         gtk_dialog_run ( GTK_DIALOG(dialog) );
522         gtk_widget_destroy(dialog);
523 }
524
525 /**
526  * For each track - mark whether the start is in within the viewport
527  */
528 static void set_in_current_view_property ( VikTrwLayer *vtl, datasource_osm_my_traces_t *data, GList *gl )
529 {
530         gdouble min_lat, max_lat, min_lon, max_lon;
531         /* get Viewport bounding box */
532         vik_viewport_get_min_max_lat_lon ( data->vvp, &min_lat, &max_lat, &min_lon, &max_lon );
533
534         LatLonBBox bbox;
535         bbox.north = max_lat;
536         bbox.east = max_lon;
537         bbox.south = min_lat;
538         bbox.west = min_lon;
539
540         GList *iterator = gl;
541         while ( iterator ) {
542                 gpx_meta_data_t* gmd = (gpx_meta_data_t*)iterator->data;
543                 // Convert point position into a 'fake' bounding box
544                 // TODO - probably should have function to see if point is within bounding box
545                 //   rather than constructing this fake bounding box for the test
546                 LatLonBBox gmd_bbox;
547                 gmd_bbox.north = gmd->ll.lat;
548                 gmd_bbox.east = gmd->ll.lon;
549                 gmd_bbox.south = gmd->ll.lat;
550                 gmd_bbox.west = gmd->ll.lon;
551
552                 if ( BBOX_INTERSECT ( bbox, gmd_bbox ) )
553                         gmd->in_current_view = TRUE;
554
555                 iterator = g_list_next ( iterator );
556         }
557 }
558
559 static gboolean datasource_osm_my_traces_process ( VikTrwLayer *vtl, const gchar *cmd, const gchar *extra, BabelStatusFunc status_cb, acq_dialog_widgets_t *adw, DownloadMapOptions *options_unused )
560 {
561         //datasource_osm_my_traces_t *data = (datasource_osm_my_traces_t *)adw->user_data;
562
563         gboolean result;
564
565         gchar *user_pass = osm_get_login();
566
567         DownloadMapOptions options = { FALSE, FALSE, NULL, 2, NULL, user_pass }; // Allow a couple of redirects
568
569         xml_data *xd = g_malloc ( sizeof (xml_data) );
570         //xd->xpath = g_string_new ( "" );
571         xd->c_cdata = g_string_new ( "" );
572         xd->current_tag = tt_unknown;
573         xd->current_gpx_meta_data = new_gpx_meta_data_t();
574         xd->list_of_gpx_meta_data = NULL;
575
576         gchar *tmpname = a_download_uri_to_tmp_file ( DS_OSM_TRACES_GPX_FILES, &options );
577         result = read_gpx_files_metadata_xml ( tmpname, xd );
578         // Test already downloaded metadata file: eg:
579         //result = read_gpx_files_metadata_xml ( "/tmp/viking-download.GI47PW", xd );
580
581         if ( tmpname ) {
582                 g_remove ( tmpname );
583                 g_free ( tmpname );
584         }
585
586         if ( ! result )
587                 return FALSE;
588
589         if ( g_list_length ( xd->list_of_gpx_meta_data ) == 0 ) {
590                 if (!vik_datasource_osm_my_traces_interface.is_thread)
591                         none_found ( GTK_WINDOW(adw->vw) );
592                 return FALSE;
593         }
594
595         xd->list_of_gpx_meta_data = g_list_reverse ( xd->list_of_gpx_meta_data );
596
597         set_in_current_view_property ( vtl, adw->user_data, xd->list_of_gpx_meta_data );
598
599     if (vik_datasource_osm_my_traces_interface.is_thread) gdk_threads_enter();
600         GList *selected = select_from_list ( GTK_WINDOW(adw->vw), xd->list_of_gpx_meta_data, "Select GPS Traces", "Select the GPS traces you want to add." );
601     if (vik_datasource_osm_my_traces_interface.is_thread) gdk_threads_leave();
602
603         // If passed in on an existing layer - we will create everything into that.
604         //  thus with many differing gpx's - this will combine all waypoints into this single layer!
605         // Hence the preference is to create multiple layers
606         //  and so this creation of the layers must be managed here
607
608         gboolean create_new_layer = ( !vtl );
609
610         // Only update the screen on the last layer acquired
611         VikTrwLayer *vtl_last = vtl;
612         gboolean got_something = FALSE;
613
614         GList *selected_iterator = selected;
615         while ( selected_iterator ) {
616
617                 VikTrwLayer *vtlX = vtl;
618
619                 if ( create_new_layer ) {
620                         // Have data but no layer - so create one
621                         vtlX = VIK_TRW_LAYER ( vik_layer_create ( VIK_LAYER_TRW, vik_window_viewport(adw->vw), NULL, FALSE ) );
622                         if ( ((gpx_meta_data_t*)selected_iterator->data)->name )
623                                 vik_layer_rename ( VIK_LAYER ( vtlX ), ((gpx_meta_data_t*)selected_iterator->data)->name );
624                         else
625                                 vik_layer_rename ( VIK_LAYER ( vtlX ), _("My OSM Traces") );
626                         vik_aggregate_layer_add_layer ( vik_layers_panel_get_top_layer (adw->vlp), VIK_LAYER(vtlX), TRUE );
627                 }
628
629                 result = FALSE;
630                 gint gpx_id = ((gpx_meta_data_t*)selected_iterator->data)->id;
631                 if ( gpx_id ) {
632                         gchar *url = g_strdup_printf ( DS_OSM_TRACES_GPX_URL_FMT, gpx_id );
633
634                         result = a_babel_convert_from_url ( vtlX, url, "gpx", status_cb, adw, &options );
635                         // TODO investigate using a progress bar:
636                         // http://developer.gnome.org/gtk/2.24/GtkProgressBar.html
637
638                         got_something = got_something || result;
639                         // TODO feedback to UI to inform which traces failed
640                         if ( !result )
641                                 g_warning ( _("Unable to get trace: %s"), url );
642                 }
643
644                 if ( result ) {
645                         // Move to area of the track
646                         vik_trw_layer_auto_set_view ( vtlX, vik_window_viewport(adw->vw) );
647                         vik_layer_post_read ( VIK_LAYER(vtlX), vik_window_viewport(adw->vw), TRUE );
648                         vtl_last = vtlX;
649                 }
650                 else if ( create_new_layer ) {
651                         // Layer not needed as no data has been acquired
652                         g_object_unref ( vtlX );
653                 }
654
655                 selected_iterator = g_list_next ( selected_iterator );
656         }
657
658         // Free memory
659         if ( xd->current_gpx_meta_data )
660                 free_gpx_meta_data ( xd->current_gpx_meta_data, NULL );
661         g_free ( xd->current_gpx_meta_data );
662         free_gpx_meta_data_list ( xd->list_of_gpx_meta_data );
663         free_gpx_meta_data_list ( selected );
664         g_free ( xd );
665         g_free ( user_pass );
666
667         // Would prefer to keep the update in acquire.c,
668         //  however since we may create the layer - need to do the update here
669         if ( got_something )
670                 vik_layer_emit_update ( VIK_LAYER(vtl_last) );
671
672         // ATM The user is only informed if all getting *all* of the traces failed
673         if ( selected )
674                 result = got_something;
675         else
676                 // Process was cancelled but need to return that it proceeded as expected
677                 result = TRUE;
678
679         return result;
680 }
681
682 static void datasource_osm_my_traces_cleanup ( gpointer data )
683 {
684         g_free ( data );
685 }