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
41 #define realpath(X,Y) _fullpath(Y,X,MAX_PATH)
44 #include <glib/gstdio.h>
45 #include <glib/gi18n.h>
48 #include "misc/strtod.h"
50 #define TEST_BOOLEAN(str) (! ((str)[0] == '\0' || (str)[0] == '0' || (str)[0] == 'n' || (str)[0] == 'N' || (str)[0] == 'f' || (str)[0] == 'F') )
51 #define VIK_MAGIC "#VIK"
52 #define GPX_MAGIC "<?xm"
53 #define VIK_MAGIC_LEN 4
54 #define GPX_MAGIC_LEN 4
56 #define VIKING_FILE_VERSION 1
58 typedef struct _Stack Stack;
65 static void pop(Stack **stack) {
66 Stack *tmp = (*stack)->under;
71 static void push(Stack **stack)
73 Stack *tmp = g_malloc ( sizeof ( Stack ) );
78 static gboolean check_magic ( FILE *f, const gchar *magic_number, guint magic_length )
80 gchar magic[magic_length];
83 if ( fread(magic, 1, sizeof(magic), f) == sizeof(magic) &&
84 strncmp(magic, magic_number, sizeof(magic)) == 0 )
86 for ( i = sizeof(magic)-1; i >= 0; i-- ) /* the ol' pushback */
92 static gboolean str_starts_with ( const gchar *haystack, const gchar *needle, guint16 len_needle, gboolean must_be_longer )
94 if ( strlen(haystack) > len_needle - (!must_be_longer) && strncasecmp ( haystack, needle, len_needle ) == 0 )
99 void file_write_layer_param ( FILE *f, const gchar *name, VikLayerParamType type, VikLayerParamData data ) {
100 /* string lists are handled differently. We get a GList (that shouldn't
101 * be freed) back for get_param and if it is null we shouldn't write
102 * anything at all (otherwise we'd read in a list with an empty string,
103 * not an empty string list.
105 if ( type == VIK_LAYER_PARAM_STRING_LIST ) {
107 GList *iter = (GList *)data.sl;
109 fprintf ( f, "%s=", name );
110 fprintf ( f, "%s\n", (gchar *)(iter->data) );
115 fprintf ( f, "%s=", name );
118 case VIK_LAYER_PARAM_DOUBLE: {
119 // char buf[15]; /* locale independent */
120 // fprintf ( f, "%s\n", (char *) g_dtostr (data.d, buf, sizeof (buf)) ); break;
121 fprintf ( f, "%f\n", data.d );
124 case VIK_LAYER_PARAM_UINT: fprintf ( f, "%d\n", data.u ); break;
125 case VIK_LAYER_PARAM_INT: fprintf ( f, "%d\n", data.i ); break;
126 case VIK_LAYER_PARAM_BOOLEAN: fprintf ( f, "%c\n", data.b ? 't' : 'f' ); break;
127 case VIK_LAYER_PARAM_STRING: fprintf ( f, "%s\n", data.s ? data.s : "" ); break;
128 case VIK_LAYER_PARAM_COLOR: fprintf ( f, "#%.2x%.2x%.2x\n", (int)(data.c.red/256),(int)(data.c.green/256),(int)(data.c.blue/256)); break;
134 static void write_layer_params_and_data ( VikLayer *l, FILE *f )
136 VikLayerParam *params = vik_layer_get_interface(l->type)->params;
137 VikLayerFuncGetParam get_param = vik_layer_get_interface(l->type)->get_param;
139 fprintf ( f, "name=%s\n", l->name ? l->name : "" );
141 fprintf ( f, "visible=f\n" );
143 if ( params && get_param )
145 VikLayerParamData data;
146 guint16 i, params_count = vik_layer_get_interface(l->type)->params_count;
147 for ( i = 0; i < params_count; i++ )
149 data = get_param(l, i, TRUE);
150 file_write_layer_param(f, params[i].name, params[i].type, data);
153 if ( vik_layer_get_interface(l->type)->write_file_data )
155 fprintf ( f, "\n\n~LayerData\n" );
156 vik_layer_get_interface(l->type)->write_file_data ( l, f );
157 fprintf ( f, "~EndLayerData\n" );
160 write param, and get_value, etc.
161 then run layer data, and that's it.
165 static void file_write ( VikAggregateLayer *top, FILE *f, gpointer vp )
168 VikLayer *current_layer;
170 VikViewportDrawMode mode;
171 gchar *modestring = NULL;
174 stack->data = (gpointer) vik_aggregate_layer_get_children(VIK_AGGREGATE_LAYER(top));
178 vik_coord_to_latlon ( vik_viewport_get_center ( VIK_VIEWPORT(vp) ), &ll );
180 mode = vik_viewport_get_drawmode ( VIK_VIEWPORT(vp) );
182 case VIK_VIEWPORT_DRAWMODE_UTM: modestring = "utm"; break;
183 case VIK_VIEWPORT_DRAWMODE_EXPEDIA: modestring = "expedia"; break;
184 case VIK_VIEWPORT_DRAWMODE_MERCATOR: modestring = "mercator"; break;
185 case VIK_VIEWPORT_DRAWMODE_LATLON: modestring = "latlon"; break;
187 g_critical("Houston, we've had a problem. mode=%d", mode);
190 fprintf ( f, "#VIKING GPS Data file " VIKING_URL "\n" );
191 fprintf ( f, "FILE_VERSION=%d\n", VIKING_FILE_VERSION );
192 fprintf ( f, "\nxmpp=%f\nympp=%f\nlat=%f\nlon=%f\nmode=%s\ncolor=%s\nhighlightcolor=%s\ndrawscale=%s\ndrawcentermark=%s\ndrawhighlight=%s\n",
193 vik_viewport_get_xmpp ( VIK_VIEWPORT(vp) ), vik_viewport_get_ympp ( VIK_VIEWPORT(vp) ), ll.lat, ll.lon,
194 modestring, vik_viewport_get_background_color(VIK_VIEWPORT(vp)),
195 vik_viewport_get_highlight_color(VIK_VIEWPORT(vp)),
196 vik_viewport_get_draw_scale(VIK_VIEWPORT(vp)) ? "t" : "f",
197 vik_viewport_get_draw_centermark(VIK_VIEWPORT(vp)) ? "t" : "f",
198 vik_viewport_get_draw_highlight(VIK_VIEWPORT(vp)) ? "t" : "f" );
200 if ( ! VIK_LAYER(top)->visible )
201 fprintf ( f, "visible=f\n" );
203 while (stack && stack->data)
205 current_layer = VIK_LAYER(((GList *)stack->data)->data);
206 fprintf ( f, "\n~Layer %s\n", vik_layer_get_interface(current_layer->type)->fixed_layer_name );
207 write_layer_params_and_data ( current_layer, f );
208 if ( current_layer->type == VIK_LAYER_AGGREGATE && !vik_aggregate_layer_is_empty(VIK_AGGREGATE_LAYER(current_layer)) )
211 stack->data = (gpointer) vik_aggregate_layer_get_children(VIK_AGGREGATE_LAYER(current_layer));
213 else if ( current_layer->type == VIK_LAYER_GPS && !vik_gps_layer_is_empty(VIK_GPS_LAYER(current_layer)) )
216 stack->data = (gpointer) vik_gps_layer_get_children(VIK_GPS_LAYER(current_layer));
220 stack->data = (gpointer) ((GList *)stack->data)->next;
221 fprintf ( f, "~EndLayer\n\n" );
222 while ( stack && (!stack->data) )
227 stack->data = (gpointer) ((GList *)stack->data)->next;
228 fprintf ( f, "~EndLayer\n\n" );
234 get vikaggregatelayer's children (?)
235 foreach write ALL params,
236 then layer data (IF function exists)
240 stack of layers (LIST) we are working on
241 when layer->next == NULL ...
246 static void string_list_delete ( gpointer key, gpointer l, gpointer user_data )
248 /* 20071021 bugfix */
249 GList *iter = (GList *) l;
251 g_free ( iter->data );
254 g_list_free ( (GList *) l );
257 static void string_list_set_param (gint i, GList *list, gpointer *layer_and_vp)
261 vik_layer_set_param ( VIK_LAYER(layer_and_vp[0]), i, x, layer_and_vp[1], TRUE );
265 * Read in a Viking file and return how successful the parsing was
266 * ATM this will always work, in that even if there are parsing problems
267 * then there will be no new values to override the defaults
269 * TODO flow up line number(s) / error messages of problems encountered...
272 static gboolean file_read ( VikAggregateLayer *top, FILE *f, const gchar *dirpath, VikViewport *vp )
275 struct LatLon ll = { 0.0, 0.0 };
281 VikLayerParam *params = NULL; /* for current layer, so we don't have to keep on looking up interface */
282 guint8 params_count = 0;
284 GHashTable *string_lists = g_hash_table_new(g_direct_hash,g_direct_equal);
286 gboolean successful_read = TRUE;
290 stack->data = (gpointer) top;
292 while ( fgets ( buffer, 4096, f ) )
297 while ( *line == ' ' || *line =='\t' )
300 if ( line[0] == '#' )
305 if ( len > 0 && line[len-1] == '\n' )
307 if ( len > 0 && line[len-1] == '\r' )
314 if ( line[0] == '~' )
319 else if ( str_starts_with ( line, "Layer ", 6, TRUE ) )
321 int parent_type = VIK_LAYER(stack->data)->type;
322 if ( ( ! stack->data ) || ((parent_type != VIK_LAYER_AGGREGATE) && (parent_type != VIK_LAYER_GPS)) )
324 successful_read = FALSE;
325 g_warning ( "Line %ld: Layer command inside non-Aggregate Layer (type %d)", line_num, parent_type );
326 push(&stack); /* inside INVALID layer */
332 VikLayerTypeEnum type = vik_layer_type_from_string ( line+6 );
334 if ( type == VIK_LAYER_NUM_TYPES )
336 successful_read = FALSE;
337 g_warning ( "Line %ld: Unknown type %s", line_num, line+6 );
340 else if (parent_type == VIK_LAYER_GPS)
342 stack->data = (gpointer) vik_gps_layer_get_a_child(VIK_GPS_LAYER(stack->under->data));
343 params = vik_layer_get_interface(type)->params;
344 params_count = vik_layer_get_interface(type)->params_count;
348 stack->data = (gpointer) vik_layer_create ( type, vp, FALSE );
349 params = vik_layer_get_interface(type)->params;
350 params_count = vik_layer_get_interface(type)->params_count;
354 else if ( str_starts_with ( line, "EndLayer", 8, FALSE ) )
356 if ( stack->under == NULL ) {
357 successful_read = FALSE;
358 g_warning ( "Line %ld: Mismatched ~EndLayer command", line_num );
362 /* add any string lists we've accumulated */
363 gpointer layer_and_vp[2];
364 layer_and_vp[0] = stack->data;
365 layer_and_vp[1] = vp;
366 g_hash_table_foreach ( string_lists, (GHFunc) string_list_set_param, layer_and_vp );
367 g_hash_table_remove_all ( string_lists );
369 if ( stack->data && stack->under->data )
371 if (VIK_LAYER(stack->under->data)->type == VIK_LAYER_AGGREGATE) {
372 vik_aggregate_layer_add_layer ( VIK_AGGREGATE_LAYER(stack->under->data), VIK_LAYER(stack->data), FALSE );
373 vik_layer_post_read ( VIK_LAYER(stack->data), vp, TRUE );
375 else if (VIK_LAYER(stack->under->data)->type == VIK_LAYER_GPS) {
376 /* TODO: anything else needs to be done here ? */
379 successful_read = FALSE;
380 g_warning ( "Line %ld: EndLayer command inside non-Aggregate Layer (type %d)", line_num, VIK_LAYER(stack->data)->type );
386 else if ( str_starts_with ( line, "LayerData", 9, FALSE ) )
388 if ( stack->data && vik_layer_get_interface(VIK_LAYER(stack->data)->type)->read_file_data )
390 /* must read until hits ~EndLayerData */
391 if ( ! vik_layer_get_interface(VIK_LAYER(stack->data)->type)->read_file_data ( VIK_LAYER(stack->data), f, dirpath ) )
392 successful_read = FALSE;
395 { /* simply skip layer data over */
396 while ( fgets ( buffer, 4096, f ) )
403 if ( len > 0 && line[len-1] == '\n' )
405 if ( len > 0 && line[len-1] == '\r' )
407 if ( strcasecmp ( line, "~EndLayerData" ) == 0 )
415 successful_read = FALSE;
416 g_warning ( "Line %ld: Unknown tilde command", line_num );
426 for ( i = 0; i < len; i++ )
427 if ( line[i] == '=' )
430 if ( stack->under == NULL && eq_pos == 12 && strncasecmp ( line, "FILE_VERSION", eq_pos ) == 0) {
431 gint version = strtol(line+13, NULL, 10);
432 g_debug ( "%s: reading file version %d", __FUNCTION__, version );
433 if ( version > VIKING_FILE_VERSION )
434 successful_read = FALSE;
435 // However we'll still carry and attempt to read whatever we can
437 else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "xmpp", eq_pos ) == 0) /* "hard coded" params: global & for all layer-types */
438 vik_viewport_set_xmpp ( VIK_VIEWPORT(vp), strtod_i8n ( line+5, NULL ) );
439 else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "ympp", eq_pos ) == 0)
440 vik_viewport_set_ympp ( VIK_VIEWPORT(vp), strtod_i8n ( line+5, NULL ) );
441 else if ( stack->under == NULL && eq_pos == 3 && strncasecmp ( line, "lat", eq_pos ) == 0 )
442 ll.lat = strtod_i8n ( line+4, NULL );
443 else if ( stack->under == NULL && eq_pos == 3 && strncasecmp ( line, "lon", eq_pos ) == 0 )
444 ll.lon = strtod_i8n ( line+4, NULL );
445 else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "utm" ) == 0)
446 vik_viewport_set_drawmode ( VIK_VIEWPORT(vp), VIK_VIEWPORT_DRAWMODE_UTM);
447 else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "expedia" ) == 0)
448 vik_viewport_set_drawmode ( VIK_VIEWPORT(vp), VIK_VIEWPORT_DRAWMODE_EXPEDIA );
449 else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "google" ) == 0)
451 successful_read = FALSE;
452 g_warning ( _("Draw mode '%s' no more supported"), "google" );
454 else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "kh" ) == 0)
456 successful_read = FALSE;
457 g_warning ( _("Draw mode '%s' no more supported"), "kh" );
459 else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "mercator" ) == 0)
460 vik_viewport_set_drawmode ( VIK_VIEWPORT(vp), VIK_VIEWPORT_DRAWMODE_MERCATOR );
461 else if ( stack->under == NULL && eq_pos == 4 && strncasecmp ( line, "mode", eq_pos ) == 0 && strcasecmp ( line+5, "latlon" ) == 0)
462 vik_viewport_set_drawmode ( VIK_VIEWPORT(vp), VIK_VIEWPORT_DRAWMODE_LATLON );
463 else if ( stack->under == NULL && eq_pos == 5 && strncasecmp ( line, "color", eq_pos ) == 0 )
464 vik_viewport_set_background_color ( VIK_VIEWPORT(vp), line+6 );
465 else if ( stack->under == NULL && eq_pos == 14 && strncasecmp ( line, "highlightcolor", eq_pos ) == 0 )
466 vik_viewport_set_highlight_color ( VIK_VIEWPORT(vp), line+15 );
467 else if ( stack->under == NULL && eq_pos == 9 && strncasecmp ( line, "drawscale", eq_pos ) == 0 )
468 vik_viewport_set_draw_scale ( VIK_VIEWPORT(vp), TEST_BOOLEAN(line+10) );
469 else if ( stack->under == NULL && eq_pos == 14 && strncasecmp ( line, "drawcentermark", eq_pos ) == 0 )
470 vik_viewport_set_draw_centermark ( VIK_VIEWPORT(vp), TEST_BOOLEAN(line+15) );
471 else if ( stack->under == NULL && eq_pos == 13 && strncasecmp ( line, "drawhighlight", eq_pos ) == 0 )
472 vik_viewport_set_draw_highlight ( VIK_VIEWPORT(vp), TEST_BOOLEAN(line+14) );
473 else if ( stack->under && eq_pos == 4 && strncasecmp ( line, "name", eq_pos ) == 0 )
474 vik_layer_rename ( VIK_LAYER(stack->data), line+5 );
475 else if ( eq_pos == 7 && strncasecmp ( line, "visible", eq_pos ) == 0 )
476 VIK_LAYER(stack->data)->visible = TEST_BOOLEAN(line+8);
477 else if ( eq_pos != -1 && stack->under )
479 gboolean found_match = FALSE;
481 /* go thru layer params. if len == eq_pos && starts_with jazz, set it. */
482 /* also got to check for name and visible. */
486 successful_read = FALSE;
487 g_warning ( "Line %ld: No options for this kind of layer", line_num );
491 for ( i = 0; i < params_count; i++ )
492 if ( strlen(params[i].name) == eq_pos && strncasecmp ( line, params[i].name, eq_pos ) == 0 )
496 if ( params[i].type == VIK_LAYER_PARAM_STRING_LIST ) {
497 GList *l = g_list_append ( g_hash_table_lookup ( string_lists, GINT_TO_POINTER ((gint) i) ),
499 g_hash_table_replace ( string_lists, GINT_TO_POINTER ((gint)i), l );
500 /* add the value to a list, possibly making a new list.
501 * this will be passed to the layer when we read an ~EndLayer */
503 switch ( params[i].type )
505 case VIK_LAYER_PARAM_DOUBLE: x.d = strtod_i8n(line, NULL); break;
506 case VIK_LAYER_PARAM_UINT: x.u = strtoul(line, NULL, 10); break;
507 case VIK_LAYER_PARAM_INT: x.i = strtol(line, NULL, 10); break;
508 case VIK_LAYER_PARAM_BOOLEAN: x.b = TEST_BOOLEAN(line); break;
509 case VIK_LAYER_PARAM_COLOR: memset(&(x.c), 0, sizeof(x.c)); /* default: black */
510 gdk_color_parse ( line, &(x.c) ); break;
511 /* STRING or STRING_LIST -- if STRING_LIST, just set param to add a STRING */
514 vik_layer_set_param ( VIK_LAYER(stack->data), i, x, vp, TRUE );
519 if ( ! found_match ) {
520 // ATM don't flow up this issue because at least one internal parameter has changed from version 1.3
521 // and don't what to worry users about raising such issues
522 // TODO Maybe hold old values here - compare the line value against them and if a match
523 // generate a different style of message in the GUI...
524 // successful_read = FALSE;
525 g_warning ( "Line %ld: Unknown parameter. Line:\n%s", line_num, line );
529 successful_read = FALSE;
530 g_warning ( "Line %ld: Invalid parameter or parameter outside of layer.", line_num );
544 if ( stack->under && stack->under->data && stack->data )
546 vik_aggregate_layer_add_layer ( VIK_AGGREGATE_LAYER(stack->under->data), VIK_LAYER(stack->data), FALSE );
547 vik_layer_post_read ( VIK_LAYER(stack->data), vp, TRUE );
552 if ( ll.lat != 0.0 || ll.lon != 0.0 )
553 vik_viewport_set_center_latlon ( VIK_VIEWPORT(vp), &ll, TRUE );
555 if ( ( ! VIK_LAYER(top)->visible ) && VIK_LAYER(top)->realized )
556 vik_treeview_item_set_visible ( VIK_LAYER(top)->vt, &(VIK_LAYER(top)->iter), FALSE );
558 /* delete anything we've forgotten about -- should only happen when file ends before an EndLayer */
559 g_hash_table_foreach ( string_lists, string_list_delete, NULL );
560 g_hash_table_destroy ( string_lists );
562 return successful_read;
569 new default layer of type (str_to_type) (check interface->name)
571 VikLayer *vl = stack->data;
573 vik_aggregate_layer_add_layer(stack->data, vl);
575 vik_layer_data ( VIK_LAYER_DATA(stack->data), f, vp );
579 /* ---------------------------------------------------- */
581 static FILE *xfopen ( const char *fn )
583 if ( strcmp(fn,"-") == 0 )
586 return g_fopen(fn, "r");
589 static void xfclose ( FILE *f )
591 if ( f != stdin && f != stdout ) {
598 * Function to determine if a filename is a 'viking' type file
600 gboolean check_file_magic_vik ( const gchar *filename )
602 gboolean result = FALSE;
603 FILE *ff = xfopen ( filename );
605 result = check_magic ( ff, VIK_MAGIC, VIK_MAGIC_LEN );
614 * Append a file extension, if not already present.
616 * Returns: a newly allocated string
618 gchar *append_file_ext ( const gchar *filename, VikFileType_t type )
620 gchar *new_name = NULL;
621 const gchar *ext = NULL;
623 /* Select an extension */
632 case FILE_TYPE_GEOJSON:
635 case FILE_TYPE_GPSMAPPER:
636 case FILE_TYPE_GPSPOINT:
638 /* Do nothing, ext already set to NULL */
643 if ( ext != NULL && ! a_file_check_ext ( filename, ext ) )
644 new_name = g_strconcat ( filename, ext, NULL );
646 /* Simply duplicate */
647 new_name = g_strdup ( filename );
652 VikLoadType_t a_file_load ( VikAggregateLayer *top, VikViewport *vp, VikTrwLayer *vtl, const gchar *filename_or_uri )
654 g_return_val_if_fail ( vp != NULL, LOAD_TYPE_READ_FAILURE );
656 char *filename = (char *)filename_or_uri;
657 if (strncmp(filename, "file://", 7) == 0) {
658 // Consider replacing this with:
659 // filename = g_filename_from_uri ( entry, NULL, NULL );
660 // Since this doesn't support URIs properly (i.e. will failure if is it has %20 characters in it)
661 filename = filename + 7;
662 g_debug ( "Loading file %s from URI %s", filename, filename_or_uri );
664 FILE *f = xfopen ( filename );
667 return LOAD_TYPE_READ_FAILURE;
669 VikLoadType_t load_answer = LOAD_TYPE_OTHER_SUCCESS;
671 gchar *dirpath = g_path_get_dirname ( filename );
672 // Attempt loading the primary file type first - our internal .vik file:
673 if ( check_magic ( f, VIK_MAGIC, VIK_MAGIC_LEN ) )
675 if ( file_read ( top, f, dirpath, vp ) )
676 load_answer = LOAD_TYPE_VIK_SUCCESS;
678 load_answer = LOAD_TYPE_VIK_FAILURE_NON_FATAL;
680 else if ( a_jpg_magic_check ( filename ) ) {
681 if ( ! a_jpg_load_file ( top, filename, vp ) )
682 load_answer = LOAD_TYPE_UNSUPPORTED_FAILURE;
686 // For all other file types which consist of tracks, routes and/or waypoints,
687 // must be loaded into a new TrackWaypoint layer (hence it be created)
688 gboolean success = TRUE; // Detect load failures - mainly to remove the layer created as it's not required
690 // Add to specified layer
691 gboolean add_new = !IS_VIK_TRW_LAYER(vtl);
693 vtl = VIK_TRW_LAYER (vik_layer_create ( VIK_LAYER_TRW, vp, FALSE ));
694 vik_layer_rename ( VIK_LAYER(vtl), a_file_basename ( filename ) );
697 // In fact both kml & gpx files start the same as they are in xml
698 if ( a_file_check_ext ( filename, ".kml" ) && check_magic ( f, GPX_MAGIC, GPX_MAGIC_LEN ) ) {
699 // Implicit Conversion
700 ProcessOptions po = { "-i kml", filename, NULL, NULL, NULL, NULL };
701 if ( ! ( success = a_babel_convert_from ( vtl, &po, NULL, NULL, NULL ) ) ) {
702 load_answer = LOAD_TYPE_GPSBABEL_FAILURE;
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 ( a_file_check_ext ( filename, ".gpx" ) || check_magic ( f, GPX_MAGIC, GPX_MAGIC_LEN ) ) {
708 if ( ! ( success = a_gpx_read_file ( vtl, f ) ) ) {
709 load_answer = LOAD_TYPE_GPX_FAILURE;
713 // Try final supported file type
714 if ( ! ( success = a_gpspoint_read_file ( vtl, f, dirpath ) ) ) {
715 // Failure here means we don't know how to handle the file
716 load_answer = LOAD_TYPE_UNSUPPORTED_FAILURE;
719 // Clean up when we can't handle the file
722 g_object_unref ( vtl );
725 // Complete the setup from the successful load
726 vik_layer_post_read ( VIK_LAYER(vtl), vp, TRUE );
728 vik_aggregate_layer_add_layer ( top, VIK_LAYER(vtl), FALSE );
730 vik_trw_layer_auto_set_view ( vtl, vp );
738 gboolean a_file_save ( VikAggregateLayer *top, gpointer vp, const gchar *filename )
742 if (strncmp(filename, "file://", 7) == 0)
743 filename = filename + 7;
745 f = g_fopen(filename, "w");
750 // Enable relative paths in .vik files to work
751 gchar *cwd = g_get_current_dir();
752 gchar *dir = g_path_get_dirname ( filename );
754 if ( g_chdir ( dir ) ) {
755 g_warning ( "Could not change directory to %s", dir );
760 file_write ( top, f, vp );
762 // Restore previous working directory
764 if ( g_chdir ( cwd ) ) {
765 g_warning ( "Could not return to directory %s", cwd );
778 gboolean is_gpx = a_file_check_ext ( "a/b/c.gpx", ".gpx" );
780 gboolean a_file_check_ext ( const gchar *filename, const gchar *fileext )
782 g_return_val_if_fail ( filename != NULL, FALSE );
783 g_return_val_if_fail ( fileext && fileext[0]=='.', FALSE );
784 const gchar *basename = a_file_basename(filename);
788 const char * dot = strrchr(basename, '.');
789 if (dot && !strcmp(dot, fileext))
797 * @vtl: The TrackWaypoint to export data from
798 * @filename: The name of the file to be written
799 * @file_type: Choose one of the supported file types for the export
800 * @trk: If specified then only export this track rather than the whole layer
801 * @write_hidden: Whether to write invisible items
803 * A general export command to convert from Viking TRW layer data to an external supported format.
804 * The write_hidden option is provided mainly to be able to transfer selected items when uploading to a GPS
806 gboolean a_file_export ( VikTrwLayer *vtl, const gchar *filename, VikFileType_t file_type, VikTrack *trk, gboolean write_hidden )
808 GpxWritingOptions options = { FALSE, FALSE, write_hidden, FALSE };
809 FILE *f = g_fopen ( filename, "w" );
812 gboolean result = TRUE;
815 switch ( file_type ) {
817 // trk defined so can set the option
818 options.is_route = trk->is_route;
819 a_gpx_write_track_file ( trk, f, &options );
822 g_critical("Houston, we've had a problem. file_type=%d", file_type);
825 switch ( file_type ) {
826 case FILE_TYPE_GPSMAPPER:
827 a_gpsmapper_write_file ( vtl, f );
830 a_gpx_write_file ( vtl, f, &options );
832 case FILE_TYPE_GPSPOINT:
833 a_gpspoint_write_file ( vtl, f );
835 case FILE_TYPE_GEOJSON:
836 result = a_geojson_write_file ( vtl, f );
840 switch ( a_vik_get_kml_export_units () ) {
841 case VIK_KML_EXPORT_UNITS_STATUTE:
842 return a_babel_convert_to ( vtl, NULL, "-o kml", filename, NULL, NULL );
844 case VIK_KML_EXPORT_UNITS_NAUTICAL:
845 return a_babel_convert_to ( vtl, NULL, "-o kml,units=n", filename, NULL, NULL );
848 // VIK_KML_EXPORT_UNITS_METRIC:
849 return a_babel_convert_to ( vtl, NULL, "-o kml,units=m", filename, NULL, NULL );
854 g_critical("Houston, we've had a problem. file_type=%d", file_type);
864 * a_file_export_babel:
866 gboolean a_file_export_babel ( VikTrwLayer *vtl, const gchar *filename, const gchar *format,
867 gboolean tracks, gboolean routes, gboolean waypoints )
869 gchar *args = g_strdup_printf("%s %s %s -o %s",
872 waypoints ? "-w" : "",
874 gboolean result = a_babel_convert_to ( vtl, NULL, args, filename, NULL, NULL );
880 * Just a wrapper around realpath, which itself is platform dependent
882 char *file_realpath ( const char *path, char *real )
884 return realpath ( path, real );
888 #define MAXPATHLEN 1024
891 * Always return the canonical filename in a newly allocated string
893 char *file_realpath_dup ( const char *path )
895 char real[MAXPATHLEN];
897 g_return_val_if_fail(path != NULL, NULL);
899 if (file_realpath(path, real))
900 return g_strdup(real);
902 return g_strdup(path);
906 * Permission granted to use this code after personal correspondance
907 * Slightly reworked for better cross platform use, glibisms, function rename and a compacter format
909 * FROM http://www.codeguru.com/cpp/misc/misc/fileanddirectorynaming/article.php/c263
912 // GetRelativeFilename(), by Rob Fisher.
914 // http://come.to/robfisher
916 // The number of characters at the start of an absolute filename. e.g. in DOS,
917 // absolute filenames start with "X:\" so this value should be 3, in UNIX they start
918 // with "\" so this value should be 1.
920 #define ABSOLUTE_NAME_START 3
922 #define ABSOLUTE_NAME_START 1
925 // Given the absolute current directory and an absolute file name, returns a relative file name.
926 // For example, if the current directory is C:\foo\bar and the filename C:\foo\whee\text.txt is given,
927 // GetRelativeFilename will return ..\whee\text.txt.
929 const gchar *file_GetRelativeFilename ( gchar *currentDirectory, gchar *absoluteFilename )
931 gint afMarker = 0, rfMarker = 0;
932 gint cdLen = 0, afLen = 0;
935 static gchar relativeFilename[MAXPATHLEN+1];
937 cdLen = strlen(currentDirectory);
938 afLen = strlen(absoluteFilename);
940 // make sure the names are not too long or too short
941 if (cdLen > MAXPATHLEN || cdLen < ABSOLUTE_NAME_START+1 ||
942 afLen > MAXPATHLEN || afLen < ABSOLUTE_NAME_START+1) {
946 // Handle DOS names that are on different drives:
947 if (currentDirectory[0] != absoluteFilename[0]) {
948 // not on the same drive, so only absolute filename will do
949 g_strlcpy(relativeFilename, absoluteFilename, MAXPATHLEN+1);
950 return relativeFilename;
953 // they are on the same drive, find out how much of the current directory
954 // is in the absolute filename
955 i = ABSOLUTE_NAME_START;
956 while (i < afLen && i < cdLen && currentDirectory[i] == absoluteFilename[i]) {
960 if (i == cdLen && (absoluteFilename[i] == G_DIR_SEPARATOR || absoluteFilename[i-1] == G_DIR_SEPARATOR)) {
961 // the whole current directory name is in the file name,
962 // so we just trim off the current directory name to get the
963 // current file name.
964 if (absoluteFilename[i] == G_DIR_SEPARATOR) {
965 // a directory name might have a trailing slash but a relative
966 // file name should not have a leading one...
970 g_strlcpy(relativeFilename, &absoluteFilename[i], MAXPATHLEN+1);
971 return relativeFilename;
974 // The file is not in a child directory of the current directory, so we
975 // need to step back the appropriate number of parent directories by
976 // using "..\"s. First find out how many levels deeper we are than the
981 // count the number of directory levels we have to go up to get to the
985 if (currentDirectory[i] == G_DIR_SEPARATOR) {
986 // make sure it's not a trailing slash
988 if (currentDirectory[i] != '\0') {
994 // move the absolute filename marker back to the start of the directory name
995 // that it has stopped in.
996 while (afMarker > 0 && absoluteFilename[afMarker-1] != G_DIR_SEPARATOR) {
1000 // check that the result will not be too long
1001 if (levels * 3 + afLen - afMarker > MAXPATHLEN) {
1005 // add the appropriate number of "..\"s.
1007 for (i = 0; i < levels; i++) {
1008 relativeFilename[rfMarker++] = '.';
1009 relativeFilename[rfMarker++] = '.';
1010 relativeFilename[rfMarker++] = G_DIR_SEPARATOR;
1013 // copy the rest of the filename into the result string
1014 strcpy(&relativeFilename[rfMarker], &absoluteFilename[afMarker]);
1016 return relativeFilename;
1018 /* END http://www.codeguru.com/cpp/misc/misc/fileanddirectorynaming/article.php/c263 */