]> git.street.me.uk Git - andy/viking.git/blob - src/file.c
[QA] Limit scope of includes of vikutils header.
[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  * Copyright (C) 2012-2013, Rob Norris <rw_norris@hotmail.com>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #endif
27 #include "viking.h"
28
29 #include "jpg.h"
30 #include "gpx.h"
31 #include "babel.h"
32
33 #include <string.h>
34 #include <stdlib.h>
35 #include <stdio.h>
36 #ifdef HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif
39 #ifdef WINDOWS
40 #define realpath(X,Y) _fullpath(Y,X,MAX_PATH)
41 #endif
42 #include <glib.h>
43 #include <glib/gstdio.h>
44 #include <glib/gi18n.h>
45
46 #include "file.h"
47
48 #define TEST_BOOLEAN(str) (! ((str)[0] == '\0' || (str)[0] == '0' || (str)[0] == 'n' || (str)[0] == 'N' || (str)[0] == 'f' || (str)[0] == 'F') )
49 #define VIK_MAGIC "#VIK"
50 #define GPX_MAGIC "<?xm"
51 #define VIK_MAGIC_LEN 4
52
53 #define VIKING_FILE_VERSION 1
54
55 typedef struct _Stack Stack;
56
57 struct _Stack {
58   Stack *under;
59   gpointer *data;
60 };
61
62 static void pop(Stack **stack) {
63   Stack *tmp = (*stack)->under;
64   g_free ( *stack );
65   *stack = tmp;
66 }
67
68 static void push(Stack **stack)
69 {
70   Stack *tmp = g_malloc ( sizeof ( Stack ) );
71   tmp->under = *stack;
72   *stack = tmp;
73 }
74
75 static gboolean check_magic ( FILE *f, const gchar *magic_number )
76 {
77   gchar magic[VIK_MAGIC_LEN];
78   gboolean rv = FALSE;
79   gint8 i;
80   if ( fread(magic, 1, sizeof(magic), f) == sizeof(magic) &&
81       strncmp(magic, magic_number, sizeof(magic)) == 0 )
82     rv = TRUE;
83   for ( i = sizeof(magic)-1; i >= 0; i-- ) /* the ol' pushback */
84     ungetc(magic[i],f);
85   return rv;
86 }
87
88
89 static gboolean str_starts_with ( const gchar *haystack, const gchar *needle, guint16 len_needle, gboolean must_be_longer )
90 {
91   if ( strlen(haystack) > len_needle - (!must_be_longer) && strncasecmp ( haystack, needle, len_needle ) == 0 )
92     return TRUE;
93   return FALSE;
94 }
95
96 void file_write_layer_param ( FILE *f, const gchar *name, VikLayerParamType type, VikLayerParamData data ) {
97       /* string lists are handled differently. We get a GList (that shouldn't
98        * be freed) back for get_param and if it is null we shouldn't write
99        * anything at all (otherwise we'd read in a list with an empty string,
100        * not an empty string list.
101        */
102       if ( type == VIK_LAYER_PARAM_STRING_LIST ) {
103         if ( data.sl ) {
104           GList *iter = (GList *)data.sl;
105           while ( iter ) {
106             fprintf ( f, "%s=", name );
107             fprintf ( f, "%s\n", (gchar *)(iter->data) );
108             iter = iter->next;
109           }
110         }
111       } else {
112         fprintf ( f, "%s=", name );
113         switch ( type )
114         {
115           case VIK_LAYER_PARAM_DOUBLE: {
116   //          char buf[15]; /* locale independent */
117   //          fprintf ( f, "%s\n", (char *) g_dtostr (data.d, buf, sizeof (buf)) ); break;
118               fprintf ( f, "%f\n", data.d );
119               break;
120          }
121           case VIK_LAYER_PARAM_UINT: fprintf ( f, "%d\n", data.u ); break;
122           case VIK_LAYER_PARAM_INT: fprintf ( f, "%d\n", data.i ); break;
123           case VIK_LAYER_PARAM_BOOLEAN: fprintf ( f, "%c\n", data.b ? 't' : 'f' ); break;
124           case VIK_LAYER_PARAM_STRING: fprintf ( f, "%s\n", data.s ? data.s : "" ); break;
125           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;
126           default: break;
127         }
128       }
129 }
130
131 static void write_layer_params_and_data ( VikLayer *l, FILE *f )
132 {
133   VikLayerParam *params = vik_layer_get_interface(l->type)->params;
134   VikLayerFuncGetParam get_param = vik_layer_get_interface(l->type)->get_param;
135
136   fprintf ( f, "name=%s\n", l->name ? l->name : "" );
137   if ( !l->visible )
138     fprintf ( f, "visible=f\n" );
139
140   if ( params && get_param )
141   {
142     VikLayerParamData data;
143     guint16 i, params_count = vik_layer_get_interface(l->type)->params_count;
144     for ( i = 0; i < params_count; i++ )
145     {
146       data = get_param(l, i, TRUE);
147       file_write_layer_param(f, params[i].name, params[i].type, data);
148     }
149   }
150   if ( vik_layer_get_interface(l->type)->write_file_data )
151   {
152     fprintf ( f, "\n\n~LayerData\n" );
153     vik_layer_get_interface(l->type)->write_file_data ( l, f );
154     fprintf ( f, "~EndLayerData\n" );
155   }
156   /* foreach param:
157      write param, and get_value, etc.
158      then run layer data, and that's it.
159   */
160 }
161
162 static void file_write ( VikAggregateLayer *top, FILE *f, gpointer vp )
163 {
164   Stack *stack = NULL;
165   VikLayer *current_layer;
166   struct LatLon ll;
167   VikViewportDrawMode mode;
168   gchar *modestring = NULL;
169
170   push(&stack);
171   stack->data = (gpointer) vik_aggregate_layer_get_children(VIK_AGGREGATE_LAYER(top));
172   stack->under = NULL;
173
174   /* crazhy CRAZHY */
175   vik_coord_to_latlon ( vik_viewport_get_center ( VIK_VIEWPORT(vp) ), &ll );
176
177   mode = vik_viewport_get_drawmode ( VIK_VIEWPORT(vp) );
178   switch ( mode ) {
179     case VIK_VIEWPORT_DRAWMODE_UTM: modestring = "utm"; break;
180     case VIK_VIEWPORT_DRAWMODE_EXPEDIA: modestring = "expedia"; break;
181     case VIK_VIEWPORT_DRAWMODE_MERCATOR: modestring = "mercator"; break;
182     case VIK_VIEWPORT_DRAWMODE_LATLON: modestring = "latlon"; break;
183     default:
184       g_critical("Houston, we've had a problem. mode=%d", mode);
185   }
186
187   fprintf ( f, "#VIKING GPS Data file " VIKING_URL "\n" );
188   fprintf ( f, "FILE_VERSION=%d\n", VIKING_FILE_VERSION );
189   fprintf ( f, "\nxmpp=%f\nympp=%f\nlat=%f\nlon=%f\nmode=%s\ncolor=%s\nhighlightcolor=%s\ndrawscale=%s\ndrawcentermark=%s\ndrawhighlight=%s\n",
190       vik_viewport_get_xmpp ( VIK_VIEWPORT(vp) ), vik_viewport_get_ympp ( VIK_VIEWPORT(vp) ), ll.lat, ll.lon,
191       modestring, vik_viewport_get_background_color(VIK_VIEWPORT(vp)),
192       vik_viewport_get_highlight_color(VIK_VIEWPORT(vp)),
193       vik_viewport_get_draw_scale(VIK_VIEWPORT(vp)) ? "t" : "f",
194       vik_viewport_get_draw_centermark(VIK_VIEWPORT(vp)) ? "t" : "f",
195       vik_viewport_get_draw_highlight(VIK_VIEWPORT(vp)) ? "t" : "f" );
196
197   if ( ! VIK_LAYER(top)->visible )
198     fprintf ( f, "visible=f\n" );
199
200   while (stack && stack->data)
201   {
202     current_layer = VIK_LAYER(((GList *)stack->data)->data);
203     fprintf ( f, "\n~Layer %s\n", vik_layer_get_interface(current_layer->type)->fixed_layer_name );
204     write_layer_params_and_data ( current_layer, f );
205     if ( current_layer->type == VIK_LAYER_AGGREGATE && !vik_aggregate_layer_is_empty(VIK_AGGREGATE_LAYER(current_layer)) )
206     {
207       push(&stack);
208       stack->data = (gpointer) vik_aggregate_layer_get_children(VIK_AGGREGATE_LAYER(current_layer));
209     }
210     else if ( current_layer->type == VIK_LAYER_GPS && !vik_gps_layer_is_empty(VIK_GPS_LAYER(current_layer)) )
211     {
212       push(&stack);
213       stack->data = (gpointer) vik_gps_layer_get_children(VIK_GPS_LAYER(current_layer));
214     }
215     else
216     {
217       stack->data = (gpointer) ((GList *)stack->data)->next;
218       fprintf ( f, "~EndLayer\n\n" );
219       while ( stack && (!stack->data) )
220       {
221         pop(&stack);
222         if ( stack )
223         {
224           stack->data = (gpointer) ((GList *)stack->data)->next;
225           fprintf ( f, "~EndLayer\n\n" );
226         }
227       }
228     }
229   }
230 /*
231   get vikaggregatelayer's children (?)
232   foreach write ALL params,
233   then layer data (IF function exists)
234   then endlayer
235
236   impl:
237   stack of layers (LIST) we are working on
238   when layer->next == NULL ...
239   we move on.
240 */
241 }
242
243 static void string_list_delete ( gpointer key, gpointer l, gpointer user_data )
244 {
245   /* 20071021 bugfix */
246   GList *iter = (GList *) l;
247   while ( iter ) {
248     g_free ( iter->data );
249     iter = iter->next;
250   }
251   g_list_free ( (GList *) l );
252 }
253
254 static void string_list_set_param (gint i, GList *list, gpointer *layer_and_vp)
255 {
256   VikLayerParamData x;
257   x.sl = list;
258   vik_layer_set_param ( VIK_LAYER(layer_and_vp[0]), i, x, layer_and_vp[1], TRUE );
259 }
260
261 /**
262  * Read in a Viking file and return how successful the parsing was
263  * ATM this will always work, in that even if there are parsing problems
264  *  then there will be no new values to override the defaults
265  *
266  * TODO flow up line number(s) / error messages of problems encountered...
267  *
268  */
269 static gboolean file_read ( VikAggregateLayer *top, FILE *f, const gchar *dirpath, VikViewport *vp )
270 {
271   Stack *stack;
272   struct LatLon ll = { 0.0, 0.0 };
273   gchar buffer[4096];
274   gchar *line;
275   guint16 len;
276   long line_num = 0;
277
278   VikLayerParam *params = NULL; /* for current layer, so we don't have to keep on looking up interface */
279   guint8 params_count = 0;
280
281   GHashTable *string_lists = g_hash_table_new(g_direct_hash,g_direct_equal);
282
283   gboolean successful_read = TRUE;
284
285   push(&stack);
286   stack->under = NULL;
287   stack->data = (gpointer) top;
288
289   while ( fgets ( buffer, 4096, f ) )
290   {
291     line_num++;
292
293     line = buffer;
294     while ( *line == ' ' || *line =='\t' )
295       line++;
296
297     if ( line[0] == '#' )
298       continue;
299     
300
301     len = strlen(line);
302     if ( len > 0 && line[len-1] == '\n' )
303       line[--len] = '\0';
304     if ( len > 0 && line[len-1] == '\r' )
305       line[--len] = '\0';
306
307     if ( len == 0 )
308       continue;
309
310
311     if ( line[0] == '~' )
312     {
313       line++; len--;
314       if ( *line == '\0' )
315         continue;
316       else if ( str_starts_with ( line, "Layer ", 6, TRUE ) )
317       {
318         int parent_type = VIK_LAYER(stack->data)->type;
319         if ( ( ! stack->data ) || ((parent_type != VIK_LAYER_AGGREGATE) && (parent_type != VIK_LAYER_GPS)) )
320         {
321           successful_read = FALSE;
322           g_warning ( "Line %ld: Layer command inside non-Aggregate Layer (type %d)", line_num, parent_type );
323           push(&stack); /* inside INVALID layer */
324           stack->data = NULL;
325           continue;
326         }
327         else
328         {
329           VikLayerTypeEnum type = vik_layer_type_from_string ( line+6 );
330           push(&stack);
331           if ( type == VIK_LAYER_NUM_TYPES )
332           {
333             successful_read = FALSE;
334             g_warning ( "Line %ld: Unknown type %s", line_num, line+6 );
335             stack->data = NULL;
336           }
337           else if (parent_type == VIK_LAYER_GPS)
338           {
339             stack->data = (gpointer) vik_gps_layer_get_a_child(VIK_GPS_LAYER(stack->under->data));
340             params = vik_layer_get_interface(type)->params;
341             params_count = vik_layer_get_interface(type)->params_count;
342           }
343           else
344           {
345             stack->data = (gpointer) vik_layer_create ( type, vp, FALSE );
346             params = vik_layer_get_interface(type)->params;
347             params_count = vik_layer_get_interface(type)->params_count;
348           }
349         }
350       }
351       else if ( str_starts_with ( line, "EndLayer", 8, FALSE ) )
352       {
353         if ( stack->under == NULL ) {
354           successful_read = FALSE;
355           g_warning ( "Line %ld: Mismatched ~EndLayer command", line_num );
356         }
357         else
358         {
359           /* add any string lists we've accumulated */
360           gpointer layer_and_vp[2];
361           layer_and_vp[0] = stack->data;
362           layer_and_vp[1] = vp;
363           g_hash_table_foreach ( string_lists, (GHFunc) string_list_set_param, layer_and_vp );
364           g_hash_table_remove_all ( string_lists );
365
366           if ( stack->data && stack->under->data )
367           {
368             if (VIK_LAYER(stack->under->data)->type == VIK_LAYER_AGGREGATE) {
369               vik_aggregate_layer_add_layer ( VIK_AGGREGATE_LAYER(stack->under->data), VIK_LAYER(stack->data), FALSE );
370               vik_layer_post_read ( VIK_LAYER(stack->data), vp, TRUE );
371             }
372             else if (VIK_LAYER(stack->under->data)->type == VIK_LAYER_GPS) {
373               /* TODO: anything else needs to be done here ? */
374             }
375             else {
376               successful_read = FALSE;
377               g_warning ( "Line %ld: EndLayer command inside non-Aggregate Layer (type %d)", line_num, VIK_LAYER(stack->data)->type );
378             }
379           }
380           pop(&stack);
381         }
382       }
383       else if ( str_starts_with ( line, "LayerData", 9, FALSE ) )
384       {
385         if ( stack->data && vik_layer_get_interface(VIK_LAYER(stack->data)->type)->read_file_data )
386         {
387           /* must read until hits ~EndLayerData */
388           if ( ! vik_layer_get_interface(VIK_LAYER(stack->data)->type)->read_file_data ( VIK_LAYER(stack->data), f, dirpath ) )
389             successful_read = FALSE;
390         }
391         else
392         { /* simply skip layer data over */
393           while ( fgets ( buffer, 4096, f ) )
394           {
395             line_num++;
396
397             line = buffer;
398
399             len = strlen(line);
400             if ( len > 0 && line[len-1] == '\n' )
401               line[--len] = '\0';
402             if ( len > 0 && line[len-1] == '\r' )
403               line[--len] = '\0';
404             if ( strcasecmp ( line, "~EndLayerData" ) == 0 )
405               break;
406           }
407           continue;
408         }
409       }
410       else
411       {
412         successful_read = FALSE;
413         g_warning ( "Line %ld: Unknown tilde command", line_num );
414       }
415     }
416     else
417     {
418       gint32 eq_pos = -1;
419       guint16 i;
420       if ( ! stack->data )
421         continue;
422
423       for ( i = 0; i < len; i++ )
424         if ( line[i] == '=' )
425           eq_pos = i;
426
427       if ( stack->under == NULL && eq_pos == 12 && strncasecmp ( line, "FILE_VERSION", eq_pos ) == 0) {
428         gint version = strtol(line+13, NULL, 10);
429         g_debug ( "%s: reading file version %d", __FUNCTION__, version );
430         if ( version > VIKING_FILE_VERSION )
431           successful_read = FALSE;
432         // However we'll still carry and attempt to read whatever we can
433       }
434       else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "xmpp", eq_pos ) == 0) /* "hard coded" params: global & for all layer-types */
435         vik_viewport_set_xmpp ( VIK_VIEWPORT(vp), strtod ( line+5, NULL ) );
436       else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "ympp", eq_pos ) == 0)
437         vik_viewport_set_ympp ( VIK_VIEWPORT(vp), strtod ( line+5, NULL ) );
438       else if ( stack->under == NULL && eq_pos == 3 && strncasecmp ( line, "lat", eq_pos ) == 0 )
439         ll.lat = strtod ( line+4, NULL );
440       else if ( stack->under == NULL && eq_pos == 3 && strncasecmp ( line, "lon", eq_pos ) == 0 )
441         ll.lon = strtod ( line+4, NULL );
442       else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "utm" ) == 0)
443         vik_viewport_set_drawmode ( VIK_VIEWPORT(vp), VIK_VIEWPORT_DRAWMODE_UTM);
444       else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "expedia" ) == 0)
445         vik_viewport_set_drawmode ( VIK_VIEWPORT(vp), VIK_VIEWPORT_DRAWMODE_EXPEDIA );
446       else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "google" ) == 0)
447       {
448         successful_read = FALSE;
449         g_warning ( _("Draw mode '%s' no more supported"), "google" );
450       }
451       else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "kh" ) == 0)
452       {
453         successful_read = FALSE;
454         g_warning ( _("Draw mode '%s' no more supported"), "kh" );
455       }
456       else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "mercator" ) == 0)
457         vik_viewport_set_drawmode ( VIK_VIEWPORT(vp), VIK_VIEWPORT_DRAWMODE_MERCATOR );
458       else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "latlon" ) == 0)
459         vik_viewport_set_drawmode ( VIK_VIEWPORT(vp), VIK_VIEWPORT_DRAWMODE_LATLON );
460       else if ( stack->under == NULL && eq_pos == 5 && strncasecmp ( line, "color", eq_pos ) == 0 )
461         vik_viewport_set_background_color ( VIK_VIEWPORT(vp), line+6 );
462       else if ( stack->under == NULL && eq_pos == 14 && strncasecmp ( line, "highlightcolor", eq_pos ) == 0 )
463         vik_viewport_set_highlight_color ( VIK_VIEWPORT(vp), line+15 );
464       else if ( stack->under == NULL && eq_pos == 9 && strncasecmp ( line, "drawscale", eq_pos ) == 0 )
465         vik_viewport_set_draw_scale ( VIK_VIEWPORT(vp), TEST_BOOLEAN(line+10) );
466       else if ( stack->under == NULL && eq_pos == 14 && strncasecmp ( line, "drawcentermark", eq_pos ) == 0 )
467         vik_viewport_set_draw_centermark ( VIK_VIEWPORT(vp), TEST_BOOLEAN(line+15) );
468       else if ( stack->under == NULL && eq_pos == 13 && strncasecmp ( line, "drawhighlight", eq_pos ) == 0 )
469         vik_viewport_set_draw_highlight ( VIK_VIEWPORT(vp), TEST_BOOLEAN(line+14) );
470       else if ( stack->under && eq_pos == 4 && strncasecmp ( line, "name", eq_pos ) == 0 )
471         vik_layer_rename ( VIK_LAYER(stack->data), line+5 );
472       else if ( eq_pos == 7 && strncasecmp ( line, "visible", eq_pos ) == 0 )
473         VIK_LAYER(stack->data)->visible = TEST_BOOLEAN(line+8);
474       else if ( eq_pos != -1 && stack->under )
475       {
476         gboolean found_match = FALSE;
477
478         /* go thru layer params. if len == eq_pos && starts_with jazz, set it. */
479         /* also got to check for name and visible. */
480
481         if ( ! params )
482         {
483           successful_read = FALSE;
484           g_warning ( "Line %ld: No options for this kind of layer", line_num );
485           continue;
486         }
487
488         for ( i = 0; i < params_count; i++ )
489           if ( strlen(params[i].name) == eq_pos && strncasecmp ( line, params[i].name, eq_pos ) == 0 )
490           {
491             VikLayerParamData x;
492             line += eq_pos+1;
493             if ( params[i].type == VIK_LAYER_PARAM_STRING_LIST ) {
494               GList *l = g_list_append ( g_hash_table_lookup ( string_lists, GINT_TO_POINTER ((gint) i) ), 
495                                          g_strdup(line) );
496               g_hash_table_replace ( string_lists, GINT_TO_POINTER ((gint)i), l );
497               /* add the value to a list, possibly making a new list.
498                * this will be passed to the layer when we read an ~EndLayer */
499             } else {
500               switch ( params[i].type )
501               {
502                 case VIK_LAYER_PARAM_DOUBLE: x.d = strtod(line, NULL); break;
503                 case VIK_LAYER_PARAM_UINT: x.u = strtoul(line, NULL, 10); break;
504                 case VIK_LAYER_PARAM_INT: x.i = strtol(line, NULL, 10); break;
505                 case VIK_LAYER_PARAM_BOOLEAN: x.b = TEST_BOOLEAN(line); break;
506                 case VIK_LAYER_PARAM_COLOR: memset(&(x.c), 0, sizeof(x.c)); /* default: black */
507                                           gdk_color_parse ( line, &(x.c) ); break;
508                 /* STRING or STRING_LIST -- if STRING_LIST, just set param to add a STRING */
509                 default: x.s = line;
510               }
511               vik_layer_set_param ( VIK_LAYER(stack->data), i, x, vp, TRUE );
512             }
513             found_match = TRUE;
514             break;
515           }
516         if ( ! found_match ) {
517           // ATM don't flow up this issue because at least one internal parameter has changed from version 1.3
518           //   and don't what to worry users about raising such issues
519           // TODO Maybe hold old values here - compare the line value against them and if a match
520           //       generate a different style of message in the GUI...
521           // successful_read = FALSE;
522           g_warning ( "Line %ld: Unknown parameter. Line:\n%s", line_num, line );
523         }
524       }
525       else {
526         successful_read = FALSE;
527         g_warning ( "Line %ld: Invalid parameter or parameter outside of layer.", line_num );
528       }
529     }
530 /* could be:
531 [Layer Type=Bla]
532 [EndLayer]
533 [LayerData]
534 name=this
535 #comment
536 */
537   }
538
539   while ( stack )
540   {
541     if ( stack->under && stack->under->data && stack->data )
542     {
543       vik_aggregate_layer_add_layer ( VIK_AGGREGATE_LAYER(stack->under->data), VIK_LAYER(stack->data), FALSE );
544       vik_layer_post_read ( VIK_LAYER(stack->data), vp, TRUE );
545     }
546     pop(&stack);
547   }
548
549   if ( ll.lat != 0.0 || ll.lon != 0.0 )
550     vik_viewport_set_center_latlon ( VIK_VIEWPORT(vp), &ll, TRUE );
551
552   if ( ( ! VIK_LAYER(top)->visible ) && VIK_LAYER(top)->realized )
553     vik_treeview_item_set_visible ( VIK_LAYER(top)->vt, &(VIK_LAYER(top)->iter), FALSE ); 
554
555   /* delete anything we've forgotten about -- should only happen when file ends before an EndLayer */
556   g_hash_table_foreach ( string_lists, string_list_delete, NULL );
557   g_hash_table_destroy ( string_lists );
558
559   return successful_read;
560 }
561
562 /*
563 read thru file
564 if "[Layer Type="
565   push(&stack)
566   new default layer of type (str_to_type) (check interface->name)
567 if "[EndLayer]"
568   VikLayer *vl = stack->data;
569   pop(&stack);
570   vik_aggregate_layer_add_layer(stack->data, vl);
571 if "[LayerData]"
572   vik_layer_data ( VIK_LAYER_DATA(stack->data), f, vp );
573
574 */
575
576 /* ---------------------------------------------------- */
577
578 static FILE *xfopen ( const char *fn )
579 {
580   if ( strcmp(fn,"-") == 0 )
581     return stdin;
582   else
583     return g_fopen(fn, "r");
584 }
585
586 static void xfclose ( FILE *f )
587 {
588   if ( f != stdin && f != stdout ) {
589     fclose ( f );
590     f = NULL;
591   }
592 }
593
594 /*
595  * Function to determine if a filename is a 'viking' type file
596  */
597 gboolean check_file_magic_vik ( const gchar *filename )
598 {
599   gboolean result = FALSE;
600   FILE *ff = xfopen ( filename );
601   if ( ff ) {
602     result = check_magic ( ff, VIK_MAGIC );
603     xfclose ( ff );
604   }
605   return result;
606 }
607
608 /**
609  * append_file_ext:
610  *
611  * Append a file extension, if not already present.
612  *
613  * Returns: a newly allocated string
614  */
615 gchar *append_file_ext ( const gchar *filename, VikFileType_t type )
616 {
617   gchar *new_name = NULL;
618   const gchar *ext = NULL;
619
620   /* Select an extension */
621   switch (type)
622   {
623   case FILE_TYPE_GPX:
624     ext = ".gpx";
625     break;
626   case FILE_TYPE_KML:
627     ext = ".kml";
628     break;
629   case FILE_TYPE_GPSMAPPER:
630   case FILE_TYPE_GPSPOINT:
631   default:
632     /* Do nothing, ext already set to NULL */
633     break;
634   }
635
636   /* Do */
637   if ( ext != NULL && ! a_file_check_ext ( filename, ext ) )
638     new_name = g_strconcat ( filename, ext, NULL );
639   else
640     /* Simply duplicate */
641     new_name = g_strdup ( filename );
642
643   return new_name;
644 }
645
646 VikLoadType_t a_file_load ( VikAggregateLayer *top, VikViewport *vp, const gchar *filename_or_uri )
647 {
648   g_return_val_if_fail ( vp != NULL, LOAD_TYPE_READ_FAILURE );
649
650   char *filename = (char *)filename_or_uri;
651   if (strncmp(filename, "file://", 7) == 0) {
652     // Consider replacing this with:
653     // filename = g_filename_from_uri ( entry, NULL, NULL );
654     // Since this doesn't support URIs properly (i.e. will failure if is it has %20 characters in it)
655     filename = filename + 7;
656     g_debug ( "Loading file %s from URI %s", filename, filename_or_uri );
657   }
658   FILE *f = xfopen ( filename );
659
660   if ( ! f )
661     return LOAD_TYPE_READ_FAILURE;
662
663   VikLoadType_t load_answer = LOAD_TYPE_OTHER_SUCCESS;
664
665   gchar *dirpath = g_path_get_dirname ( filename );
666   // Attempt loading the primary file type first - our internal .vik file:
667   if ( check_magic ( f, VIK_MAGIC ) )
668   {
669     if ( file_read ( top, f, dirpath, vp ) )
670       load_answer = LOAD_TYPE_VIK_SUCCESS;
671     else
672       load_answer = LOAD_TYPE_VIK_FAILURE_NON_FATAL;
673   }
674   else if ( a_jpg_magic_check ( filename ) ) {
675     if ( ! a_jpg_load_file ( top, filename, vp ) )
676       load_answer = LOAD_TYPE_UNSUPPORTED_FAILURE;
677   }
678   else
679   {
680         // For all other file types which consist of tracks, routes and/or waypoints,
681         //  must be loaded into a new TrackWaypoint layer (hence it be created)
682     gboolean success = TRUE; // Detect load failures - mainly to remove the layer created as it's not required
683
684     VikLayer *vtl = vik_layer_create ( VIK_LAYER_TRW, vp, FALSE );
685     vik_layer_rename ( vtl, a_file_basename ( filename ) );
686
687     // In fact both kml & gpx files start the same as they are in xml
688     if ( a_file_check_ext ( filename, ".kml" ) && check_magic ( f, GPX_MAGIC ) ) {
689       // Implicit Conversion
690       if ( ! ( success = a_babel_convert_from ( VIK_TRW_LAYER(vtl), "-i kml", filename, NULL, NULL, NULL ) ) ) {
691         load_answer = LOAD_TYPE_GPSBABEL_FAILURE;
692       }
693     }
694     // NB use a extension check first, as a GPX file header may have a Byte Order Mark (BOM) in it
695     //    - which currently confuses our check_magic function
696     else if ( a_file_check_ext ( filename, ".gpx" ) || check_magic ( f, GPX_MAGIC ) ) {
697       if ( ! ( success = a_gpx_read_file ( VIK_TRW_LAYER(vtl), f ) ) ) {
698         load_answer = LOAD_TYPE_GPX_FAILURE;
699       }
700     }
701     else {
702       // Try final supported file type
703       if ( ! ( success = a_gpspoint_read_file ( VIK_TRW_LAYER(vtl), f, dirpath ) ) ) {
704         // Failure here means we don't know how to handle the file
705         load_answer = LOAD_TYPE_UNSUPPORTED_FAILURE;
706       }
707     }
708     g_free ( dirpath );
709
710     // Clean up when we can't handle the file
711     if ( ! success ) {
712       // free up layer
713       g_object_unref ( vtl );
714     }
715     else {
716       // Complete the setup from the successful load
717       vik_layer_post_read ( vtl, vp, TRUE );
718       vik_aggregate_layer_add_layer ( top, vtl, FALSE );
719       vik_trw_layer_auto_set_view ( VIK_TRW_LAYER(vtl), vp );
720     }
721   }
722   xfclose(f);
723   return load_answer;
724 }
725
726 gboolean a_file_save ( VikAggregateLayer *top, gpointer vp, const gchar *filename )
727 {
728   FILE *f;
729
730   if (strncmp(filename, "file://", 7) == 0)
731     filename = filename + 7;
732
733   f = g_fopen(filename, "w");
734
735   if ( ! f )
736     return FALSE;
737
738   // Enable relative paths in .vik files to work
739   gchar *cwd = g_get_current_dir();
740   gchar *dir = g_path_get_dirname ( filename );
741   if ( dir ) {
742     if ( g_chdir ( dir ) ) {
743       g_warning ( "Could not change directory to %s", dir );
744     }
745     g_free (dir);
746   }
747
748   file_write ( top, f, vp );
749
750   // Restore previous working directory
751   if ( cwd ) {
752     if ( g_chdir ( cwd ) ) {
753       g_warning ( "Could not return to directory %s", cwd );
754     }
755     g_free (cwd);
756   }
757
758   fclose(f);
759   f = NULL;
760
761   return TRUE;
762 }
763
764
765 /* example: 
766      gboolean is_gpx = a_file_check_ext ( "a/b/c.gpx", ".gpx" );
767 */
768 gboolean a_file_check_ext ( const gchar *filename, const gchar *fileext )
769 {
770   g_return_val_if_fail ( filename != NULL, FALSE );
771   g_return_val_if_fail ( fileext && fileext[0]=='.', FALSE );
772   const gchar *basename = a_file_basename(filename);
773   if (!basename)
774     return FALSE;
775
776   const char * dot = strrchr(basename, '.');
777   if (dot && !strcmp(dot, fileext))
778     return TRUE;
779
780   return FALSE;
781 }
782
783 /**
784  * a_file_export:
785  * @vtl: The TrackWaypoint to export data from
786  * @filename: The name of the file to be written
787  * @file_type: Choose one of the supported file types for the export
788  * @trk: If specified then only export this track rather than the whole layer
789  * @write_hidden: Whether to write invisible items
790  *
791  * A general export command to convert from Viking TRW layer data to an external supported format.
792  * The write_hidden option is provided mainly to be able to transfer selected items when uploading to a GPS
793  */
794 gboolean a_file_export ( VikTrwLayer *vtl, const gchar *filename, VikFileType_t file_type, VikTrack *trk, gboolean write_hidden )
795 {
796   GpxWritingOptions options = { FALSE, FALSE, write_hidden, FALSE };
797   FILE *f = g_fopen ( filename, "w" );
798   if ( f )
799   {
800     if ( trk ) {
801       switch ( file_type ) {
802         case FILE_TYPE_GPX:
803           // trk defined so can set the option
804           options.is_route = trk->is_route;
805           a_gpx_write_track_file ( trk, f, &options );
806           break;
807         default:
808           g_critical("Houston, we've had a problem. file_type=%d", file_type);
809       }
810     } else {
811       switch ( file_type ) {
812         case FILE_TYPE_GPSMAPPER:
813           a_gpsmapper_write_file ( vtl, f );
814           break;
815         case FILE_TYPE_GPX:
816           a_gpx_write_file ( vtl, f, &options );
817           break;
818         case FILE_TYPE_GPSPOINT:
819           a_gpspoint_write_file ( vtl, f );
820           break;
821         case FILE_TYPE_KML:
822           fclose ( f );
823           f = NULL;
824           switch ( a_vik_get_kml_export_units () ) {
825             case VIK_KML_EXPORT_UNITS_STATUTE:
826               return a_babel_convert_to ( vtl, NULL, "-o kml", filename, NULL, NULL );
827               break;
828             case VIK_KML_EXPORT_UNITS_NAUTICAL:
829               return a_babel_convert_to ( vtl, NULL, "-o kml,units=n", filename, NULL, NULL );
830               break;
831             default:
832               // VIK_KML_EXPORT_UNITS_METRIC:
833               return a_babel_convert_to ( vtl, NULL, "-o kml,units=m", filename, NULL, NULL );
834               break;
835           }
836           break;
837         default:
838           g_critical("Houston, we've had a problem. file_type=%d", file_type);
839       }
840     }
841     fclose ( f );
842     f = NULL;
843     return TRUE;
844   }
845   return FALSE;
846 }
847
848 /**
849  * a_file_export_babel:
850  */
851 gboolean a_file_export_babel ( VikTrwLayer *vtl, const gchar *filename, const gchar *format,
852                                gboolean tracks, gboolean routes, gboolean waypoints )
853 {
854   gchar *args = g_strdup_printf("%s %s %s -o %s",
855                                 tracks ? "-t" : "",
856                                 routes ? "-r" : "",
857                                 waypoints ? "-w" : "",
858                                 format);
859   gboolean result = a_babel_convert_to ( vtl, NULL, args, filename, NULL, NULL );
860   g_free(args);
861   return result;
862 }
863
864 /**
865  * Just a wrapper around realpath, which itself is platform dependent
866  */
867 char *file_realpath ( const char *path, char *real )
868 {
869   return realpath ( path, real );
870 }
871
872 #ifndef MAXPATHLEN
873 #define MAXPATHLEN 1024
874 #endif
875 /**
876  * Always return the canonical filename in a newly allocated string
877  */
878 char *file_realpath_dup ( const char *path )
879 {
880         char real[MAXPATHLEN];
881
882         g_return_val_if_fail(path != NULL, NULL);
883
884         if (file_realpath(path, real))
885                 return g_strdup(real);
886
887         return g_strdup(path);
888 }
889
890 /**
891  * Permission granted to use this code after personal correspondance
892  * Slightly reworked for better cross platform use, glibisms, function rename and a compacter format
893  *
894  * FROM http://www.codeguru.com/cpp/misc/misc/fileanddirectorynaming/article.php/c263
895  */
896
897 // GetRelativeFilename(), by Rob Fisher.
898 // rfisher@iee.org
899 // http://come.to/robfisher
900
901 // The number of characters at the start of an absolute filename.  e.g. in DOS,
902 // absolute filenames start with "X:\" so this value should be 3, in UNIX they start
903 // with "\" so this value should be 1.
904 #ifdef WINDOWS
905 #define ABSOLUTE_NAME_START 3
906 #else
907 #define ABSOLUTE_NAME_START 1
908 #endif
909
910 // Given the absolute current directory and an absolute file name, returns a relative file name.
911 // For example, if the current directory is C:\foo\bar and the filename C:\foo\whee\text.txt is given,
912 // GetRelativeFilename will return ..\whee\text.txt.
913
914 const gchar *file_GetRelativeFilename ( gchar *currentDirectory, gchar *absoluteFilename )
915 {
916   gint afMarker = 0, rfMarker = 0;
917   gint cdLen = 0, afLen = 0;
918   gint i = 0;
919   gint levels = 0;
920   static gchar relativeFilename[MAXPATHLEN+1];
921
922   cdLen = strlen(currentDirectory);
923   afLen = strlen(absoluteFilename);
924
925   // make sure the names are not too long or too short
926   if (cdLen > MAXPATHLEN || cdLen < ABSOLUTE_NAME_START+1 ||
927       afLen > MAXPATHLEN || afLen < ABSOLUTE_NAME_START+1) {
928     return NULL;
929   }
930
931   // Handle DOS names that are on different drives:
932   if (currentDirectory[0] != absoluteFilename[0]) {
933     // not on the same drive, so only absolute filename will do
934     strcpy(relativeFilename, absoluteFilename);
935     return relativeFilename;
936   }
937
938   // they are on the same drive, find out how much of the current directory
939   // is in the absolute filename
940   i = ABSOLUTE_NAME_START;
941   while (i < afLen && i < cdLen && currentDirectory[i] == absoluteFilename[i]) {
942     i++;
943   }
944
945   if (i == cdLen && (absoluteFilename[i] == G_DIR_SEPARATOR || absoluteFilename[i-1] == G_DIR_SEPARATOR)) {
946     // the whole current directory name is in the file name,
947     // so we just trim off the current directory name to get the
948     // current file name.
949     if (absoluteFilename[i] == G_DIR_SEPARATOR) {
950       // a directory name might have a trailing slash but a relative
951       // file name should not have a leading one...
952       i++;
953     }
954
955     strcpy(relativeFilename, &absoluteFilename[i]);
956     return relativeFilename;
957   }
958
959   // The file is not in a child directory of the current directory, so we
960   // need to step back the appropriate number of parent directories by
961   // using "..\"s.  First find out how many levels deeper we are than the
962   // common directory
963   afMarker = i;
964   levels = 1;
965
966   // count the number of directory levels we have to go up to get to the
967   // common directory
968   while (i < cdLen) {
969     i++;
970     if (currentDirectory[i] == G_DIR_SEPARATOR) {
971       // make sure it's not a trailing slash
972       i++;
973       if (currentDirectory[i] != '\0') {
974         levels++;
975       }
976     }
977   }
978
979   // move the absolute filename marker back to the start of the directory name
980   // that it has stopped in.
981   while (afMarker > 0 && absoluteFilename[afMarker-1] != G_DIR_SEPARATOR) {
982     afMarker--;
983   }
984
985   // check that the result will not be too long
986   if (levels * 3 + afLen - afMarker > MAXPATHLEN) {
987     return NULL;
988   }
989
990   // add the appropriate number of "..\"s.
991   rfMarker = 0;
992   for (i = 0; i < levels; i++) {
993     relativeFilename[rfMarker++] = '.';
994     relativeFilename[rfMarker++] = '.';
995     relativeFilename[rfMarker++] = G_DIR_SEPARATOR;
996   }
997
998   // copy the rest of the filename into the result string
999   strcpy(&relativeFilename[rfMarker], &absoluteFilename[afMarker]);
1000
1001   return relativeFilename;
1002 }
1003 /* END http://www.codeguru.com/cpp/misc/misc/fileanddirectorynaming/article.php/c263 */