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