]> git.street.me.uk Git - andy/viking.git/blame - src/file.c
Some spelling fixes in a comment
[andy/viking.git] / src / file.c
CommitLineData
50a14534
EB
1/*
2 * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
3 *
4 * Copyright (C) 2003-2005, Evan Battaglia <gtoevan@gmx.net>
29f1598c 5 * Copyright (C) 2012, Guilhem Bonnefille <guilhem.bonnefille@gmail.com>
1b14d0d2 6 * Copyright (C) 2012-2013, Rob Norris <rw_norris@hotmail.com>
50a14534
EB
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
eb93fa95
GB
24#ifdef HAVE_CONFIG_H
25#include "config.h"
26#endif
50a14534
EB
27#include "viking.h"
28
5bed0ef6 29#include "jpg.h"
bf35388d 30#include "gpx.h"
1ca082d7 31#include "geojson.h"
ba9d0a00 32#include "babel.h"
113c9b1b 33#include "gpsmapper.h"
bf35388d 34
50a14534
EB
35#include <string.h>
36#include <stdlib.h>
8c060406 37#include <stdio.h>
45acf79e
MA
38#ifdef HAVE_UNISTD_H
39#include <unistd.h>
40#endif
d5728c65
GB
41#include <glib.h>
42#include <glib/gstdio.h>
fd98b156 43#include <glib/gi18n.h>
50a14534 44
694b6d08 45#include "file.h"
81687a73 46#include "misc/strtod.h"
694b6d08 47
50a14534
EB
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"
bf35388d 50#define GPX_MAGIC "<?xm"
50a14534 51#define VIK_MAGIC_LEN 4
f8ecf9c2 52#define GPX_MAGIC_LEN 4
50a14534 53
e087b0d9
RN
54#define VIKING_FILE_VERSION 1
55
50a14534
EB
56typedef struct _Stack Stack;
57
58struct _Stack {
59 Stack *under;
ab8c8dbf 60 gpointer data;
50a14534
EB
61};
62
63static void pop(Stack **stack) {
64 Stack *tmp = (*stack)->under;
65 g_free ( *stack );
66 *stack = tmp;
67}
68
69static void push(Stack **stack)
70{
71 Stack *tmp = g_malloc ( sizeof ( Stack ) );
72 tmp->under = *stack;
73 *stack = tmp;
74}
75
f8ecf9c2 76static gboolean check_magic ( FILE *f, const gchar *magic_number, guint magic_length )
50a14534 77{
f8ecf9c2 78 gchar magic[magic_length];
50a14534
EB
79 gboolean rv = FALSE;
80 gint8 i;
81 if ( fread(magic, 1, sizeof(magic), f) == sizeof(magic) &&
bf35388d 82 strncmp(magic, magic_number, sizeof(magic)) == 0 )
50a14534
EB
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
90static 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
b5926b35 97void file_write_layer_param ( FILE *f, const gchar *name, VikLayerParamType type, VikLayerParamData data ) {
ad0a8c2d
EB
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,
17a1f8f9 101 * not an empty string list.
ad0a8c2d 102 */
17a1f8f9 103 if ( type == VIK_LAYER_PARAM_STRING_LIST ) {
ad0a8c2d
EB
104 if ( data.sl ) {
105 GList *iter = (GList *)data.sl;
106 while ( iter ) {
17a1f8f9 107 fprintf ( f, "%s=", name );
ad0a8c2d
EB
108 fprintf ( f, "%s\n", (gchar *)(iter->data) );
109 iter = iter->next;
110 }
111 }
112 } else {
17a1f8f9
EB
113 fprintf ( f, "%s=", name );
114 switch ( type )
ad0a8c2d
EB
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;
fd74cdb9 125 case VIK_LAYER_PARAM_STRING: fprintf ( f, "%s\n", data.s ? data.s : "" ); break;
ad0a8c2d 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;
b5926b35 127 default: break;
ad0a8c2d 128 }
50a14534 129 }
17a1f8f9
EB
130}
131
8a439f31 132static void write_layer_params_and_data ( VikLayer *l, FILE *f, const gchar *dirpath )
17a1f8f9
EB
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 {
158b3642 147 data = get_param(l, i, TRUE);
17a1f8f9 148 file_write_layer_param(f, params[i].name, params[i].type, data);
50a14534
EB
149 }
150 }
151 if ( vik_layer_get_interface(l->type)->write_file_data )
152 {
153 fprintf ( f, "\n\n~LayerData\n" );
8a439f31 154 vik_layer_get_interface(l->type)->write_file_data ( l, f, dirpath );
50a14534
EB
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
8a439f31 163static void file_write ( VikAggregateLayer *top, FILE *f, gpointer vp, const gchar *dirpath )
50a14534
EB
164{
165 Stack *stack = NULL;
166 VikLayer *current_layer;
167 struct LatLon ll;
c5f9245d 168 VikViewportDrawMode mode;
4d872dde 169 gchar *modestring = NULL;
50a14534
EB
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
c5f9245d
GB
178 mode = vik_viewport_get_drawmode ( VIK_VIEWPORT(vp) );
179 switch ( mode ) {
50a14534
EB
180 case VIK_VIEWPORT_DRAWMODE_UTM: modestring = "utm"; break;
181 case VIK_VIEWPORT_DRAWMODE_EXPEDIA: modestring = "expedia"; break;
c5f9245d 182 case VIK_VIEWPORT_DRAWMODE_MERCATOR: modestring = "mercator"; break;
d587678a 183 case VIK_VIEWPORT_DRAWMODE_LATLON: modestring = "latlon"; break;
c5f9245d
GB
184 default:
185 g_critical("Houston, we've had a problem. mode=%d", mode);
50a14534
EB
186 }
187
e087b0d9
RN
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",
50a14534 191 vik_viewport_get_xmpp ( VIK_VIEWPORT(vp) ), vik_viewport_get_ympp ( VIK_VIEWPORT(vp) ), ll.lat, ll.lon,
35c7c0ba 192 modestring, vik_viewport_get_background_color(VIK_VIEWPORT(vp)),
480fb7e1 193 vik_viewport_get_highlight_color(VIK_VIEWPORT(vp)),
c933487f 194 vik_viewport_get_draw_scale(VIK_VIEWPORT(vp)) ? "t" : "f",
2afcef36
RN
195 vik_viewport_get_draw_centermark(VIK_VIEWPORT(vp)) ? "t" : "f",
196 vik_viewport_get_draw_highlight(VIK_VIEWPORT(vp)) ? "t" : "f" );
50a14534
EB
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);
db386630 204 fprintf ( f, "\n~Layer %s\n", vik_layer_get_interface(current_layer->type)->fixed_layer_name );
8a439f31 205 write_layer_params_and_data ( current_layer, f, dirpath );
50a14534
EB
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 }
f253a6a6 211 else if ( current_layer->type == VIK_LAYER_GPS && !vik_gps_layer_is_empty(VIK_GPS_LAYER(current_layer)) )
7886de28
QT
212 {
213 push(&stack);
214 stack->data = (gpointer) vik_gps_layer_get_children(VIK_GPS_LAYER(current_layer));
215 }
50a14534
EB
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
ad0a8c2d
EB
244static void string_list_delete ( gpointer key, gpointer l, gpointer user_data )
245{
28c82d8b
EB
246 /* 20071021 bugfix */
247 GList *iter = (GList *) l;
ad0a8c2d
EB
248 while ( iter ) {
249 g_free ( iter->data );
250 iter = iter->next;
251 }
28c82d8b 252 g_list_free ( (GList *) l );
ad0a8c2d
EB
253}
254
255static void string_list_set_param (gint i, GList *list, gpointer *layer_and_vp)
256{
d7a77674
RN
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;
b6db1dc4 262 vlsp.dirpath = (const gchar*)layer_and_vp[2];
d7a77674
RN
263
264 vik_layer_set_param ( VIK_LAYER(layer_and_vp[0]), &vlsp );
ad0a8c2d
EB
265}
266
327a2533
RN
267/**
268 * Read in a Viking file and return how successful the parsing was
269 * ATM this will always work, in that even if there are parsing problems
270 * then there will be no new values to override the defaults
271 *
272 * TODO flow up line number(s) / error messages of problems encountered...
273 *
274 */
1b14d0d2 275static gboolean file_read ( VikAggregateLayer *top, FILE *f, const gchar *dirpath, VikViewport *vp )
50a14534 276{
d99f5da9 277 Stack *stack = NULL;
50a14534
EB
278 struct LatLon ll = { 0.0, 0.0 };
279 gchar buffer[4096];
280 gchar *line;
281 guint16 len;
282 long line_num = 0;
283
37518034
QT
284 VikLayerParam *params = NULL; /* for current layer, so we don't have to keep on looking up interface */
285 guint8 params_count = 0;
50a14534 286
ad0a8c2d
EB
287 GHashTable *string_lists = g_hash_table_new(g_direct_hash,g_direct_equal);
288
327a2533
RN
289 gboolean successful_read = TRUE;
290
50a14534
EB
291 push(&stack);
292 stack->under = NULL;
293 stack->data = (gpointer) top;
294
295 while ( fgets ( buffer, 4096, f ) )
296 {
297 line_num++;
298
299 line = buffer;
300 while ( *line == ' ' || *line =='\t' )
301 line++;
302
303 if ( line[0] == '#' )
304 continue;
305
306
307 len = strlen(line);
308 if ( len > 0 && line[len-1] == '\n' )
309 line[--len] = '\0';
310 if ( len > 0 && line[len-1] == '\r' )
311 line[--len] = '\0';
312
313 if ( len == 0 )
314 continue;
315
316
317 if ( line[0] == '~' )
318 {
319 line++; len--;
320 if ( *line == '\0' )
321 continue;
322 else if ( str_starts_with ( line, "Layer ", 6, TRUE ) )
323 {
f253a6a6
QT
324 int parent_type = VIK_LAYER(stack->data)->type;
325 if ( ( ! stack->data ) || ((parent_type != VIK_LAYER_AGGREGATE) && (parent_type != VIK_LAYER_GPS)) )
50a14534 326 {
327a2533 327 successful_read = FALSE;
f253a6a6 328 g_warning ( "Line %ld: Layer command inside non-Aggregate Layer (type %d)", line_num, parent_type );
50a14534
EB
329 push(&stack); /* inside INVALID layer */
330 stack->data = NULL;
331 continue;
332 }
333 else
334 {
44b84795 335 VikLayerTypeEnum type = vik_layer_type_from_string ( line+6 );
50a14534 336 push(&stack);
b5926b35 337 if ( type == VIK_LAYER_NUM_TYPES )
50a14534 338 {
327a2533 339 successful_read = FALSE;
4258f4e2 340 g_warning ( "Line %ld: Unknown type %s", line_num, line+6 );
50a14534
EB
341 stack->data = NULL;
342 }
f253a6a6
QT
343 else if (parent_type == VIK_LAYER_GPS)
344 {
345 stack->data = (gpointer) vik_gps_layer_get_a_child(VIK_GPS_LAYER(stack->under->data));
346 params = vik_layer_get_interface(type)->params;
347 params_count = vik_layer_get_interface(type)->params_count;
348 }
50a14534
EB
349 else
350 {
0ab35525 351 stack->data = (gpointer) vik_layer_create ( type, vp, FALSE );
50a14534
EB
352 params = vik_layer_get_interface(type)->params;
353 params_count = vik_layer_get_interface(type)->params_count;
354 }
355 }
356 }
357 else if ( str_starts_with ( line, "EndLayer", 8, FALSE ) )
358 {
327a2533
RN
359 if ( stack->under == NULL ) {
360 successful_read = FALSE;
50a14534 361 g_warning ( "Line %ld: Mismatched ~EndLayer command", line_num );
327a2533 362 }
50a14534
EB
363 else
364 {
ad0a8c2d 365 /* add any string lists we've accumulated */
d7a77674 366 gpointer layer_and_vp[3];
ad0a8c2d
EB
367 layer_and_vp[0] = stack->data;
368 layer_and_vp[1] = vp;
d7a77674 369 layer_and_vp[2] = (gpointer)dirpath;
ad0a8c2d
EB
370 g_hash_table_foreach ( string_lists, (GHFunc) string_list_set_param, layer_and_vp );
371 g_hash_table_remove_all ( string_lists );
372
50a14534
EB
373 if ( stack->data && stack->under->data )
374 {
f253a6a6 375 if (VIK_LAYER(stack->under->data)->type == VIK_LAYER_AGGREGATE) {
c3a02429 376 vik_aggregate_layer_add_layer ( VIK_AGGREGATE_LAYER(stack->under->data), VIK_LAYER(stack->data), FALSE );
dcb51e52 377 vik_layer_post_read ( VIK_LAYER(stack->data), vp, TRUE );
f253a6a6
QT
378 }
379 else if (VIK_LAYER(stack->under->data)->type == VIK_LAYER_GPS) {
380 /* TODO: anything else needs to be done here ? */
381 }
327a2533
RN
382 else {
383 successful_read = FALSE;
f253a6a6 384 g_warning ( "Line %ld: EndLayer command inside non-Aggregate Layer (type %d)", line_num, VIK_LAYER(stack->data)->type );
327a2533 385 }
50a14534
EB
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 )
119ada4c 393 {
50a14534 394 /* must read until hits ~EndLayerData */
1b14d0d2 395 if ( ! vik_layer_get_interface(VIK_LAYER(stack->data)->type)->read_file_data ( VIK_LAYER(stack->data), f, dirpath ) )
119ada4c
RN
396 successful_read = FALSE;
397 }
50a14534
EB
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 {
327a2533 419 successful_read = FALSE;
50a14534
EB
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
e087b0d9
RN
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 */
81687a73 442 vik_viewport_set_xmpp ( VIK_VIEWPORT(vp), strtod_i8n ( line+5, NULL ) );
50a14534 443 else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "ympp", eq_pos ) == 0)
81687a73 444 vik_viewport_set_ympp ( VIK_VIEWPORT(vp), strtod_i8n ( line+5, NULL ) );
50a14534 445 else if ( stack->under == NULL && eq_pos == 3 && strncasecmp ( line, "lat", eq_pos ) == 0 )
81687a73 446 ll.lat = strtod_i8n ( line+4, NULL );
50a14534 447 else if ( stack->under == NULL && eq_pos == 3 && strncasecmp ( line, "lon", eq_pos ) == 0 )
81687a73 448 ll.lon = strtod_i8n ( line+4, NULL );
50a14534
EB
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)
fd98b156 454 {
327a2533 455 successful_read = FALSE;
fd98b156
GB
456 g_warning ( _("Draw mode '%s' no more supported"), "google" );
457 }
50a14534 458 else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "kh" ) == 0)
fd98b156 459 {
327a2533 460 successful_read = FALSE;
fd98b156
GB
461 g_warning ( _("Draw mode '%s' no more supported"), "kh" );
462 }
50a14534
EB
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 );
d587678a
GB
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 );
50a14534
EB
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 );
480fb7e1
RN
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 );
35c7c0ba
EB
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) );
de66b263 473 else if ( stack->under == NULL && eq_pos == 14 && strncasecmp ( line, "drawcentermark", eq_pos ) == 0 )
1657065a 474 vik_viewport_set_draw_centermark ( VIK_VIEWPORT(vp), TEST_BOOLEAN(line+15) );
2afcef36
RN
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) );
50a14534
EB
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;
ad0a8c2d 484
50a14534
EB
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 {
327a2533 490 successful_read = FALSE;
50a14534
EB
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;
ad0a8c2d 500 if ( params[i].type == VIK_LAYER_PARAM_STRING_LIST ) {
dc2c040e
RN
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 );
ad0a8c2d
EB
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 {
81687a73 509 case VIK_LAYER_PARAM_DOUBLE: x.d = strtod_i8n(line, NULL); break;
ad0a8c2d
EB
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 */
50a14534 514 gdk_color_parse ( line, &(x.c) ); break;
ad0a8c2d
EB
515 /* STRING or STRING_LIST -- if STRING_LIST, just set param to add a STRING */
516 default: x.s = line;
517 }
d7a77674
RN
518
519 VikLayerSetParam vlsp;
520 vlsp.id = i;
521 vlsp.data = x;
522 vlsp.vp = vp;
523 vlsp.is_file_operation = TRUE;
b6db1dc4 524 vlsp.dirpath = dirpath;
d7a77674 525 vik_layer_set_param ( VIK_LAYER(stack->data), &vlsp );
50a14534 526 }
50a14534
EB
527 found_match = TRUE;
528 break;
529 }
327a2533
RN
530 if ( ! found_match ) {
531 // ATM don't flow up this issue because at least one internal parameter has changed from version 1.3
532 // and don't what to worry users about raising such issues
533 // TODO Maybe hold old values here - compare the line value against them and if a match
534 // generate a different style of message in the GUI...
535 // successful_read = FALSE;
ea3933fc 536 g_warning ( "Line %ld: Unknown parameter. Line:\n%s", line_num, line );
327a2533 537 }
50a14534 538 }
327a2533
RN
539 else {
540 successful_read = FALSE;
50a14534 541 g_warning ( "Line %ld: Invalid parameter or parameter outside of layer.", line_num );
327a2533 542 }
50a14534
EB
543 }
544/* could be:
545[Layer Type=Bla]
546[EndLayer]
547[LayerData]
548name=this
549#comment
550*/
551 }
552
553 while ( stack )
554 {
555 if ( stack->under && stack->under->data && stack->data )
556 {
c3a02429 557 vik_aggregate_layer_add_layer ( VIK_AGGREGATE_LAYER(stack->under->data), VIK_LAYER(stack->data), FALSE );
dcb51e52 558 vik_layer_post_read ( VIK_LAYER(stack->data), vp, TRUE );
50a14534
EB
559 }
560 pop(&stack);
561 }
562
563 if ( ll.lat != 0.0 || ll.lon != 0.0 )
be5554c5 564 vik_viewport_set_center_latlon ( VIK_VIEWPORT(vp), &ll, TRUE );
50a14534
EB
565
566 if ( ( ! VIK_LAYER(top)->visible ) && VIK_LAYER(top)->realized )
567 vik_treeview_item_set_visible ( VIK_LAYER(top)->vt, &(VIK_LAYER(top)->iter), FALSE );
ad0a8c2d
EB
568
569 /* delete anything we've forgotten about -- should only happen when file ends before an EndLayer */
570 g_hash_table_foreach ( string_lists, string_list_delete, NULL );
571 g_hash_table_destroy ( string_lists );
327a2533
RN
572
573 return successful_read;
50a14534
EB
574}
575
576/*
577read thru file
578if "[Layer Type="
579 push(&stack)
580 new default layer of type (str_to_type) (check interface->name)
581if "[EndLayer]"
582 VikLayer *vl = stack->data;
583 pop(&stack);
584 vik_aggregate_layer_add_layer(stack->data, vl);
585if "[LayerData]"
586 vik_layer_data ( VIK_LAYER_DATA(stack->data), f, vp );
587
588*/
589
590/* ---------------------------------------------------- */
591
0ba6e0b9 592static FILE *xfopen ( const char *fn )
50a14534
EB
593{
594 if ( strcmp(fn,"-") == 0 )
595 return stdin;
596 else
8c060406 597 return g_fopen(fn, "r");
50a14534
EB
598}
599
600static void xfclose ( FILE *f )
601{
8c060406 602 if ( f != stdin && f != stdout ) {
50a14534 603 fclose ( f );
8c060406
MA
604 f = NULL;
605 }
50a14534
EB
606}
607
ba9d0a00
RN
608/*
609 * Function to determine if a filename is a 'viking' type file
610 */
611gboolean check_file_magic_vik ( const gchar *filename )
612{
a3180051 613 gboolean result = FALSE;
0ba6e0b9 614 FILE *ff = xfopen ( filename );
a3180051 615 if ( ff ) {
f8ecf9c2 616 result = check_magic ( ff, VIK_MAGIC, VIK_MAGIC_LEN );
a3180051
RN
617 xfclose ( ff );
618 }
ba9d0a00
RN
619 return result;
620}
621
e4a11fbe
GB
622/**
623 * append_file_ext:
624 *
625 * Append a file extension, if not already present.
626 *
627 * Returns: a newly allocated string
628 */
bb3c38af 629gchar *append_file_ext ( const gchar *filename, VikFileType_t type )
e4a11fbe
GB
630{
631 gchar *new_name = NULL;
632 const gchar *ext = NULL;
633
634 /* Select an extension */
635 switch (type)
636 {
637 case FILE_TYPE_GPX:
638 ext = ".gpx";
639 break;
640 case FILE_TYPE_KML:
641 ext = ".kml";
642 break;
1ca082d7
RN
643 case FILE_TYPE_GEOJSON:
644 ext = ".geojson";
645 break;
e4a11fbe
GB
646 case FILE_TYPE_GPSMAPPER:
647 case FILE_TYPE_GPSPOINT:
648 default:
649 /* Do nothing, ext already set to NULL */
650 break;
651 }
652
653 /* Do */
140d0d67 654 if ( ext != NULL && ! a_file_check_ext ( filename, ext ) )
e4a11fbe
GB
655 new_name = g_strconcat ( filename, ext, NULL );
656 else
657 /* Simply duplicate */
658 new_name = g_strdup ( filename );
659
660 return new_name;
661}
662
718696d6 663VikLoadType_t a_file_load ( VikAggregateLayer *top, VikViewport *vp, VikTrwLayer *vtl, const gchar *filename_or_uri )
50a14534 664{
0a514451
RN
665 g_return_val_if_fail ( vp != NULL, LOAD_TYPE_READ_FAILURE );
666
11f427b8 667 char *filename = (char *)filename_or_uri;
df390922 668 if (strncmp(filename, "file://", 7) == 0) {
07c78458
RN
669 // Consider replacing this with:
670 // filename = g_filename_from_uri ( entry, NULL, NULL );
671 // Since this doesn't support URIs properly (i.e. will failure if is it has %20 characters in it)
db32b809 672 filename = filename + 7;
df390922
RN
673 g_debug ( "Loading file %s from URI %s", filename, filename_or_uri );
674 }
0ba6e0b9 675 FILE *f = xfopen ( filename );
50a14534 676
50a14534 677 if ( ! f )
ba9d0a00 678 return LOAD_TYPE_READ_FAILURE;
50a14534 679
327a2533 680 VikLoadType_t load_answer = LOAD_TYPE_OTHER_SUCCESS;
0a514451 681
8a439f31
RN
682 gchar *absolute = file_realpath_dup ( filename );
683 gchar *dirpath = NULL;
684 if ( absolute )
685 dirpath = g_path_get_dirname ( absolute );
686 g_free ( absolute );
687
0a514451 688 // Attempt loading the primary file type first - our internal .vik file:
f8ecf9c2 689 if ( check_magic ( f, VIK_MAGIC, VIK_MAGIC_LEN ) )
50a14534 690 {
1b14d0d2 691 if ( file_read ( top, f, dirpath, vp ) )
327a2533
RN
692 load_answer = LOAD_TYPE_VIK_SUCCESS;
693 else
694 load_answer = LOAD_TYPE_VIK_FAILURE_NON_FATAL;
50a14534 695 }
5bed0ef6
RN
696 else if ( a_jpg_magic_check ( filename ) ) {
697 if ( ! a_jpg_load_file ( top, filename, vp ) )
698 load_answer = LOAD_TYPE_UNSUPPORTED_FAILURE;
699 }
50a14534
EB
700 else
701 {
0a514451
RN
702 // For all other file types which consist of tracks, routes and/or waypoints,
703 // must be loaded into a new TrackWaypoint layer (hence it be created)
704 gboolean success = TRUE; // Detect load failures - mainly to remove the layer created as it's not required
705
718696d6 706 // Add to specified layer
707 gboolean add_new = !IS_VIK_TRW_LAYER(vtl);
708 if (add_new) {
3f350544
RN
709 vtl = VIK_TRW_LAYER (vik_layer_create ( VIK_LAYER_TRW, vp, FALSE ));
710 vik_layer_rename ( VIK_LAYER(vtl), a_file_basename ( filename ) );
718696d6 711 }
bf35388d 712
ba9d0a00 713 // In fact both kml & gpx files start the same as they are in xml
f8ecf9c2 714 if ( a_file_check_ext ( filename, ".kml" ) && check_magic ( f, GPX_MAGIC, GPX_MAGIC_LEN ) ) {
ba9d0a00 715 // Implicit Conversion
17acdaec 716 ProcessOptions po = { "-i kml", filename, NULL, NULL, NULL, NULL };
3f350544 717 if ( ! ( success = a_babel_convert_from ( vtl, &po, NULL, NULL, NULL ) ) ) {
0a514451 718 load_answer = LOAD_TYPE_GPSBABEL_FAILURE;
ba9d0a00
RN
719 }
720 }
0a514451
RN
721 // NB use a extension check first, as a GPX file header may have a Byte Order Mark (BOM) in it
722 // - which currently confuses our check_magic function
f8ecf9c2 723 else if ( a_file_check_ext ( filename, ".gpx" ) || check_magic ( f, GPX_MAGIC, GPX_MAGIC_LEN ) ) {
8a439f31 724 if ( ! ( success = a_gpx_read_file ( vtl, f, dirpath ) ) ) {
0a514451 725 load_answer = LOAD_TYPE_GPX_FAILURE;
54b84792 726 }
ba9d0a00 727 }
0a514451
RN
728 else {
729 // Try final supported file type
3f350544 730 if ( ! ( success = a_gpspoint_read_file ( vtl, f, dirpath ) ) ) {
1b14d0d2 731 // Failure here means we don't know how to handle the file
0a514451 732 load_answer = LOAD_TYPE_UNSUPPORTED_FAILURE;
1b14d0d2 733 }
0a514451 734 }
0a514451 735 // Clean up when we can't handle the file
cb5ec7a8
RN
736 if ( ! success ) {
737 // free up layer
738 g_object_unref ( vtl );
cb5ec7a8 739 }
0a514451
RN
740 else {
741 // Complete the setup from the successful load
3f350544 742 vik_layer_post_read ( VIK_LAYER(vtl), vp, TRUE );
718696d6 743 if (add_new) {
3f350544 744 vik_aggregate_layer_add_layer ( top, VIK_LAYER(vtl), FALSE );
718696d6 745 }
1af3583b
RN
746 else {
747 // Make it more accessible in layers panel
748 vik_layer_expand_tree ( VIK_LAYER(vtl) );
749 }
3f350544 750 vik_trw_layer_auto_set_view ( vtl, vp );
0a514451 751 }
50a14534 752 }
70b96cd5 753 g_free ( dirpath );
0a514451
RN
754 xfclose(f);
755 return load_answer;
50a14534
EB
756}
757
758gboolean a_file_save ( VikAggregateLayer *top, gpointer vp, const gchar *filename )
759{
bf1c0ae3
SM
760 FILE *f;
761
762 if (strncmp(filename, "file://", 7) == 0)
763 filename = filename + 7;
764
765 f = g_fopen(filename, "w");
50a14534
EB
766
767 if ( ! f )
768 return FALSE;
769
31729835 770 // Enable relative paths in .vik files to work
1dfb1691 771 gchar *cwd = g_get_current_dir();
31729835
RN
772 gchar *dir = g_path_get_dirname ( filename );
773 if ( dir ) {
774 if ( g_chdir ( dir ) ) {
775 g_warning ( "Could not change directory to %s", dir );
776 }
31729835
RN
777 }
778
8a439f31
RN
779 file_write ( top, f, vp, dir );
780 g_free (dir);
50a14534 781
1dfb1691
RN
782 // Restore previous working directory
783 if ( cwd ) {
784 if ( g_chdir ( cwd ) ) {
785 g_warning ( "Could not return to directory %s", cwd );
786 }
787 g_free (cwd);
788 }
789
50a14534 790 fclose(f);
8c060406 791 f = NULL;
50a14534
EB
792
793 return TRUE;
794}
795
796
b0252b2e 797/* example:
140d0d67 798 gboolean is_gpx = a_file_check_ext ( "a/b/c.gpx", ".gpx" );
b0252b2e 799*/
140d0d67 800gboolean a_file_check_ext ( const gchar *filename, const gchar *fileext )
b0252b2e 801{
0a514451
RN
802 g_return_val_if_fail ( filename != NULL, FALSE );
803 g_return_val_if_fail ( fileext && fileext[0]=='.', FALSE );
b0252b2e 804 const gchar *basename = a_file_basename(filename);
b0252b2e
T
805 if (!basename)
806 return FALSE;
807
808 const char * dot = strrchr(basename, '.');
809 if (dot && !strcmp(dot, fileext))
810 return TRUE;
811
812 return FALSE;
813}
814
208d2084
RN
815/**
816 * a_file_export:
817 * @vtl: The TrackWaypoint to export data from
818 * @filename: The name of the file to be written
819 * @file_type: Choose one of the supported file types for the export
820 * @trk: If specified then only export this track rather than the whole layer
821 * @write_hidden: Whether to write invisible items
822 *
823 * A general export command to convert from Viking TRW layer data to an external supported format.
824 * The write_hidden option is provided mainly to be able to transfer selected items when uploading to a GPS
825 */
826gboolean a_file_export ( VikTrwLayer *vtl, const gchar *filename, VikFileType_t file_type, VikTrack *trk, gboolean write_hidden )
50a14534 827{
0d2b891f 828 GpxWritingOptions options = { FALSE, FALSE, write_hidden, FALSE };
8c060406 829 FILE *f = g_fopen ( filename, "w" );
50a14534
EB
830 if ( f )
831 {
1ca082d7 832 gboolean result = TRUE;
8a439f31 833 gchar *dirpath = g_path_get_dirname ( filename );
1ca082d7 834
ce4bd1cf 835 if ( trk ) {
f7f8a0a6
GB
836 switch ( file_type ) {
837 case FILE_TYPE_GPX:
0d2b891f
RN
838 // trk defined so can set the option
839 options.is_route = trk->is_route;
208d2084 840 a_gpx_write_track_file ( trk, f, &options );
f7f8a0a6
GB
841 break;
842 default:
843 g_critical("Houston, we've had a problem. file_type=%d", file_type);
844 }
845 } else {
846 switch ( file_type ) {
847 case FILE_TYPE_GPSMAPPER:
848 a_gpsmapper_write_file ( vtl, f );
849 break;
850 case FILE_TYPE_GPX:
8a439f31 851 a_gpx_write_file ( vtl, f, &options, dirpath );
f7f8a0a6
GB
852 break;
853 case FILE_TYPE_GPSPOINT:
8a439f31 854 a_gpspoint_write_file ( vtl, f, dirpath );
f7f8a0a6 855 break;
1ca082d7
RN
856 case FILE_TYPE_GEOJSON:
857 result = a_geojson_write_file ( vtl, f );
858 break;
ba9d0a00
RN
859 case FILE_TYPE_KML:
860 fclose ( f );
60dbd0ad
RN
861 switch ( a_vik_get_kml_export_units () ) {
862 case VIK_KML_EXPORT_UNITS_STATUTE:
6f94db6d 863 return a_babel_convert_to ( vtl, NULL, "-o kml", filename, NULL, NULL );
60dbd0ad
RN
864 break;
865 case VIK_KML_EXPORT_UNITS_NAUTICAL:
6f94db6d 866 return a_babel_convert_to ( vtl, NULL, "-o kml,units=n", filename, NULL, NULL );
60dbd0ad
RN
867 break;
868 default:
869 // VIK_KML_EXPORT_UNITS_METRIC:
6f94db6d 870 return a_babel_convert_to ( vtl, NULL, "-o kml,units=m", filename, NULL, NULL );
60dbd0ad
RN
871 break;
872 }
873 break;
f7f8a0a6
GB
874 default:
875 g_critical("Houston, we've had a problem. file_type=%d", file_type);
876 }
7f6757c4 877 }
8a439f31 878 g_free ( dirpath );
50a14534 879 fclose ( f );
1ca082d7 880 return result;
50a14534
EB
881 }
882 return FALSE;
883}
80d0ff2b 884
17720e63
GB
885/**
886 * a_file_export_babel:
887 */
888gboolean a_file_export_babel ( VikTrwLayer *vtl, const gchar *filename, const gchar *format,
889 gboolean tracks, gboolean routes, gboolean waypoints )
890{
891 gchar *args = g_strdup_printf("%s %s %s -o %s",
892 tracks ? "-t" : "",
893 routes ? "-r" : "",
894 waypoints ? "-w" : "",
895 format);
896 gboolean result = a_babel_convert_to ( vtl, NULL, args, filename, NULL, NULL );
897 g_free(args);
898 return result;
899}