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