]> git.street.me.uk Git - andy/viking.git/blob - src/file.c
help/Makefile.am: explicitly list figures.
[andy/viking.git] / src / file.c
1 /*
2  * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
3  *
4  * Copyright (C) 2003-2005, Evan Battaglia <gtoevan@gmx.net>
5  * Copyright (C) 2012, Guilhem Bonnefille <guilhem.bonnefille@gmail.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
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26 #include "viking.h"
27
28 #include "gpx.h"
29 #include "babel.h"
30
31 #include <string.h>
32 #include <stdlib.h>
33 #include <stdio.h>
34 #ifdef HAVE_UNISTD_H
35 #include <unistd.h>
36 #endif
37 #include <glib.h>
38 #include <glib/gstdio.h>
39 #include <glib/gi18n.h>
40
41 #define TEST_BOOLEAN(str) (! ((str)[0] == '\0' || (str)[0] == '0' || (str)[0] == 'n' || (str)[0] == 'N' || (str)[0] == 'f' || (str)[0] == 'F') )
42 #define VIK_MAGIC "#VIK"
43 #define GPX_MAGIC "<?xm"
44 #define VIK_MAGIC_LEN 4
45
46 #ifdef WINDOWS
47 #define FILE_SEP '\\'
48 #else
49 #define FILE_SEP '/'
50 #endif
51
52 #define VIKING_FILE_VERSION 1
53
54 typedef struct _Stack Stack;
55
56 struct _Stack {
57   Stack *under;
58   gpointer *data;
59 };
60
61 static void pop(Stack **stack) {
62   Stack *tmp = (*stack)->under;
63   g_free ( *stack );
64   *stack = tmp;
65 }
66
67 static void push(Stack **stack)
68 {
69   Stack *tmp = g_malloc ( sizeof ( Stack ) );
70   tmp->under = *stack;
71   *stack = tmp;
72 }
73
74 static gboolean check_magic ( FILE *f, const gchar *magic_number )
75 {
76   gchar magic[VIK_MAGIC_LEN];
77   gboolean rv = FALSE;
78   gint8 i;
79   if ( fread(magic, 1, sizeof(magic), f) == sizeof(magic) &&
80       strncmp(magic, magic_number, sizeof(magic)) == 0 )
81     rv = TRUE;
82   for ( i = sizeof(magic)-1; i >= 0; i-- ) /* the ol' pushback */
83     ungetc(magic[i],f);
84   return rv;
85 }
86
87
88 static gboolean str_starts_with ( const gchar *haystack, const gchar *needle, guint16 len_needle, gboolean must_be_longer )
89 {
90   if ( strlen(haystack) > len_needle - (!must_be_longer) && strncasecmp ( haystack, needle, len_needle ) == 0 )
91     return TRUE;
92   return FALSE;
93 }
94
95 static guint16 layer_type_from_string ( const gchar *str )
96 {
97   guint8 i;
98   for ( i = 0; i < VIK_LAYER_NUM_TYPES; i++ )
99     if ( strcasecmp ( str, vik_layer_get_interface(i)->fixed_layer_name ) == 0 )
100       return i;
101   return -1;
102 }
103
104 void file_write_layer_param ( FILE *f, const gchar *name, guint8 type, VikLayerParamData data ) {
105       /* string lists are handled differently. We get a GList (that shouldn't
106        * be freed) back for get_param and if it is null we shouldn't write
107        * anything at all (otherwise we'd read in a list with an empty string,
108        * not an empty string list.
109        */
110       if ( type == VIK_LAYER_PARAM_STRING_LIST ) {
111         if ( data.sl ) {
112           GList *iter = (GList *)data.sl;
113           while ( iter ) {
114             fprintf ( f, "%s=", name );
115             fprintf ( f, "%s\n", (gchar *)(iter->data) );
116             iter = iter->next;
117           }
118         }
119       } else {
120         fprintf ( f, "%s=", name );
121         switch ( type )
122         {
123           case VIK_LAYER_PARAM_DOUBLE: {
124   //          char buf[15]; /* locale independent */
125   //          fprintf ( f, "%s\n", (char *) g_dtostr (data.d, buf, sizeof (buf)) ); break;
126               fprintf ( f, "%f\n", data.d );
127               break;
128          }
129           case VIK_LAYER_PARAM_UINT: fprintf ( f, "%d\n", data.u ); break;
130           case VIK_LAYER_PARAM_INT: fprintf ( f, "%d\n", data.i ); break;
131           case VIK_LAYER_PARAM_BOOLEAN: fprintf ( f, "%c\n", data.b ? 't' : 'f' ); break;
132           case VIK_LAYER_PARAM_STRING: fprintf ( f, "%s\n", data.s ); break;
133           case VIK_LAYER_PARAM_COLOR: fprintf ( f, "#%.2x%.2x%.2x\n", (int)(data.c.red/256),(int)(data.c.green/256),(int)(data.c.blue/256)); break;
134         }
135       }
136 }
137
138 static void write_layer_params_and_data ( VikLayer *l, FILE *f )
139 {
140   VikLayerParam *params = vik_layer_get_interface(l->type)->params;
141   VikLayerFuncGetParam get_param = vik_layer_get_interface(l->type)->get_param;
142
143   fprintf ( f, "name=%s\n", l->name ? l->name : "" );
144   if ( !l->visible )
145     fprintf ( f, "visible=f\n" );
146
147   if ( params && get_param )
148   {
149     VikLayerParamData data;
150     guint16 i, params_count = vik_layer_get_interface(l->type)->params_count;
151     for ( i = 0; i < params_count; i++ )
152     {
153       data = get_param(l, i, TRUE);
154       file_write_layer_param(f, params[i].name, params[i].type, data);
155     }
156   }
157   if ( vik_layer_get_interface(l->type)->write_file_data )
158   {
159     fprintf ( f, "\n\n~LayerData\n" );
160     vik_layer_get_interface(l->type)->write_file_data ( l, f );
161     fprintf ( f, "~EndLayerData\n" );
162   }
163   /* foreach param:
164      write param, and get_value, etc.
165      then run layer data, and that's it.
166   */
167 }
168
169 static void file_write ( VikAggregateLayer *top, FILE *f, gpointer vp )
170 {
171   Stack *stack = NULL;
172   VikLayer *current_layer;
173   struct LatLon ll;
174   VikViewportDrawMode mode;
175   gchar *modestring = NULL;
176
177   push(&stack);
178   stack->data = (gpointer) vik_aggregate_layer_get_children(VIK_AGGREGATE_LAYER(top));
179   stack->under = NULL;
180
181   /* crazhy CRAZHY */
182   vik_coord_to_latlon ( vik_viewport_get_center ( VIK_VIEWPORT(vp) ), &ll );
183
184   mode = vik_viewport_get_drawmode ( VIK_VIEWPORT(vp) );
185   switch ( mode ) {
186     case VIK_VIEWPORT_DRAWMODE_UTM: modestring = "utm"; break;
187     case VIK_VIEWPORT_DRAWMODE_EXPEDIA: modestring = "expedia"; break;
188     case VIK_VIEWPORT_DRAWMODE_MERCATOR: modestring = "mercator"; break;
189     case VIK_VIEWPORT_DRAWMODE_LATLON: modestring = "latlon"; break;
190     default:
191       g_critical("Houston, we've had a problem. mode=%d", mode);
192   }
193
194   fprintf ( f, "#VIKING GPS Data file " VIKING_URL "\n" );
195   fprintf ( f, "FILE_VERSION=%d\n", VIKING_FILE_VERSION );
196   fprintf ( f, "\nxmpp=%f\nympp=%f\nlat=%f\nlon=%f\nmode=%s\ncolor=%s\nhighlightcolor=%s\ndrawscale=%s\ndrawcentermark=%s\ndrawhighlight=%s\n",
197       vik_viewport_get_xmpp ( VIK_VIEWPORT(vp) ), vik_viewport_get_ympp ( VIK_VIEWPORT(vp) ), ll.lat, ll.lon,
198       modestring, vik_viewport_get_background_color(VIK_VIEWPORT(vp)),
199       vik_viewport_get_highlight_color(VIK_VIEWPORT(vp)),
200       vik_viewport_get_draw_scale(VIK_VIEWPORT(vp)) ? "t" : "f",
201       vik_viewport_get_draw_centermark(VIK_VIEWPORT(vp)) ? "t" : "f",
202       vik_viewport_get_draw_highlight(VIK_VIEWPORT(vp)) ? "t" : "f" );
203
204   if ( ! VIK_LAYER(top)->visible )
205     fprintf ( f, "visible=f\n" );
206
207   while (stack && stack->data)
208   {
209     current_layer = VIK_LAYER(((GList *)stack->data)->data);
210     fprintf ( f, "\n~Layer %s\n", vik_layer_get_interface(current_layer->type)->fixed_layer_name );
211     write_layer_params_and_data ( current_layer, f );
212     if ( current_layer->type == VIK_LAYER_AGGREGATE && !vik_aggregate_layer_is_empty(VIK_AGGREGATE_LAYER(current_layer)) )
213     {
214       push(&stack);
215       stack->data = (gpointer) vik_aggregate_layer_get_children(VIK_AGGREGATE_LAYER(current_layer));
216     }
217     else if ( current_layer->type == VIK_LAYER_GPS && !vik_gps_layer_is_empty(VIK_GPS_LAYER(current_layer)) )
218     {
219       push(&stack);
220       stack->data = (gpointer) vik_gps_layer_get_children(VIK_GPS_LAYER(current_layer));
221     }
222     else
223     {
224       stack->data = (gpointer) ((GList *)stack->data)->next;
225       fprintf ( f, "~EndLayer\n\n" );
226       while ( stack && (!stack->data) )
227       {
228         pop(&stack);
229         if ( stack )
230         {
231           stack->data = (gpointer) ((GList *)stack->data)->next;
232           fprintf ( f, "~EndLayer\n\n" );
233         }
234       }
235     }
236   }
237 /*
238   get vikaggregatelayer's children (?)
239   foreach write ALL params,
240   then layer data (IF function exists)
241   then endlayer
242
243   impl:
244   stack of layers (LIST) we are working on
245   when layer->next == NULL ...
246   we move on.
247 */
248 }
249
250 static void string_list_delete ( gpointer key, gpointer l, gpointer user_data )
251 {
252   /* 20071021 bugfix */
253   GList *iter = (GList *) l;
254   while ( iter ) {
255     g_free ( iter->data );
256     iter = iter->next;
257   }
258   g_list_free ( (GList *) l );
259 }
260
261 static void string_list_set_param (gint i, GList *list, gpointer *layer_and_vp)
262 {
263   VikLayerParamData x;
264   x.sl = list;
265   vik_layer_set_param ( VIK_LAYER(layer_and_vp[0]), i, x, layer_and_vp[1], TRUE );
266 }
267
268 /**
269  * Read in a Viking file and return how successful the parsing was
270  * ATM this will always work, in that even if there are parsing problems
271  *  then there will be no new values to override the defaults
272  *
273  * TODO flow up line number(s) / error messages of problems encountered...
274  *
275  */
276 static gboolean file_read ( VikAggregateLayer *top, FILE *f, VikViewport *vp )
277 {
278   Stack *stack;
279   struct LatLon ll = { 0.0, 0.0 };
280   gchar buffer[4096];
281   gchar *line;
282   guint16 len;
283   long line_num = 0;
284
285   VikLayerParam *params = NULL; /* for current layer, so we don't have to keep on looking up interface */
286   guint8 params_count = 0;
287
288   GHashTable *string_lists = g_hash_table_new(g_direct_hash,g_direct_equal);
289
290   gboolean successful_read = TRUE;
291
292   push(&stack);
293   stack->under = NULL;
294   stack->data = (gpointer) top;
295
296   while ( fgets ( buffer, 4096, f ) )
297   {
298     line_num++;
299
300     line = buffer;
301     while ( *line == ' ' || *line =='\t' )
302       line++;
303
304     if ( line[0] == '#' )
305       continue;
306     
307
308     len = strlen(line);
309     if ( len > 0 && line[len-1] == '\n' )
310       line[--len] = '\0';
311     if ( len > 0 && line[len-1] == '\r' )
312       line[--len] = '\0';
313
314     if ( len == 0 )
315       continue;
316
317
318     if ( line[0] == '~' )
319     {
320       line++; len--;
321       if ( *line == '\0' )
322         continue;
323       else if ( str_starts_with ( line, "Layer ", 6, TRUE ) )
324       {
325         int parent_type = VIK_LAYER(stack->data)->type;
326         if ( ( ! stack->data ) || ((parent_type != VIK_LAYER_AGGREGATE) && (parent_type != VIK_LAYER_GPS)) )
327         {
328           successful_read = FALSE;
329           g_warning ( "Line %ld: Layer command inside non-Aggregate Layer (type %d)", line_num, parent_type );
330           push(&stack); /* inside INVALID layer */
331           stack->data = NULL;
332           continue;
333         }
334         else
335         {
336           gint16 type = layer_type_from_string ( line+6 );
337           push(&stack);
338           if ( type == -1 )
339           {
340             successful_read = FALSE;
341             g_warning ( "Line %ld: Unknown type %s", line_num, line+6 );
342             stack->data = NULL;
343           }
344           else if (parent_type == VIK_LAYER_GPS)
345           {
346             stack->data = (gpointer) vik_gps_layer_get_a_child(VIK_GPS_LAYER(stack->under->data));
347             params = vik_layer_get_interface(type)->params;
348             params_count = vik_layer_get_interface(type)->params_count;
349           }
350           else
351           {
352             stack->data = (gpointer) vik_layer_create ( type, vp, NULL, FALSE );
353             params = vik_layer_get_interface(type)->params;
354             params_count = vik_layer_get_interface(type)->params_count;
355           }
356         }
357       }
358       else if ( str_starts_with ( line, "EndLayer", 8, FALSE ) )
359       {
360         if ( stack->under == NULL ) {
361           successful_read = FALSE;
362           g_warning ( "Line %ld: Mismatched ~EndLayer command", line_num );
363         }
364         else
365         {
366           /* add any string lists we've accumulated */
367           gpointer layer_and_vp[2];
368           layer_and_vp[0] = stack->data;
369           layer_and_vp[1] = vp;
370           g_hash_table_foreach ( string_lists, (GHFunc) string_list_set_param, layer_and_vp );
371           g_hash_table_remove_all ( string_lists );
372
373           if ( stack->data && stack->under->data )
374           {
375             if (VIK_LAYER(stack->under->data)->type == VIK_LAYER_AGGREGATE) {
376               vik_aggregate_layer_add_layer ( VIK_AGGREGATE_LAYER(stack->under->data), VIK_LAYER(stack->data) );
377               vik_layer_post_read ( VIK_LAYER(stack->data), vp, TRUE );
378             }
379             else if (VIK_LAYER(stack->under->data)->type == VIK_LAYER_GPS) {
380               /* TODO: anything else needs to be done here ? */
381             }
382             else {
383               successful_read = FALSE;
384               g_warning ( "Line %ld: EndLayer command inside non-Aggregate Layer (type %d)", line_num, VIK_LAYER(stack->data)->type );
385             }
386           }
387           pop(&stack);
388         }
389       }
390       else if ( str_starts_with ( line, "LayerData", 9, FALSE ) )
391       {
392         if ( stack->data && vik_layer_get_interface(VIK_LAYER(stack->data)->type)->read_file_data )
393         {
394           /* must read until hits ~EndLayerData */
395           if ( ! vik_layer_get_interface(VIK_LAYER(stack->data)->type)->read_file_data ( VIK_LAYER(stack->data), f ) )
396             successful_read = FALSE;
397         }
398         else
399         { /* simply skip layer data over */
400           while ( fgets ( buffer, 4096, f ) )
401           {
402             line_num++;
403
404             line = buffer;
405
406             len = strlen(line);
407             if ( len > 0 && line[len-1] == '\n' )
408               line[--len] = '\0';
409             if ( len > 0 && line[len-1] == '\r' )
410               line[--len] = '\0';
411             if ( strcasecmp ( line, "~EndLayerData" ) == 0 )
412               break;
413           }
414           continue;
415         }
416       }
417       else
418       {
419         successful_read = FALSE;
420         g_warning ( "Line %ld: Unknown tilde command", line_num );
421       }
422     }
423     else
424     {
425       gint32 eq_pos = -1;
426       guint16 i;
427       if ( ! stack->data )
428         continue;
429
430       for ( i = 0; i < len; i++ )
431         if ( line[i] == '=' )
432           eq_pos = i;
433
434       if ( stack->under == NULL && eq_pos == 12 && strncasecmp ( line, "FILE_VERSION", eq_pos ) == 0) {
435         gint version = strtol(line+13, NULL, 10);
436         g_debug ( "%s: reading file version %d", __FUNCTION__, version );
437         if ( version > VIKING_FILE_VERSION )
438           successful_read = FALSE;
439         // However we'll still carry and attempt to read whatever we can
440       }
441       else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "xmpp", eq_pos ) == 0) /* "hard coded" params: global & for all layer-types */
442         vik_viewport_set_xmpp ( VIK_VIEWPORT(vp), strtod ( line+5, NULL ) );
443       else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "ympp", eq_pos ) == 0)
444         vik_viewport_set_ympp ( VIK_VIEWPORT(vp), strtod ( line+5, NULL ) );
445       else if ( stack->under == NULL && eq_pos == 3 && strncasecmp ( line, "lat", eq_pos ) == 0 )
446         ll.lat = strtod ( line+4, NULL );
447       else if ( stack->under == NULL && eq_pos == 3 && strncasecmp ( line, "lon", eq_pos ) == 0 )
448         ll.lon = strtod ( line+4, NULL );
449       else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "utm" ) == 0)
450         vik_viewport_set_drawmode ( VIK_VIEWPORT(vp), VIK_VIEWPORT_DRAWMODE_UTM);
451       else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "expedia" ) == 0)
452         vik_viewport_set_drawmode ( VIK_VIEWPORT(vp), VIK_VIEWPORT_DRAWMODE_EXPEDIA );
453       else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "google" ) == 0)
454       {
455         successful_read = FALSE;
456         g_warning ( _("Draw mode '%s' no more supported"), "google" );
457       }
458       else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "kh" ) == 0)
459       {
460         successful_read = FALSE;
461         g_warning ( _("Draw mode '%s' no more supported"), "kh" );
462       }
463       else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "mercator" ) == 0)
464         vik_viewport_set_drawmode ( VIK_VIEWPORT(vp), VIK_VIEWPORT_DRAWMODE_MERCATOR );
465       else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "latlon" ) == 0)
466         vik_viewport_set_drawmode ( VIK_VIEWPORT(vp), VIK_VIEWPORT_DRAWMODE_LATLON );
467       else if ( stack->under == NULL && eq_pos == 5 && strncasecmp ( line, "color", eq_pos ) == 0 )
468         vik_viewport_set_background_color ( VIK_VIEWPORT(vp), line+6 );
469       else if ( stack->under == NULL && eq_pos == 14 && strncasecmp ( line, "highlightcolor", eq_pos ) == 0 )
470         vik_viewport_set_highlight_color ( VIK_VIEWPORT(vp), line+15 );
471       else if ( stack->under == NULL && eq_pos == 9 && strncasecmp ( line, "drawscale", eq_pos ) == 0 )
472         vik_viewport_set_draw_scale ( VIK_VIEWPORT(vp), TEST_BOOLEAN(line+10) );
473       else if ( stack->under == NULL && eq_pos == 14 && strncasecmp ( line, "drawcentermark", eq_pos ) == 0 )
474         vik_viewport_set_draw_centermark ( VIK_VIEWPORT(vp), TEST_BOOLEAN(line+15) );
475       else if ( stack->under == NULL && eq_pos == 13 && strncasecmp ( line, "drawhighlight", eq_pos ) == 0 )
476         vik_viewport_set_draw_highlight ( VIK_VIEWPORT(vp), TEST_BOOLEAN(line+14) );
477       else if ( stack->under && eq_pos == 4 && strncasecmp ( line, "name", eq_pos ) == 0 )
478         vik_layer_rename ( VIK_LAYER(stack->data), line+5 );
479       else if ( eq_pos == 7 && strncasecmp ( line, "visible", eq_pos ) == 0 )
480         VIK_LAYER(stack->data)->visible = TEST_BOOLEAN(line+8);
481       else if ( eq_pos != -1 && stack->under )
482       {
483         gboolean found_match = FALSE;
484
485         /* go thru layer params. if len == eq_pos && starts_with jazz, set it. */
486         /* also got to check for name and visible. */
487
488         if ( ! params )
489         {
490           successful_read = FALSE;
491           g_warning ( "Line %ld: No options for this kind of layer", line_num );
492           continue;
493         }
494
495         for ( i = 0; i < params_count; i++ )
496           if ( strlen(params[i].name) == eq_pos && strncasecmp ( line, params[i].name, eq_pos ) == 0 )
497           {
498             VikLayerParamData x;
499             line += eq_pos+1;
500             if ( params[i].type == VIK_LAYER_PARAM_STRING_LIST ) {
501               GList *l = g_list_append ( g_hash_table_lookup ( string_lists, GINT_TO_POINTER ((gint) i) ), 
502                                          g_strdup(line) );
503               g_hash_table_replace ( string_lists, GINT_TO_POINTER ((gint)i), l );
504               /* add the value to a list, possibly making a new list.
505                * this will be passed to the layer when we read an ~EndLayer */
506             } else {
507               switch ( params[i].type )
508               {
509                 case VIK_LAYER_PARAM_DOUBLE: x.d = strtod(line, NULL); break;
510                 case VIK_LAYER_PARAM_UINT: x.u = strtoul(line, NULL, 10); break;
511                 case VIK_LAYER_PARAM_INT: x.i = strtol(line, NULL, 10); break;
512                 case VIK_LAYER_PARAM_BOOLEAN: x.b = TEST_BOOLEAN(line); break;
513                 case VIK_LAYER_PARAM_COLOR: memset(&(x.c), 0, sizeof(x.c)); /* default: black */
514                                           gdk_color_parse ( line, &(x.c) ); break;
515                 /* STRING or STRING_LIST -- if STRING_LIST, just set param to add a STRING */
516                 default: x.s = line;
517               }
518               vik_layer_set_param ( VIK_LAYER(stack->data), i, x, vp, TRUE );
519             }
520             found_match = TRUE;
521             break;
522           }
523         if ( ! found_match ) {
524           // ATM don't flow up this issue because at least one internal parameter has changed from version 1.3
525           //   and don't what to worry users about raising such issues
526           // TODO Maybe hold old values here - compare the line value against them and if a match
527           //       generate a different style of message in the GUI...
528           // successful_read = FALSE;
529           g_warning ( "Line %ld: Unknown parameter. Line:\n%s", line_num, line );
530         }
531       }
532       else {
533         successful_read = FALSE;
534         g_warning ( "Line %ld: Invalid parameter or parameter outside of layer.", line_num );
535       }
536     }
537 /* could be:
538 [Layer Type=Bla]
539 [EndLayer]
540 [LayerData]
541 name=this
542 #comment
543 */
544   }
545
546   while ( stack )
547   {
548     if ( stack->under && stack->under->data && stack->data )
549     {
550       vik_aggregate_layer_add_layer ( VIK_AGGREGATE_LAYER(stack->under->data), VIK_LAYER(stack->data) );
551       vik_layer_post_read ( VIK_LAYER(stack->data), vp, TRUE );
552     }
553     pop(&stack);
554   }
555
556   if ( ll.lat != 0.0 || ll.lon != 0.0 )
557     vik_viewport_set_center_latlon ( VIK_VIEWPORT(vp), &ll );
558
559   if ( ( ! VIK_LAYER(top)->visible ) && VIK_LAYER(top)->realized )
560     vik_treeview_item_set_visible ( VIK_LAYER(top)->vt, &(VIK_LAYER(top)->iter), FALSE ); 
561
562   /* delete anything we've forgotten about -- should only happen when file ends before an EndLayer */
563   g_hash_table_foreach ( string_lists, string_list_delete, NULL );
564   g_hash_table_destroy ( string_lists );
565
566   return successful_read;
567 }
568
569 /*
570 read thru file
571 if "[Layer Type="
572   push(&stack)
573   new default layer of type (str_to_type) (check interface->name)
574 if "[EndLayer]"
575   VikLayer *vl = stack->data;
576   pop(&stack);
577   vik_aggregate_layer_add_layer(stack->data, vl);
578 if "[LayerData]"
579   vik_layer_data ( VIK_LAYER_DATA(stack->data), f, vp );
580
581 */
582
583 /* ---------------------------------------------------- */
584
585 static FILE *xfopen ( const char *fn, const char *mode )
586 {
587   if ( strcmp(fn,"-") == 0 )
588     return stdin;
589   else
590     return g_fopen(fn, "r");
591 }
592
593 static void xfclose ( FILE *f )
594 {
595   if ( f != stdin && f != stdout ) {
596     fclose ( f );
597     f = NULL;
598   }
599 }
600
601 /*
602  * Function to determine if a filename is a 'viking' type file
603  */
604 gboolean check_file_magic_vik ( const gchar *filename )
605 {
606   gboolean result = FALSE;
607   FILE *ff = xfopen ( filename, "r" );
608   if ( ff ) {
609     result = check_magic ( ff, VIK_MAGIC );
610     xfclose ( ff );
611   }
612   return result;
613 }
614
615 VikLoadType_t a_file_load ( VikAggregateLayer *top, VikViewport *vp, const gchar *filename_or_uri )
616 {
617   g_return_val_if_fail ( vp != NULL, LOAD_TYPE_READ_FAILURE );
618
619   char *filename = (char *)filename_or_uri;
620   if (strncmp(filename, "file://", 7) == 0)
621     filename = filename + 7;
622
623   FILE *f = xfopen ( filename, "r" );
624
625   if ( ! f )
626     return LOAD_TYPE_READ_FAILURE;
627
628   VikLoadType_t load_answer = LOAD_TYPE_OTHER_SUCCESS;
629
630   // Attempt loading the primary file type first - our internal .vik file:
631   if ( check_magic ( f, VIK_MAGIC ) )
632   {
633     if ( file_read ( top, f, vp ) )
634       load_answer = LOAD_TYPE_VIK_SUCCESS;
635     else
636       load_answer = LOAD_TYPE_VIK_FAILURE_NON_FATAL;
637   }
638   else
639   {
640         // For all other file types which consist of tracks, routes and/or waypoints,
641         //  must be loaded into a new TrackWaypoint layer (hence it be created)
642     gboolean success = TRUE; // Detect load failures - mainly to remove the layer created as it's not required
643
644     VikLayer *vtl = vik_layer_create ( VIK_LAYER_TRW, vp, NULL, FALSE );
645
646     // In fact both kml & gpx files start the same as they are in xml
647     if ( check_file_ext ( filename, ".kml" ) && check_magic ( f, GPX_MAGIC ) ) {
648       // Implicit Conversion
649       if ( ! ( success = a_babel_convert_from ( VIK_TRW_LAYER(vtl), "-i kml", filename, NULL, NULL, NULL ) ) ) {
650         load_answer = LOAD_TYPE_GPSBABEL_FAILURE;
651       }
652     }
653     // NB use a extension check first, as a GPX file header may have a Byte Order Mark (BOM) in it
654     //    - which currently confuses our check_magic function
655     else if ( check_file_ext ( filename, ".gpx" ) || check_magic ( f, GPX_MAGIC ) ) {
656       if ( ! ( success = a_gpx_read_file ( VIK_TRW_LAYER(vtl), f ) ) ) {
657         load_answer = LOAD_TYPE_GPX_FAILURE;
658       }
659     }
660     else {
661       // Try final supported file type
662       if ( ! ( success = a_gpspoint_read_file ( VIK_TRW_LAYER(vtl), f ) ) ) {
663                 // Failure here means we don't know how to handle the file
664         load_answer = LOAD_TYPE_UNSUPPORTED_FAILURE;
665           }
666     }
667
668     // Clean up when we can't handle the file
669     if ( ! success ) {
670       // free up layer
671       g_object_unref ( vtl );
672     }
673     else {
674       // Complete the setup from the successful load
675       vik_layer_rename ( vtl, a_file_basename ( filename ) );
676       vik_layer_post_read ( vtl, vp, TRUE );
677       vik_aggregate_layer_add_layer ( top, vtl );
678       vik_trw_layer_auto_set_view ( VIK_TRW_LAYER(vtl), vp );
679     }
680   }
681   xfclose(f);
682   return load_answer;
683 }
684
685 gboolean a_file_save ( VikAggregateLayer *top, gpointer vp, const gchar *filename )
686 {
687   FILE *f;
688
689   if (strncmp(filename, "file://", 7) == 0)
690     filename = filename + 7;
691
692   f = g_fopen(filename, "w");
693
694   if ( ! f )
695     return FALSE;
696
697   file_write ( top, f, vp );
698
699   fclose(f);
700   f = NULL;
701
702   return TRUE;
703 }
704
705
706 const gchar *a_file_basename ( const gchar *filename )
707 {
708   const gchar *t = filename + strlen(filename) - 1;
709   while ( --t > filename )
710     if ( *(t-1) == FILE_SEP )
711       break;
712   if ( t >= filename )
713     return t;
714   return filename;
715 }
716
717 /* example: 
718      gboolean is_gpx = check_file_ext ( "a/b/c.gpx", ".gpx" );
719 */
720 gboolean check_file_ext ( const gchar *filename, const gchar *fileext )
721 {
722   g_return_val_if_fail ( filename != NULL, FALSE );
723   g_return_val_if_fail ( fileext && fileext[0]=='.', FALSE );
724   const gchar *basename = a_file_basename(filename);
725   if (!basename)
726     return FALSE;
727
728   const char * dot = strrchr(basename, '.');
729   if (dot && !strcmp(dot, fileext))
730     return TRUE;
731
732   return FALSE;
733 }
734
735 /**
736  * a_file_export:
737  * @vtl: The TrackWaypoint to export data from
738  * @filename: The name of the file to be written
739  * @file_type: Choose one of the supported file types for the export
740  * @trk: If specified then only export this track rather than the whole layer
741  * @write_hidden: Whether to write invisible items
742  *
743  * A general export command to convert from Viking TRW layer data to an external supported format.
744  * The write_hidden option is provided mainly to be able to transfer selected items when uploading to a GPS
745  */
746 gboolean a_file_export ( VikTrwLayer *vtl, const gchar *filename, VikFileType_t file_type, VikTrack *trk, gboolean write_hidden )
747 {
748   GpxWritingOptions options = { FALSE, FALSE, write_hidden, FALSE };
749   FILE *f = g_fopen ( filename, "w" );
750   if ( f )
751   {
752     if ( trk ) {
753       switch ( file_type ) {
754         case FILE_TYPE_GPX:
755           // trk defined so can set the option
756           options.is_route = trk->is_route;
757           a_gpx_write_track_file ( trk, f, &options );
758           break;
759         default:
760           g_critical("Houston, we've had a problem. file_type=%d", file_type);
761       }
762     } else {
763       switch ( file_type ) {
764         case FILE_TYPE_GPSMAPPER:
765           a_gpsmapper_write_file ( vtl, f );
766           break;
767         case FILE_TYPE_GPX:
768           a_gpx_write_file ( vtl, f, &options );
769           break;
770         case FILE_TYPE_GPSPOINT:
771           a_gpspoint_write_file ( vtl, f );
772           break;
773         case FILE_TYPE_KML:
774           fclose ( f );
775           f = NULL;
776           switch ( a_vik_get_kml_export_units () ) {
777             case VIK_KML_EXPORT_UNITS_STATUTE:
778               return a_babel_convert_to ( vtl, NULL, "-o kml", filename, NULL, NULL );
779               break;
780             case VIK_KML_EXPORT_UNITS_NAUTICAL:
781               return a_babel_convert_to ( vtl, NULL, "-o kml,units=n", filename, NULL, NULL );
782               break;
783             default:
784               // VIK_KML_EXPORT_UNITS_METRIC:
785               return a_babel_convert_to ( vtl, NULL, "-o kml,units=m", filename, NULL, NULL );
786               break;
787           }
788           break;
789         default:
790           g_critical("Houston, we've had a problem. file_type=%d", file_type);
791       }
792     }
793     fclose ( f );
794     f = NULL;
795     return TRUE;
796   }
797   return FALSE;
798 }
799