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>
6 * Copyright (C) 2012-2013, Rob Norris <rw_norris@hotmail.com>
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.
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.
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
40 #define realpath(X,Y) _fullpath(Y,X,MAX_PATH)
43 #include <glib/gstdio.h>
44 #include <glib/gi18n.h>
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"
50 #define GPX_MAGIC "<?xm"
51 #define VIK_MAGIC_LEN 4
53 #define VIKING_FILE_VERSION 1
55 typedef struct _Stack Stack;
62 static void pop(Stack **stack) {
63 Stack *tmp = (*stack)->under;
68 static void push(Stack **stack)
70 Stack *tmp = g_malloc ( sizeof ( Stack ) );
75 static gboolean check_magic ( FILE *f, const gchar *magic_number )
77 gchar magic[VIK_MAGIC_LEN];
80 if ( fread(magic, 1, sizeof(magic), f) == sizeof(magic) &&
81 strncmp(magic, magic_number, sizeof(magic)) == 0 )
83 for ( i = sizeof(magic)-1; i >= 0; i-- ) /* the ol' pushback */
89 static gboolean str_starts_with ( const gchar *haystack, const gchar *needle, guint16 len_needle, gboolean must_be_longer )
91 if ( strlen(haystack) > len_needle - (!must_be_longer) && strncasecmp ( haystack, needle, len_needle ) == 0 )
96 void file_write_layer_param ( FILE *f, const gchar *name, VikLayerParamType type, VikLayerParamData data ) {
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,
100 * not an empty string list.
102 if ( type == VIK_LAYER_PARAM_STRING_LIST ) {
104 GList *iter = (GList *)data.sl;
106 fprintf ( f, "%s=", name );
107 fprintf ( f, "%s\n", (gchar *)(iter->data) );
112 fprintf ( f, "%s=", name );
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 );
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;
124 case VIK_LAYER_PARAM_STRING: fprintf ( f, "%s\n", data.s ? data.s : "" ); break;
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;
131 static void write_layer_params_and_data ( VikLayer *l, FILE *f )
133 VikLayerParam *params = vik_layer_get_interface(l->type)->params;
134 VikLayerFuncGetParam get_param = vik_layer_get_interface(l->type)->get_param;
136 fprintf ( f, "name=%s\n", l->name ? l->name : "" );
138 fprintf ( f, "visible=f\n" );
140 if ( params && get_param )
142 VikLayerParamData data;
143 guint16 i, params_count = vik_layer_get_interface(l->type)->params_count;
144 for ( i = 0; i < params_count; i++ )
146 data = get_param(l, i, TRUE);
147 file_write_layer_param(f, params[i].name, params[i].type, data);
150 if ( vik_layer_get_interface(l->type)->write_file_data )
152 fprintf ( f, "\n\n~LayerData\n" );
153 vik_layer_get_interface(l->type)->write_file_data ( l, f );
154 fprintf ( f, "~EndLayerData\n" );
157 write param, and get_value, etc.
158 then run layer data, and that's it.
162 static void file_write ( VikAggregateLayer *top, FILE *f, gpointer vp )
165 VikLayer *current_layer;
167 VikViewportDrawMode mode;
168 gchar *modestring = NULL;
171 stack->data = (gpointer) vik_aggregate_layer_get_children(VIK_AGGREGATE_LAYER(top));
175 vik_coord_to_latlon ( vik_viewport_get_center ( VIK_VIEWPORT(vp) ), &ll );
177 mode = vik_viewport_get_drawmode ( VIK_VIEWPORT(vp) );
179 case VIK_VIEWPORT_DRAWMODE_UTM: modestring = "utm"; break;
180 case VIK_VIEWPORT_DRAWMODE_EXPEDIA: modestring = "expedia"; break;
181 case VIK_VIEWPORT_DRAWMODE_MERCATOR: modestring = "mercator"; break;
182 case VIK_VIEWPORT_DRAWMODE_LATLON: modestring = "latlon"; break;
184 g_critical("Houston, we've had a problem. mode=%d", mode);
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",
190 vik_viewport_get_xmpp ( VIK_VIEWPORT(vp) ), vik_viewport_get_ympp ( VIK_VIEWPORT(vp) ), ll.lat, ll.lon,
191 modestring, vik_viewport_get_background_color(VIK_VIEWPORT(vp)),
192 vik_viewport_get_highlight_color(VIK_VIEWPORT(vp)),
193 vik_viewport_get_draw_scale(VIK_VIEWPORT(vp)) ? "t" : "f",
194 vik_viewport_get_draw_centermark(VIK_VIEWPORT(vp)) ? "t" : "f",
195 vik_viewport_get_draw_highlight(VIK_VIEWPORT(vp)) ? "t" : "f" );
197 if ( ! VIK_LAYER(top)->visible )
198 fprintf ( f, "visible=f\n" );
200 while (stack && stack->data)
202 current_layer = VIK_LAYER(((GList *)stack->data)->data);
203 fprintf ( f, "\n~Layer %s\n", vik_layer_get_interface(current_layer->type)->fixed_layer_name );
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)) )
208 stack->data = (gpointer) vik_aggregate_layer_get_children(VIK_AGGREGATE_LAYER(current_layer));
210 else if ( current_layer->type == VIK_LAYER_GPS && !vik_gps_layer_is_empty(VIK_GPS_LAYER(current_layer)) )
213 stack->data = (gpointer) vik_gps_layer_get_children(VIK_GPS_LAYER(current_layer));
217 stack->data = (gpointer) ((GList *)stack->data)->next;
218 fprintf ( f, "~EndLayer\n\n" );
219 while ( stack && (!stack->data) )
224 stack->data = (gpointer) ((GList *)stack->data)->next;
225 fprintf ( f, "~EndLayer\n\n" );
231 get vikaggregatelayer's children (?)
232 foreach write ALL params,
233 then layer data (IF function exists)
237 stack of layers (LIST) we are working on
238 when layer->next == NULL ...
243 static void string_list_delete ( gpointer key, gpointer l, gpointer user_data )
245 /* 20071021 bugfix */
246 GList *iter = (GList *) l;
248 g_free ( iter->data );
251 g_list_free ( (GList *) l );
254 static void string_list_set_param (gint i, GList *list, gpointer *layer_and_vp)
258 vik_layer_set_param ( VIK_LAYER(layer_and_vp[0]), i, x, layer_and_vp[1], TRUE );
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
266 * TODO flow up line number(s) / error messages of problems encountered...
269 static gboolean file_read ( VikAggregateLayer *top, FILE *f, const gchar *dirpath, VikViewport *vp )
272 struct LatLon ll = { 0.0, 0.0 };
278 VikLayerParam *params = NULL; /* for current layer, so we don't have to keep on looking up interface */
279 guint8 params_count = 0;
281 GHashTable *string_lists = g_hash_table_new(g_direct_hash,g_direct_equal);
283 gboolean successful_read = TRUE;
287 stack->data = (gpointer) top;
289 while ( fgets ( buffer, 4096, f ) )
294 while ( *line == ' ' || *line =='\t' )
297 if ( line[0] == '#' )
302 if ( len > 0 && line[len-1] == '\n' )
304 if ( len > 0 && line[len-1] == '\r' )
311 if ( line[0] == '~' )
316 else if ( str_starts_with ( line, "Layer ", 6, TRUE ) )
318 int parent_type = VIK_LAYER(stack->data)->type;
319 if ( ( ! stack->data ) || ((parent_type != VIK_LAYER_AGGREGATE) && (parent_type != VIK_LAYER_GPS)) )
321 successful_read = FALSE;
322 g_warning ( "Line %ld: Layer command inside non-Aggregate Layer (type %d)", line_num, parent_type );
323 push(&stack); /* inside INVALID layer */
329 VikLayerTypeEnum type = vik_layer_type_from_string ( line+6 );
331 if ( type == VIK_LAYER_NUM_TYPES )
333 successful_read = FALSE;
334 g_warning ( "Line %ld: Unknown type %s", line_num, line+6 );
337 else if (parent_type == VIK_LAYER_GPS)
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;
345 stack->data = (gpointer) vik_layer_create ( type, vp, FALSE );
346 params = vik_layer_get_interface(type)->params;
347 params_count = vik_layer_get_interface(type)->params_count;
351 else if ( str_starts_with ( line, "EndLayer", 8, FALSE ) )
353 if ( stack->under == NULL ) {
354 successful_read = FALSE;
355 g_warning ( "Line %ld: Mismatched ~EndLayer command", line_num );
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 );
366 if ( stack->data && stack->under->data )
368 if (VIK_LAYER(stack->under->data)->type == VIK_LAYER_AGGREGATE) {
369 vik_aggregate_layer_add_layer ( VIK_AGGREGATE_LAYER(stack->under->data), VIK_LAYER(stack->data), FALSE );
370 vik_layer_post_read ( VIK_LAYER(stack->data), vp, TRUE );
372 else if (VIK_LAYER(stack->under->data)->type == VIK_LAYER_GPS) {
373 /* TODO: anything else needs to be done here ? */
376 successful_read = FALSE;
377 g_warning ( "Line %ld: EndLayer command inside non-Aggregate Layer (type %d)", line_num, VIK_LAYER(stack->data)->type );
383 else if ( str_starts_with ( line, "LayerData", 9, FALSE ) )
385 if ( stack->data && vik_layer_get_interface(VIK_LAYER(stack->data)->type)->read_file_data )
387 /* must read until hits ~EndLayerData */
388 if ( ! vik_layer_get_interface(VIK_LAYER(stack->data)->type)->read_file_data ( VIK_LAYER(stack->data), f, dirpath ) )
389 successful_read = FALSE;
392 { /* simply skip layer data over */
393 while ( fgets ( buffer, 4096, f ) )
400 if ( len > 0 && line[len-1] == '\n' )
402 if ( len > 0 && line[len-1] == '\r' )
404 if ( strcasecmp ( line, "~EndLayerData" ) == 0 )
412 successful_read = FALSE;
413 g_warning ( "Line %ld: Unknown tilde command", line_num );
423 for ( i = 0; i < len; i++ )
424 if ( line[i] == '=' )
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
434 else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "xmpp", eq_pos ) == 0) /* "hard coded" params: global & for all layer-types */
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)
448 successful_read = FALSE;
449 g_warning ( _("Draw mode '%s' no more supported"), "google" );
451 else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "kh" ) == 0)
453 successful_read = FALSE;
454 g_warning ( _("Draw mode '%s' no more supported"), "kh" );
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 );
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 );
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 );
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 );
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) );
466 else if ( stack->under == NULL && eq_pos == 14 && strncasecmp ( line, "drawcentermark", eq_pos ) == 0 )
467 vik_viewport_set_draw_centermark ( VIK_VIEWPORT(vp), TEST_BOOLEAN(line+15) );
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) );
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 )
476 gboolean found_match = FALSE;
478 /* go thru layer params. if len == eq_pos && starts_with jazz, set it. */
479 /* also got to check for name and visible. */
483 successful_read = FALSE;
484 g_warning ( "Line %ld: No options for this kind of layer", line_num );
488 for ( i = 0; i < params_count; i++ )
489 if ( strlen(params[i].name) == eq_pos && strncasecmp ( line, params[i].name, eq_pos ) == 0 )
493 if ( params[i].type == VIK_LAYER_PARAM_STRING_LIST ) {
494 GList *l = g_list_append ( g_hash_table_lookup ( string_lists, GINT_TO_POINTER ((gint) i) ),
496 g_hash_table_replace ( string_lists, GINT_TO_POINTER ((gint)i), l );
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 */
500 switch ( params[i].type )
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 */
507 gdk_color_parse ( line, &(x.c) ); break;
508 /* STRING or STRING_LIST -- if STRING_LIST, just set param to add a STRING */
511 vik_layer_set_param ( VIK_LAYER(stack->data), i, x, vp, TRUE );
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;
522 g_warning ( "Line %ld: Unknown parameter. Line:\n%s", line_num, line );
526 successful_read = FALSE;
527 g_warning ( "Line %ld: Invalid parameter or parameter outside of layer.", line_num );
541 if ( stack->under && stack->under->data && stack->data )
543 vik_aggregate_layer_add_layer ( VIK_AGGREGATE_LAYER(stack->under->data), VIK_LAYER(stack->data), FALSE );
544 vik_layer_post_read ( VIK_LAYER(stack->data), vp, TRUE );
549 if ( ll.lat != 0.0 || ll.lon != 0.0 )
550 vik_viewport_set_center_latlon ( VIK_VIEWPORT(vp), &ll, TRUE );
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 );
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 );
559 return successful_read;
566 new default layer of type (str_to_type) (check interface->name)
568 VikLayer *vl = stack->data;
570 vik_aggregate_layer_add_layer(stack->data, vl);
572 vik_layer_data ( VIK_LAYER_DATA(stack->data), f, vp );
576 /* ---------------------------------------------------- */
578 static FILE *xfopen ( const char *fn )
580 if ( strcmp(fn,"-") == 0 )
583 return g_fopen(fn, "r");
586 static void xfclose ( FILE *f )
588 if ( f != stdin && f != stdout ) {
595 * Function to determine if a filename is a 'viking' type file
597 gboolean check_file_magic_vik ( const gchar *filename )
599 gboolean result = FALSE;
600 FILE *ff = xfopen ( filename );
602 result = check_magic ( ff, VIK_MAGIC );
611 * Append a file extension, if not already present.
613 * Returns: a newly allocated string
615 gchar *append_file_ext ( const gchar *filename, VikLoadType_t type )
617 gchar *new_name = NULL;
618 const gchar *ext = NULL;
620 /* Select an extension */
629 case FILE_TYPE_GPSMAPPER:
630 case FILE_TYPE_GPSPOINT:
632 /* Do nothing, ext already set to NULL */
637 if ( ext != NULL && ! a_file_check_ext ( filename, ext ) )
638 new_name = g_strconcat ( filename, ext, NULL );
640 /* Simply duplicate */
641 new_name = g_strdup ( filename );
646 VikLoadType_t a_file_load ( VikAggregateLayer *top, VikViewport *vp, const gchar *filename_or_uri )
648 g_return_val_if_fail ( vp != NULL, LOAD_TYPE_READ_FAILURE );
650 char *filename = (char *)filename_or_uri;
651 if (strncmp(filename, "file://", 7) == 0) {
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)
655 filename = filename + 7;
656 g_debug ( "Loading file %s from URI %s", filename, filename_or_uri );
658 FILE *f = xfopen ( filename );
661 return LOAD_TYPE_READ_FAILURE;
663 VikLoadType_t load_answer = LOAD_TYPE_OTHER_SUCCESS;
665 gchar *dirpath = g_path_get_dirname ( filename );
666 // Attempt loading the primary file type first - our internal .vik file:
667 if ( check_magic ( f, VIK_MAGIC ) )
669 if ( file_read ( top, f, dirpath, vp ) )
670 load_answer = LOAD_TYPE_VIK_SUCCESS;
672 load_answer = LOAD_TYPE_VIK_FAILURE_NON_FATAL;
674 else if ( a_jpg_magic_check ( filename ) ) {
675 if ( ! a_jpg_load_file ( top, filename, vp ) )
676 load_answer = LOAD_TYPE_UNSUPPORTED_FAILURE;
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
684 VikLayer *vtl = vik_layer_create ( VIK_LAYER_TRW, vp, FALSE );
685 vik_layer_rename ( vtl, a_file_basename ( filename ) );
687 // In fact both kml & gpx files start the same as they are in xml
688 if ( a_file_check_ext ( filename, ".kml" ) && check_magic ( f, GPX_MAGIC ) ) {
689 // Implicit Conversion
690 if ( ! ( success = a_babel_convert_from ( VIK_TRW_LAYER(vtl), "-i kml", filename, NULL, NULL, NULL ) ) ) {
691 load_answer = LOAD_TYPE_GPSBABEL_FAILURE;
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
696 else if ( a_file_check_ext ( filename, ".gpx" ) || check_magic ( f, GPX_MAGIC ) ) {
697 if ( ! ( success = a_gpx_read_file ( VIK_TRW_LAYER(vtl), f ) ) ) {
698 load_answer = LOAD_TYPE_GPX_FAILURE;
702 // Try final supported file type
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
705 load_answer = LOAD_TYPE_UNSUPPORTED_FAILURE;
710 // Clean up when we can't handle the file
713 g_object_unref ( vtl );
716 // Complete the setup from the successful load
717 vik_layer_post_read ( vtl, vp, TRUE );
718 vik_aggregate_layer_add_layer ( top, vtl, FALSE );
719 vik_trw_layer_auto_set_view ( VIK_TRW_LAYER(vtl), vp );
726 gboolean a_file_save ( VikAggregateLayer *top, gpointer vp, const gchar *filename )
730 if (strncmp(filename, "file://", 7) == 0)
731 filename = filename + 7;
733 f = g_fopen(filename, "w");
738 // Enable relative paths in .vik files to work
739 gchar *cwd = g_get_current_dir();
740 gchar *dir = g_path_get_dirname ( filename );
742 if ( g_chdir ( dir ) ) {
743 g_warning ( "Could not change directory to %s", dir );
748 file_write ( top, f, vp );
750 // Restore previous working directory
752 if ( g_chdir ( cwd ) ) {
753 g_warning ( "Could not return to directory %s", cwd );
766 gboolean is_gpx = a_file_check_ext ( "a/b/c.gpx", ".gpx" );
768 gboolean a_file_check_ext ( const gchar *filename, const gchar *fileext )
770 g_return_val_if_fail ( filename != NULL, FALSE );
771 g_return_val_if_fail ( fileext && fileext[0]=='.', FALSE );
772 const gchar *basename = a_file_basename(filename);
776 const char * dot = strrchr(basename, '.');
777 if (dot && !strcmp(dot, fileext))
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
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
794 gboolean a_file_export ( VikTrwLayer *vtl, const gchar *filename, VikFileType_t file_type, VikTrack *trk, gboolean write_hidden )
796 GpxWritingOptions options = { FALSE, FALSE, write_hidden, FALSE };
797 FILE *f = g_fopen ( filename, "w" );
801 switch ( file_type ) {
803 // trk defined so can set the option
804 options.is_route = trk->is_route;
805 a_gpx_write_track_file ( trk, f, &options );
808 g_critical("Houston, we've had a problem. file_type=%d", file_type);
811 switch ( file_type ) {
812 case FILE_TYPE_GPSMAPPER:
813 a_gpsmapper_write_file ( vtl, f );
816 a_gpx_write_file ( vtl, f, &options );
818 case FILE_TYPE_GPSPOINT:
819 a_gpspoint_write_file ( vtl, f );
824 switch ( a_vik_get_kml_export_units () ) {
825 case VIK_KML_EXPORT_UNITS_STATUTE:
826 return a_babel_convert_to ( vtl, NULL, "-o kml", filename, NULL, NULL );
828 case VIK_KML_EXPORT_UNITS_NAUTICAL:
829 return a_babel_convert_to ( vtl, NULL, "-o kml,units=n", filename, NULL, NULL );
832 // VIK_KML_EXPORT_UNITS_METRIC:
833 return a_babel_convert_to ( vtl, NULL, "-o kml,units=m", filename, NULL, NULL );
838 g_critical("Houston, we've had a problem. file_type=%d", file_type);
849 * a_file_export_babel:
851 gboolean a_file_export_babel ( VikTrwLayer *vtl, const gchar *filename, const gchar *format,
852 gboolean tracks, gboolean routes, gboolean waypoints )
854 gchar *args = g_strdup_printf("%s %s %s -o %s",
857 waypoints ? "-w" : "",
859 gboolean result = a_babel_convert_to ( vtl, NULL, args, filename, NULL, NULL );
865 * Just a wrapper around realpath, which itself is platform dependent
867 char *file_realpath ( const char *path, char *real )
869 return realpath ( path, real );
873 #define MAXPATHLEN 1024
876 * Always return the canonical filename in a newly allocated string
878 char *file_realpath_dup ( const char *path )
880 char real[MAXPATHLEN];
882 g_return_val_if_fail(path != NULL, NULL);
884 if (file_realpath(path, real))
885 return g_strdup(real);
887 return g_strdup(path);
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
894 * FROM http://www.codeguru.com/cpp/misc/misc/fileanddirectorynaming/article.php/c263
897 // GetRelativeFilename(), by Rob Fisher.
899 // http://come.to/robfisher
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.
905 #define ABSOLUTE_NAME_START 3
907 #define ABSOLUTE_NAME_START 1
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.
914 const gchar *file_GetRelativeFilename ( gchar *currentDirectory, gchar *absoluteFilename )
916 gint afMarker = 0, rfMarker = 0;
917 gint cdLen = 0, afLen = 0;
920 static gchar relativeFilename[MAXPATHLEN+1];
922 cdLen = strlen(currentDirectory);
923 afLen = strlen(absoluteFilename);
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) {
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;
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]) {
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...
955 strcpy(relativeFilename, &absoluteFilename[i]);
956 return relativeFilename;
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
966 // count the number of directory levels we have to go up to get to the
970 if (currentDirectory[i] == G_DIR_SEPARATOR) {
971 // make sure it's not a trailing slash
973 if (currentDirectory[i] != '\0') {
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) {
985 // check that the result will not be too long
986 if (levels * 3 + afLen - afMarker > MAXPATHLEN) {
990 // add the appropriate number of "..\"s.
992 for (i = 0; i < levels; i++) {
993 relativeFilename[rfMarker++] = '.';
994 relativeFilename[rfMarker++] = '.';
995 relativeFilename[rfMarker++] = G_DIR_SEPARATOR;
998 // copy the rest of the filename into the result string
999 strcpy(&relativeFilename[rfMarker], &absoluteFilename[afMarker]);
1001 return relativeFilename;
1003 /* END http://www.codeguru.com/cpp/misc/misc/fileanddirectorynaming/article.php/c263 */