2 * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
4 * Copyright (C) 2003-2005, Evan Battaglia <gtoevan@gmx.net>
5 * Copyright (C) 2012, Guilhem Bonnefille <guilhem.bonnefille@gmail.com>
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.
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.
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
38 #define realpath(X,Y) _fullpath(Y,X,MAX_PATH)
41 #include <glib/gstdio.h>
42 #include <glib/gi18n.h>
44 #define TEST_BOOLEAN(str) (! ((str)[0] == '\0' || (str)[0] == '0' || (str)[0] == 'n' || (str)[0] == 'N' || (str)[0] == 'f' || (str)[0] == 'F') )
45 #define VIK_MAGIC "#VIK"
46 #define GPX_MAGIC "<?xm"
47 #define VIK_MAGIC_LEN 4
55 #define VIKING_FILE_VERSION 1
57 typedef struct _Stack Stack;
64 static void pop(Stack **stack) {
65 Stack *tmp = (*stack)->under;
70 static void push(Stack **stack)
72 Stack *tmp = g_malloc ( sizeof ( Stack ) );
77 static gboolean check_magic ( FILE *f, const gchar *magic_number )
79 gchar magic[VIK_MAGIC_LEN];
82 if ( fread(magic, 1, sizeof(magic), f) == sizeof(magic) &&
83 strncmp(magic, magic_number, sizeof(magic)) == 0 )
85 for ( i = sizeof(magic)-1; i >= 0; i-- ) /* the ol' pushback */
91 static gboolean str_starts_with ( const gchar *haystack, const gchar *needle, guint16 len_needle, gboolean must_be_longer )
93 if ( strlen(haystack) > len_needle - (!must_be_longer) && strncasecmp ( haystack, needle, len_needle ) == 0 )
98 void file_write_layer_param ( FILE *f, const gchar *name, VikLayerParamType type, VikLayerParamData data ) {
99 /* string lists are handled differently. We get a GList (that shouldn't
100 * be freed) back for get_param and if it is null we shouldn't write
101 * anything at all (otherwise we'd read in a list with an empty string,
102 * not an empty string list.
104 if ( type == VIK_LAYER_PARAM_STRING_LIST ) {
106 GList *iter = (GList *)data.sl;
108 fprintf ( f, "%s=", name );
109 fprintf ( f, "%s\n", (gchar *)(iter->data) );
114 fprintf ( f, "%s=", name );
117 case VIK_LAYER_PARAM_DOUBLE: {
118 // char buf[15]; /* locale independent */
119 // fprintf ( f, "%s\n", (char *) g_dtostr (data.d, buf, sizeof (buf)) ); break;
120 fprintf ( f, "%f\n", data.d );
123 case VIK_LAYER_PARAM_UINT: fprintf ( f, "%d\n", data.u ); break;
124 case VIK_LAYER_PARAM_INT: fprintf ( f, "%d\n", data.i ); break;
125 case VIK_LAYER_PARAM_BOOLEAN: fprintf ( f, "%c\n", data.b ? 't' : 'f' ); break;
126 case VIK_LAYER_PARAM_STRING: fprintf ( f, "%s\n", data.s ? data.s : "" ); break;
127 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;
133 static void write_layer_params_and_data ( VikLayer *l, FILE *f )
135 VikLayerParam *params = vik_layer_get_interface(l->type)->params;
136 VikLayerFuncGetParam get_param = vik_layer_get_interface(l->type)->get_param;
138 fprintf ( f, "name=%s\n", l->name ? l->name : "" );
140 fprintf ( f, "visible=f\n" );
142 if ( params && get_param )
144 VikLayerParamData data;
145 guint16 i, params_count = vik_layer_get_interface(l->type)->params_count;
146 for ( i = 0; i < params_count; i++ )
148 data = get_param(l, i, TRUE);
149 file_write_layer_param(f, params[i].name, params[i].type, data);
152 if ( vik_layer_get_interface(l->type)->write_file_data )
154 fprintf ( f, "\n\n~LayerData\n" );
155 vik_layer_get_interface(l->type)->write_file_data ( l, f );
156 fprintf ( f, "~EndLayerData\n" );
159 write param, and get_value, etc.
160 then run layer data, and that's it.
164 static void file_write ( VikAggregateLayer *top, FILE *f, gpointer vp )
167 VikLayer *current_layer;
169 VikViewportDrawMode mode;
170 gchar *modestring = NULL;
173 stack->data = (gpointer) vik_aggregate_layer_get_children(VIK_AGGREGATE_LAYER(top));
177 vik_coord_to_latlon ( vik_viewport_get_center ( VIK_VIEWPORT(vp) ), &ll );
179 mode = vik_viewport_get_drawmode ( VIK_VIEWPORT(vp) );
181 case VIK_VIEWPORT_DRAWMODE_UTM: modestring = "utm"; break;
182 case VIK_VIEWPORT_DRAWMODE_EXPEDIA: modestring = "expedia"; break;
183 case VIK_VIEWPORT_DRAWMODE_MERCATOR: modestring = "mercator"; break;
184 case VIK_VIEWPORT_DRAWMODE_LATLON: modestring = "latlon"; break;
186 g_critical("Houston, we've had a problem. mode=%d", mode);
189 fprintf ( f, "#VIKING GPS Data file " VIKING_URL "\n" );
190 fprintf ( f, "FILE_VERSION=%d\n", VIKING_FILE_VERSION );
191 fprintf ( f, "\nxmpp=%f\nympp=%f\nlat=%f\nlon=%f\nmode=%s\ncolor=%s\nhighlightcolor=%s\ndrawscale=%s\ndrawcentermark=%s\ndrawhighlight=%s\n",
192 vik_viewport_get_xmpp ( VIK_VIEWPORT(vp) ), vik_viewport_get_ympp ( VIK_VIEWPORT(vp) ), ll.lat, ll.lon,
193 modestring, vik_viewport_get_background_color(VIK_VIEWPORT(vp)),
194 vik_viewport_get_highlight_color(VIK_VIEWPORT(vp)),
195 vik_viewport_get_draw_scale(VIK_VIEWPORT(vp)) ? "t" : "f",
196 vik_viewport_get_draw_centermark(VIK_VIEWPORT(vp)) ? "t" : "f",
197 vik_viewport_get_draw_highlight(VIK_VIEWPORT(vp)) ? "t" : "f" );
199 if ( ! VIK_LAYER(top)->visible )
200 fprintf ( f, "visible=f\n" );
202 while (stack && stack->data)
204 current_layer = VIK_LAYER(((GList *)stack->data)->data);
205 fprintf ( f, "\n~Layer %s\n", vik_layer_get_interface(current_layer->type)->fixed_layer_name );
206 write_layer_params_and_data ( current_layer, f );
207 if ( current_layer->type == VIK_LAYER_AGGREGATE && !vik_aggregate_layer_is_empty(VIK_AGGREGATE_LAYER(current_layer)) )
210 stack->data = (gpointer) vik_aggregate_layer_get_children(VIK_AGGREGATE_LAYER(current_layer));
212 else if ( current_layer->type == VIK_LAYER_GPS && !vik_gps_layer_is_empty(VIK_GPS_LAYER(current_layer)) )
215 stack->data = (gpointer) vik_gps_layer_get_children(VIK_GPS_LAYER(current_layer));
219 stack->data = (gpointer) ((GList *)stack->data)->next;
220 fprintf ( f, "~EndLayer\n\n" );
221 while ( stack && (!stack->data) )
226 stack->data = (gpointer) ((GList *)stack->data)->next;
227 fprintf ( f, "~EndLayer\n\n" );
233 get vikaggregatelayer's children (?)
234 foreach write ALL params,
235 then layer data (IF function exists)
239 stack of layers (LIST) we are working on
240 when layer->next == NULL ...
245 static void string_list_delete ( gpointer key, gpointer l, gpointer user_data )
247 /* 20071021 bugfix */
248 GList *iter = (GList *) l;
250 g_free ( iter->data );
253 g_list_free ( (GList *) l );
256 static void string_list_set_param (gint i, GList *list, gpointer *layer_and_vp)
260 vik_layer_set_param ( VIK_LAYER(layer_and_vp[0]), i, x, layer_and_vp[1], TRUE );
264 * Read in a Viking file and return how successful the parsing was
265 * ATM this will always work, in that even if there are parsing problems
266 * then there will be no new values to override the defaults
268 * TODO flow up line number(s) / error messages of problems encountered...
271 static gboolean file_read ( VikAggregateLayer *top, FILE *f, VikViewport *vp )
274 struct LatLon ll = { 0.0, 0.0 };
280 VikLayerParam *params = NULL; /* for current layer, so we don't have to keep on looking up interface */
281 guint8 params_count = 0;
283 GHashTable *string_lists = g_hash_table_new(g_direct_hash,g_direct_equal);
285 gboolean successful_read = TRUE;
289 stack->data = (gpointer) top;
291 while ( fgets ( buffer, 4096, f ) )
296 while ( *line == ' ' || *line =='\t' )
299 if ( line[0] == '#' )
304 if ( len > 0 && line[len-1] == '\n' )
306 if ( len > 0 && line[len-1] == '\r' )
313 if ( line[0] == '~' )
318 else if ( str_starts_with ( line, "Layer ", 6, TRUE ) )
320 int parent_type = VIK_LAYER(stack->data)->type;
321 if ( ( ! stack->data ) || ((parent_type != VIK_LAYER_AGGREGATE) && (parent_type != VIK_LAYER_GPS)) )
323 successful_read = FALSE;
324 g_warning ( "Line %ld: Layer command inside non-Aggregate Layer (type %d)", line_num, parent_type );
325 push(&stack); /* inside INVALID layer */
331 VikLayerTypeEnum type = vik_layer_type_from_string ( line+6 );
333 if ( type == VIK_LAYER_NUM_TYPES )
335 successful_read = FALSE;
336 g_warning ( "Line %ld: Unknown type %s", line_num, line+6 );
339 else if (parent_type == VIK_LAYER_GPS)
341 stack->data = (gpointer) vik_gps_layer_get_a_child(VIK_GPS_LAYER(stack->under->data));
342 params = vik_layer_get_interface(type)->params;
343 params_count = vik_layer_get_interface(type)->params_count;
347 stack->data = (gpointer) vik_layer_create ( type, vp, NULL, FALSE );
348 params = vik_layer_get_interface(type)->params;
349 params_count = vik_layer_get_interface(type)->params_count;
353 else if ( str_starts_with ( line, "EndLayer", 8, FALSE ) )
355 if ( stack->under == NULL ) {
356 successful_read = FALSE;
357 g_warning ( "Line %ld: Mismatched ~EndLayer command", line_num );
361 /* add any string lists we've accumulated */
362 gpointer layer_and_vp[2];
363 layer_and_vp[0] = stack->data;
364 layer_and_vp[1] = vp;
365 g_hash_table_foreach ( string_lists, (GHFunc) string_list_set_param, layer_and_vp );
366 g_hash_table_remove_all ( string_lists );
368 if ( stack->data && stack->under->data )
370 if (VIK_LAYER(stack->under->data)->type == VIK_LAYER_AGGREGATE) {
371 vik_aggregate_layer_add_layer ( VIK_AGGREGATE_LAYER(stack->under->data), VIK_LAYER(stack->data), FALSE );
372 vik_layer_post_read ( VIK_LAYER(stack->data), vp, TRUE );
374 else if (VIK_LAYER(stack->under->data)->type == VIK_LAYER_GPS) {
375 /* TODO: anything else needs to be done here ? */
378 successful_read = FALSE;
379 g_warning ( "Line %ld: EndLayer command inside non-Aggregate Layer (type %d)", line_num, VIK_LAYER(stack->data)->type );
385 else if ( str_starts_with ( line, "LayerData", 9, FALSE ) )
387 if ( stack->data && vik_layer_get_interface(VIK_LAYER(stack->data)->type)->read_file_data )
389 /* must read until hits ~EndLayerData */
390 if ( ! vik_layer_get_interface(VIK_LAYER(stack->data)->type)->read_file_data ( VIK_LAYER(stack->data), f ) )
391 successful_read = FALSE;
394 { /* simply skip layer data over */
395 while ( fgets ( buffer, 4096, f ) )
402 if ( len > 0 && line[len-1] == '\n' )
404 if ( len > 0 && line[len-1] == '\r' )
406 if ( strcasecmp ( line, "~EndLayerData" ) == 0 )
414 successful_read = FALSE;
415 g_warning ( "Line %ld: Unknown tilde command", line_num );
425 for ( i = 0; i < len; i++ )
426 if ( line[i] == '=' )
429 if ( stack->under == NULL && eq_pos == 12 && strncasecmp ( line, "FILE_VERSION", eq_pos ) == 0) {
430 gint version = strtol(line+13, NULL, 10);
431 g_debug ( "%s: reading file version %d", __FUNCTION__, version );
432 if ( version > VIKING_FILE_VERSION )
433 successful_read = FALSE;
434 // However we'll still carry and attempt to read whatever we can
436 else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "xmpp", eq_pos ) == 0) /* "hard coded" params: global & for all layer-types */
437 vik_viewport_set_xmpp ( VIK_VIEWPORT(vp), strtod ( line+5, NULL ) );
438 else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "ympp", eq_pos ) == 0)
439 vik_viewport_set_ympp ( VIK_VIEWPORT(vp), strtod ( line+5, NULL ) );
440 else if ( stack->under == NULL && eq_pos == 3 && strncasecmp ( line, "lat", eq_pos ) == 0 )
441 ll.lat = strtod ( line+4, NULL );
442 else if ( stack->under == NULL && eq_pos == 3 && strncasecmp ( line, "lon", eq_pos ) == 0 )
443 ll.lon = strtod ( line+4, NULL );
444 else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "utm" ) == 0)
445 vik_viewport_set_drawmode ( VIK_VIEWPORT(vp), VIK_VIEWPORT_DRAWMODE_UTM);
446 else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "expedia" ) == 0)
447 vik_viewport_set_drawmode ( VIK_VIEWPORT(vp), VIK_VIEWPORT_DRAWMODE_EXPEDIA );
448 else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "google" ) == 0)
450 successful_read = FALSE;
451 g_warning ( _("Draw mode '%s' no more supported"), "google" );
453 else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "kh" ) == 0)
455 successful_read = FALSE;
456 g_warning ( _("Draw mode '%s' no more supported"), "kh" );
458 else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "mercator" ) == 0)
459 vik_viewport_set_drawmode ( VIK_VIEWPORT(vp), VIK_VIEWPORT_DRAWMODE_MERCATOR );
460 else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "latlon" ) == 0)
461 vik_viewport_set_drawmode ( VIK_VIEWPORT(vp), VIK_VIEWPORT_DRAWMODE_LATLON );
462 else if ( stack->under == NULL && eq_pos == 5 && strncasecmp ( line, "color", eq_pos ) == 0 )
463 vik_viewport_set_background_color ( VIK_VIEWPORT(vp), line+6 );
464 else if ( stack->under == NULL && eq_pos == 14 && strncasecmp ( line, "highlightcolor", eq_pos ) == 0 )
465 vik_viewport_set_highlight_color ( VIK_VIEWPORT(vp), line+15 );
466 else if ( stack->under == NULL && eq_pos == 9 && strncasecmp ( line, "drawscale", eq_pos ) == 0 )
467 vik_viewport_set_draw_scale ( VIK_VIEWPORT(vp), TEST_BOOLEAN(line+10) );
468 else if ( stack->under == NULL && eq_pos == 14 && strncasecmp ( line, "drawcentermark", eq_pos ) == 0 )
469 vik_viewport_set_draw_centermark ( VIK_VIEWPORT(vp), TEST_BOOLEAN(line+15) );
470 else if ( stack->under == NULL && eq_pos == 13 && strncasecmp ( line, "drawhighlight", eq_pos ) == 0 )
471 vik_viewport_set_draw_highlight ( VIK_VIEWPORT(vp), TEST_BOOLEAN(line+14) );
472 else if ( stack->under && eq_pos == 4 && strncasecmp ( line, "name", eq_pos ) == 0 )
473 vik_layer_rename ( VIK_LAYER(stack->data), line+5 );
474 else if ( eq_pos == 7 && strncasecmp ( line, "visible", eq_pos ) == 0 )
475 VIK_LAYER(stack->data)->visible = TEST_BOOLEAN(line+8);
476 else if ( eq_pos != -1 && stack->under )
478 gboolean found_match = FALSE;
480 /* go thru layer params. if len == eq_pos && starts_with jazz, set it. */
481 /* also got to check for name and visible. */
485 successful_read = FALSE;
486 g_warning ( "Line %ld: No options for this kind of layer", line_num );
490 for ( i = 0; i < params_count; i++ )
491 if ( strlen(params[i].name) == eq_pos && strncasecmp ( line, params[i].name, eq_pos ) == 0 )
495 if ( params[i].type == VIK_LAYER_PARAM_STRING_LIST ) {
496 GList *l = g_list_append ( g_hash_table_lookup ( string_lists, GINT_TO_POINTER ((gint) i) ),
498 g_hash_table_replace ( string_lists, GINT_TO_POINTER ((gint)i), l );
499 /* add the value to a list, possibly making a new list.
500 * this will be passed to the layer when we read an ~EndLayer */
502 switch ( params[i].type )
504 case VIK_LAYER_PARAM_DOUBLE: x.d = strtod(line, NULL); break;
505 case VIK_LAYER_PARAM_UINT: x.u = strtoul(line, NULL, 10); break;
506 case VIK_LAYER_PARAM_INT: x.i = strtol(line, NULL, 10); break;
507 case VIK_LAYER_PARAM_BOOLEAN: x.b = TEST_BOOLEAN(line); break;
508 case VIK_LAYER_PARAM_COLOR: memset(&(x.c), 0, sizeof(x.c)); /* default: black */
509 gdk_color_parse ( line, &(x.c) ); break;
510 /* STRING or STRING_LIST -- if STRING_LIST, just set param to add a STRING */
513 vik_layer_set_param ( VIK_LAYER(stack->data), i, x, vp, TRUE );
518 if ( ! found_match ) {
519 // ATM don't flow up this issue because at least one internal parameter has changed from version 1.3
520 // and don't what to worry users about raising such issues
521 // TODO Maybe hold old values here - compare the line value against them and if a match
522 // generate a different style of message in the GUI...
523 // successful_read = FALSE;
524 g_warning ( "Line %ld: Unknown parameter. Line:\n%s", line_num, line );
528 successful_read = FALSE;
529 g_warning ( "Line %ld: Invalid parameter or parameter outside of layer.", line_num );
543 if ( stack->under && stack->under->data && stack->data )
545 vik_aggregate_layer_add_layer ( VIK_AGGREGATE_LAYER(stack->under->data), VIK_LAYER(stack->data), FALSE );
546 vik_layer_post_read ( VIK_LAYER(stack->data), vp, TRUE );
551 if ( ll.lat != 0.0 || ll.lon != 0.0 )
552 vik_viewport_set_center_latlon ( VIK_VIEWPORT(vp), &ll );
554 if ( ( ! VIK_LAYER(top)->visible ) && VIK_LAYER(top)->realized )
555 vik_treeview_item_set_visible ( VIK_LAYER(top)->vt, &(VIK_LAYER(top)->iter), FALSE );
557 /* delete anything we've forgotten about -- should only happen when file ends before an EndLayer */
558 g_hash_table_foreach ( string_lists, string_list_delete, NULL );
559 g_hash_table_destroy ( string_lists );
561 return successful_read;
568 new default layer of type (str_to_type) (check interface->name)
570 VikLayer *vl = stack->data;
572 vik_aggregate_layer_add_layer(stack->data, vl);
574 vik_layer_data ( VIK_LAYER_DATA(stack->data), f, vp );
578 /* ---------------------------------------------------- */
580 static FILE *xfopen ( const char *fn, const char *mode )
582 if ( strcmp(fn,"-") == 0 )
585 return g_fopen(fn, "r");
588 static void xfclose ( FILE *f )
590 if ( f != stdin && f != stdout ) {
597 * Function to determine if a filename is a 'viking' type file
599 gboolean check_file_magic_vik ( const gchar *filename )
601 gboolean result = FALSE;
602 FILE *ff = xfopen ( filename, "r" );
604 result = check_magic ( ff, VIK_MAGIC );
610 VikLoadType_t a_file_load ( VikAggregateLayer *top, VikViewport *vp, const gchar *filename_or_uri )
612 g_return_val_if_fail ( vp != NULL, LOAD_TYPE_READ_FAILURE );
614 char *filename = (char *)filename_or_uri;
615 if (strncmp(filename, "file://", 7) == 0) {
616 filename = filename + 7;
618 // For drag and drop we receive URIs like 'file:///c:/path/to/file'
619 // Thus may need to ignore the leading '/'
620 if ( strlen (filename) > 3 ) {
621 if ( (strncmp (filename, "/", 1) == 0) && (strncmp (filename+2, ":", 1) == 0) )
622 filename = filename + 1;
625 g_debug ( "Loading file %s from URI %s", filename, filename_or_uri );
627 FILE *f = xfopen ( filename, "r" );
630 return LOAD_TYPE_READ_FAILURE;
632 // Enables relative paths in a .vik file to work
633 // Also allows us to remember what directory we where using
634 gchar *dir = g_path_get_dirname ( filename );
636 if ( g_chdir ( dir ) ) {
637 g_warning ( "Could not change directory to %s", dir );
642 VikLoadType_t load_answer = LOAD_TYPE_OTHER_SUCCESS;
644 // Attempt loading the primary file type first - our internal .vik file:
645 if ( check_magic ( f, VIK_MAGIC ) )
647 if ( file_read ( top, f, vp ) )
648 load_answer = LOAD_TYPE_VIK_SUCCESS;
650 load_answer = LOAD_TYPE_VIK_FAILURE_NON_FATAL;
654 // For all other file types which consist of tracks, routes and/or waypoints,
655 // must be loaded into a new TrackWaypoint layer (hence it be created)
656 gboolean success = TRUE; // Detect load failures - mainly to remove the layer created as it's not required
658 VikLayer *vtl = vik_layer_create ( VIK_LAYER_TRW, vp, NULL, FALSE );
660 // In fact both kml & gpx files start the same as they are in xml
661 if ( check_file_ext ( filename, ".kml" ) && check_magic ( f, GPX_MAGIC ) ) {
662 // Implicit Conversion
663 if ( ! ( success = a_babel_convert_from ( VIK_TRW_LAYER(vtl), "-i kml", filename, NULL, NULL, NULL ) ) ) {
664 load_answer = LOAD_TYPE_GPSBABEL_FAILURE;
667 // NB use a extension check first, as a GPX file header may have a Byte Order Mark (BOM) in it
668 // - which currently confuses our check_magic function
669 else if ( check_file_ext ( filename, ".gpx" ) || check_magic ( f, GPX_MAGIC ) ) {
670 if ( ! ( success = a_gpx_read_file ( VIK_TRW_LAYER(vtl), f ) ) ) {
671 load_answer = LOAD_TYPE_GPX_FAILURE;
675 // Try final supported file type
676 if ( ! ( success = a_gpspoint_read_file ( VIK_TRW_LAYER(vtl), f ) ) ) {
677 // Failure here means we don't know how to handle the file
678 load_answer = LOAD_TYPE_UNSUPPORTED_FAILURE;
682 // Clean up when we can't handle the file
685 g_object_unref ( vtl );
688 // Complete the setup from the successful load
689 vik_layer_rename ( vtl, a_file_basename ( filename ) );
690 vik_layer_post_read ( vtl, vp, TRUE );
691 vik_aggregate_layer_add_layer ( top, vtl, FALSE );
692 vik_trw_layer_auto_set_view ( VIK_TRW_LAYER(vtl), vp );
699 gboolean a_file_save ( VikAggregateLayer *top, gpointer vp, const gchar *filename )
703 if (strncmp(filename, "file://", 7) == 0)
704 filename = filename + 7;
706 f = g_fopen(filename, "w");
711 // Enable relative paths in .vik files to work
712 // Also allows us to remember what directory we where using
713 gchar *dir = g_path_get_dirname ( filename );
715 if ( g_chdir ( dir ) ) {
716 g_warning ( "Could not change directory to %s", dir );
721 file_write ( top, f, vp );
730 const gchar *a_file_basename ( const gchar *filename )
732 const gchar *t = filename + strlen(filename) - 1;
733 while ( --t > filename )
734 if ( *(t-1) == FILE_SEP )
742 gboolean is_gpx = check_file_ext ( "a/b/c.gpx", ".gpx" );
744 gboolean check_file_ext ( const gchar *filename, const gchar *fileext )
746 g_return_val_if_fail ( filename != NULL, FALSE );
747 g_return_val_if_fail ( fileext && fileext[0]=='.', FALSE );
748 const gchar *basename = a_file_basename(filename);
752 const char * dot = strrchr(basename, '.');
753 if (dot && !strcmp(dot, fileext))
761 * @vtl: The TrackWaypoint to export data from
762 * @filename: The name of the file to be written
763 * @file_type: Choose one of the supported file types for the export
764 * @trk: If specified then only export this track rather than the whole layer
765 * @write_hidden: Whether to write invisible items
767 * A general export command to convert from Viking TRW layer data to an external supported format.
768 * The write_hidden option is provided mainly to be able to transfer selected items when uploading to a GPS
770 gboolean a_file_export ( VikTrwLayer *vtl, const gchar *filename, VikFileType_t file_type, VikTrack *trk, gboolean write_hidden )
772 GpxWritingOptions options = { FALSE, FALSE, write_hidden, FALSE };
773 FILE *f = g_fopen ( filename, "w" );
777 switch ( file_type ) {
779 // trk defined so can set the option
780 options.is_route = trk->is_route;
781 a_gpx_write_track_file ( trk, f, &options );
784 g_critical("Houston, we've had a problem. file_type=%d", file_type);
787 switch ( file_type ) {
788 case FILE_TYPE_GPSMAPPER:
789 a_gpsmapper_write_file ( vtl, f );
792 a_gpx_write_file ( vtl, f, &options );
794 case FILE_TYPE_GPSPOINT:
795 a_gpspoint_write_file ( vtl, f );
800 switch ( a_vik_get_kml_export_units () ) {
801 case VIK_KML_EXPORT_UNITS_STATUTE:
802 return a_babel_convert_to ( vtl, NULL, "-o kml", filename, NULL, NULL );
804 case VIK_KML_EXPORT_UNITS_NAUTICAL:
805 return a_babel_convert_to ( vtl, NULL, "-o kml,units=n", filename, NULL, NULL );
808 // VIK_KML_EXPORT_UNITS_METRIC:
809 return a_babel_convert_to ( vtl, NULL, "-o kml,units=m", filename, NULL, NULL );
814 g_critical("Houston, we've had a problem. file_type=%d", file_type);
825 * Just a wrapper around realpath, which itself is platform dependent
827 char *file_realpath ( const char *path, char *real )
829 return realpath ( path, real );
833 * Permission granted to use this code after personal correspondance
834 * Slightly reworked for better cross platform use, glibisms, function rename and a compacter format
836 * FROM http://www.codeguru.com/cpp/misc/misc/fileanddirectorynaming/article.php/c263
839 // GetRelativeFilename(), by Rob Fisher.
841 // http://come.to/robfisher
845 #define MAXPATHLEN 1024
847 // The number of characters at the start of an absolute filename. e.g. in DOS,
848 // absolute filenames start with "X:\" so this value should be 3, in UNIX they start
849 // with "\" so this value should be 1.
851 #define ABSOLUTE_NAME_START 3
853 #define ABSOLUTE_NAME_START 1
856 // Given the absolute current directory and an absolute file name, returns a relative file name.
857 // For example, if the current directory is C:\foo\bar and the filename C:\foo\whee\text.txt is given,
858 // GetRelativeFilename will return ..\whee\text.txt.
860 const gchar *file_GetRelativeFilename ( gchar *currentDirectory, gchar *absoluteFilename )
862 gint afMarker = 0, rfMarker = 0;
863 gint cdLen = 0, afLen = 0;
866 static gchar relativeFilename[MAXPATHLEN+1];
868 cdLen = strlen(currentDirectory);
869 afLen = strlen(absoluteFilename);
871 // make sure the names are not too long or too short
872 if (cdLen > MAXPATHLEN || cdLen < ABSOLUTE_NAME_START+1 ||
873 afLen > MAXPATHLEN || afLen < ABSOLUTE_NAME_START+1) {
877 // Handle DOS names that are on different drives:
878 if (currentDirectory[0] != absoluteFilename[0]) {
879 // not on the same drive, so only absolute filename will do
880 strcpy(relativeFilename, absoluteFilename);
881 return relativeFilename;
884 // they are on the same drive, find out how much of the current directory
885 // is in the absolute filename
886 i = ABSOLUTE_NAME_START;
887 while (i < afLen && i < cdLen && currentDirectory[i] == absoluteFilename[i]) {
891 if (i == cdLen && (absoluteFilename[i] == G_DIR_SEPARATOR || absoluteFilename[i-1] == G_DIR_SEPARATOR)) {
892 // the whole current directory name is in the file name,
893 // so we just trim off the current directory name to get the
894 // current file name.
895 if (absoluteFilename[i] == G_DIR_SEPARATOR) {
896 // a directory name might have a trailing slash but a relative
897 // file name should not have a leading one...
901 strcpy(relativeFilename, &absoluteFilename[i]);
902 return relativeFilename;
905 // The file is not in a child directory of the current directory, so we
906 // need to step back the appropriate number of parent directories by
907 // using "..\"s. First find out how many levels deeper we are than the
912 // count the number of directory levels we have to go up to get to the
916 if (currentDirectory[i] == G_DIR_SEPARATOR) {
917 // make sure it's not a trailing slash
919 if (currentDirectory[i] != '\0') {
925 // move the absolute filename marker back to the start of the directory name
926 // that it has stopped in.
927 while (afMarker > 0 && absoluteFilename[afMarker-1] != G_DIR_SEPARATOR) {
931 // check that the result will not be too long
932 if (levels * 3 + afLen - afMarker > MAXPATHLEN) {
936 // add the appropriate number of "..\"s.
938 for (i = 0; i < levels; i++) {
939 relativeFilename[rfMarker++] = '.';
940 relativeFilename[rfMarker++] = '.';
941 relativeFilename[rfMarker++] = G_DIR_SEPARATOR;
944 // copy the rest of the filename into the result string
945 strcpy(&relativeFilename[rfMarker], &absoluteFilename[afMarker]);
947 return relativeFilename;
949 /* END http://www.codeguru.com/cpp/misc/misc/fileanddirectorynaming/article.php/c263 */