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