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