]> git.street.me.uk Git - andy/viking.git/blob - src/gpx.c
f251e432a19a6e5763be5aac14672482e5896f0d
[andy/viking.git] / src / gpx.c
1 /*
2  * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
3  *
4  * Copyright (C) 2003-2007, Evan Battaglia <gtoevan@gmx.net>
5  * Copyright (C) 2007, Quy Tonthat <qtonthat@gmail.com>
6  * Copyright (C) 2008, Hein Ragas <viking@ragas.nl>
7  * Copyright (C) 2009, Tal B <tal.bav@gmail.com>
8  * Copyright (c) 2012-2014, Rob Norris <rw_norris@hotmail.com>
9  *
10  * Some of the code adapted from GPSBabel 1.2.7
11  * http://gpsbabel.sf.net/
12  * Copyright (C) 2002, 2003, 2004, 2005 Robert Lipe, robertlipe@usa.net
13  *
14  * This program is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation; either version 2 of the License, or
17  * (at your option) any later version.
18  *
19  * This program is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program; if not, write to the Free Software
26  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27  *
28  */
29 #ifdef HAVE_CONFIG_H
30 #include "config.h"
31 #endif
32
33 #define _XOPEN_SOURCE /* glibc2 needs this */
34
35 #include "gpx.h"
36 #include "viking.h"
37 #include <expat.h>
38 #ifdef HAVE_STRING_H
39 #include <string.h>
40 #endif
41 #include <glib.h>
42 #include <glib/gstdio.h>
43 #include <glib/gi18n.h>
44 #ifdef HAVE_MATH_H
45 #include <math.h>
46 #endif
47 #include <time.h>
48
49 typedef enum {
50         tt_unknown = 0,
51
52         tt_gpx,
53         tt_gpx_name,
54         tt_gpx_desc,
55         tt_gpx_author,
56         tt_gpx_time,
57         tt_gpx_keywords,
58
59         tt_wpt,
60         tt_wpt_cmt,
61         tt_wpt_desc,
62         tt_wpt_src,
63         tt_wpt_name,
64         tt_wpt_ele,
65         tt_wpt_sym,
66         tt_wpt_time,
67         tt_wpt_url,
68         tt_wpt_link,            /* New in GPX 1.1 */
69
70         tt_trk,
71         tt_trk_cmt,
72         tt_trk_desc,
73         tt_trk_src,
74         tt_trk_name,
75
76         tt_rte,
77
78         tt_trk_trkseg,
79         tt_trk_trkseg_trkpt,
80         tt_trk_trkseg_trkpt_ele,
81         tt_trk_trkseg_trkpt_time,
82         tt_trk_trkseg_trkpt_name,
83         /* extended */
84         tt_trk_trkseg_trkpt_course,
85         tt_trk_trkseg_trkpt_speed,
86         tt_trk_trkseg_trkpt_fix,
87         tt_trk_trkseg_trkpt_sat,
88
89         tt_trk_trkseg_trkpt_hdop,
90         tt_trk_trkseg_trkpt_vdop,
91         tt_trk_trkseg_trkpt_pdop,
92
93         tt_waypoint,
94         tt_waypoint_coord,
95         tt_waypoint_name,
96 } tag_type;
97
98 typedef struct tag_mapping {
99         tag_type tag_type;              /* enum from above for this tag */
100         const char *tag_name;           /* xpath-ish tag name */
101 } tag_mapping;
102
103 typedef struct {
104         GpxWritingOptions *options;
105         FILE *file;
106 } GpxWritingContext;
107
108 /*
109  * xpath(ish) mappings between full tag paths and internal identifiers.
110  * These appear in the order they appear in the GPX specification.
111  * If it's not a tag we explicitly handle, it doesn't go here.
112  */
113
114 tag_mapping tag_path_map[] = {
115
116         { tt_gpx, "/gpx" },
117         { tt_gpx_name, "/gpx/name" },
118         { tt_gpx_desc, "/gpx/desc" },
119         { tt_gpx_time, "/gpx/time" },
120         { tt_gpx_author, "/gpx/author" },
121         { tt_gpx_keywords, "/gpx/keywords" },
122
123         // GPX 1.1 variant - basic properties moved into metadata namespace
124         { tt_gpx_name, "/gpx/metadata/name" },
125         { tt_gpx_desc, "/gpx/metadata/desc" },
126         { tt_gpx_time, "/gpx/metadata/time" },
127         { tt_gpx_author, "/gpx/metadata/author" },
128         { tt_gpx_keywords, "/gpx/metadata/keywords" },
129
130         { tt_wpt, "/gpx/wpt" },
131
132         { tt_waypoint, "/loc/waypoint" },
133         { tt_waypoint_coord, "/loc/waypoint/coord" },
134         { tt_waypoint_name, "/loc/waypoint/name" },
135
136         { tt_wpt_ele, "/gpx/wpt/ele" },
137         { tt_wpt_time, "/gpx/wpt/time" },
138         { tt_wpt_name, "/gpx/wpt/name" },
139         { tt_wpt_cmt, "/gpx/wpt/cmt" },
140         { tt_wpt_desc, "/gpx/wpt/desc" },
141         { tt_wpt_src, "/gpx/wpt/src" },
142         { tt_wpt_sym, "/gpx/wpt/sym" },
143         { tt_wpt_sym, "/loc/waypoint/type" },
144         { tt_wpt_url, "/gpx/wpt/url" },
145         { tt_wpt_link, "/gpx/wpt/link" },                    /* GPX 1.1 */
146
147         { tt_trk, "/gpx/trk" },
148         { tt_trk_name, "/gpx/trk/name" },
149         { tt_trk_cmt, "/gpx/trk/cmt" },
150         { tt_trk_desc, "/gpx/trk/desc" },
151         { tt_trk_src, "/gpx/trk/src" },
152         { tt_trk_trkseg, "/gpx/trk/trkseg" },
153         { tt_trk_trkseg_trkpt, "/gpx/trk/trkseg/trkpt" },
154         { tt_trk_trkseg_trkpt_ele, "/gpx/trk/trkseg/trkpt/ele" },
155         { tt_trk_trkseg_trkpt_time, "/gpx/trk/trkseg/trkpt/time" },
156         { tt_trk_trkseg_trkpt_name, "/gpx/trk/trkseg/trkpt/name" },
157         /* extended */
158         { tt_trk_trkseg_trkpt_course, "/gpx/trk/trkseg/trkpt/course" },
159         { tt_trk_trkseg_trkpt_speed, "/gpx/trk/trkseg/trkpt/speed" },
160         { tt_trk_trkseg_trkpt_fix, "/gpx/trk/trkseg/trkpt/fix" },
161         { tt_trk_trkseg_trkpt_sat, "/gpx/trk/trkseg/trkpt/sat" },
162
163         { tt_trk_trkseg_trkpt_hdop, "/gpx/trk/trkseg/trkpt/hdop" },
164         { tt_trk_trkseg_trkpt_vdop, "/gpx/trk/trkseg/trkpt/vdop" },
165         { tt_trk_trkseg_trkpt_pdop, "/gpx/trk/trkseg/trkpt/pdop" },
166
167         { tt_rte, "/gpx/rte" },
168         // NB Route reuses track point feature tags
169         { tt_trk_name, "/gpx/rte/name" },
170         { tt_trk_cmt, "/gpx/rte/cmt" },
171         { tt_trk_desc, "/gpx/rte/desc" },
172         { tt_trk_src, "/gpx/rte/src" },
173         { tt_trk_trkseg_trkpt, "/gpx/rte/rtept" },
174         { tt_trk_trkseg_trkpt_name, "/gpx/rte/rtept/name" },
175         { tt_trk_trkseg_trkpt_ele, "/gpx/rte/rtept/ele" },
176
177         {0}
178 };
179
180 static tag_type get_tag(const char *t)
181 {
182         tag_mapping *tm;
183         for (tm = tag_path_map; tm->tag_type != 0; tm++)
184                 if (0 == strcmp(tm->tag_name, t))
185                         return tm->tag_type;
186         return tt_unknown;
187 }
188
189 /******************************************/
190
191 tag_type current_tag = tt_unknown;
192 GString *xpath = NULL;
193 GString *c_cdata = NULL;
194
195 /* current ("c_") objects */
196 VikTrackpoint *c_tp = NULL;
197 VikWaypoint *c_wp = NULL;
198 VikTrack *c_tr = NULL;
199 VikTRWMetadata *c_md = NULL;
200
201 gchar *c_wp_name = NULL;
202 gchar *c_tr_name = NULL;
203
204 /* temporary things so we don't have to create them lots of times */
205 const gchar *c_slat, *c_slon;
206 struct LatLon c_ll;
207
208 /* specialty flags / etc */
209 gboolean f_tr_newseg;
210 guint unnamed_waypoints = 0;
211 guint unnamed_tracks = 0;
212 guint unnamed_routes = 0;
213
214 static const char *get_attr ( const char **attr, const char *key )
215 {
216   while ( *attr ) {
217     if ( strcmp(*attr,key) == 0 )
218       return *(attr + 1);
219     attr += 2;
220   }
221   return NULL;
222 }
223
224 static gboolean set_c_ll ( const char **attr )
225 {
226   if ( (c_slat = get_attr ( attr, "lat" )) && (c_slon = get_attr ( attr, "lon" )) ) {
227     c_ll.lat = g_ascii_strtod(c_slat, NULL);
228     c_ll.lon = g_ascii_strtod(c_slon, NULL);
229     return TRUE;
230   }
231   return FALSE;
232 }
233
234 static void gpx_start(VikTrwLayer *vtl, const char *el, const char **attr)
235 {
236   static const gchar *tmp;
237
238   g_string_append_c ( xpath, '/' );
239   g_string_append ( xpath, el );
240   current_tag = get_tag ( xpath->str );
241
242   switch ( current_tag ) {
243
244      case tt_gpx:
245        c_md = vik_trw_metadata_new();
246        break;
247
248      case tt_wpt:
249        if ( set_c_ll( attr ) ) {
250          c_wp = vik_waypoint_new ();
251          c_wp->visible = TRUE;
252          if ( get_attr ( attr, "hidden" ) )
253            c_wp->visible = FALSE;
254
255          vik_coord_load_from_latlon ( &(c_wp->coord), vik_trw_layer_get_coord_mode ( vtl ), &c_ll );
256        }
257        break;
258
259      case tt_trk:
260      case tt_rte:
261        c_tr = vik_track_new ();
262        vik_track_set_defaults ( c_tr );
263        c_tr->is_route = (current_tag == tt_rte) ? TRUE : FALSE;
264        c_tr->visible = TRUE;
265        if ( get_attr ( attr, "hidden" ) )
266          c_tr->visible = FALSE;
267        break;
268
269      case tt_trk_trkseg:
270        f_tr_newseg = TRUE;
271        break;
272
273      case tt_trk_trkseg_trkpt:
274        if ( set_c_ll( attr ) ) {
275          c_tp = vik_trackpoint_new ();
276          vik_coord_load_from_latlon ( &(c_tp->coord), vik_trw_layer_get_coord_mode ( vtl ), &c_ll );
277          if ( f_tr_newseg ) {
278            c_tp->newsegment = TRUE;
279            f_tr_newseg = FALSE;
280          }
281          c_tr->trackpoints = g_list_append ( c_tr->trackpoints, c_tp );
282        }
283        break;
284
285      case tt_gpx_name:
286      case tt_gpx_author:
287      case tt_gpx_desc:
288      case tt_gpx_keywords:
289      case tt_gpx_time:
290      case tt_trk_trkseg_trkpt_name:
291      case tt_trk_trkseg_trkpt_ele:
292      case tt_trk_trkseg_trkpt_time:
293      case tt_wpt_cmt:
294      case tt_wpt_desc:
295      case tt_wpt_src:
296      case tt_wpt_name:
297      case tt_wpt_ele:
298      case tt_wpt_time:
299      case tt_wpt_url:
300      case tt_wpt_link:
301      case tt_trk_cmt:
302      case tt_trk_desc:
303      case tt_trk_src:
304      case tt_trk_name:
305        g_string_erase ( c_cdata, 0, -1 ); /* clear the cdata buffer */
306        break;
307
308      case tt_waypoint:
309        c_wp = vik_waypoint_new ();
310        c_wp->visible = TRUE;
311        break;
312
313      case tt_waypoint_coord:
314        if ( set_c_ll( attr ) )
315          vik_coord_load_from_latlon ( &(c_wp->coord), vik_trw_layer_get_coord_mode ( vtl ), &c_ll );
316        break;
317
318      case tt_waypoint_name:
319        if ( ( tmp = get_attr(attr, "id") ) ) {
320          if ( c_wp_name )
321            g_free ( c_wp_name );
322          c_wp_name = g_strdup ( tmp );
323        }
324        g_string_erase ( c_cdata, 0, -1 ); /* clear the cdata buffer for description */
325        break;
326         
327      default: break;
328   }
329 }
330
331 static void gpx_end(VikTrwLayer *vtl, const char *el)
332 {
333   static GTimeVal tp_time;
334   static GTimeVal wp_time;
335
336   g_string_truncate ( xpath, xpath->len - strlen(el) - 1 );
337
338   switch ( current_tag ) {
339
340      case tt_gpx:
341        vik_trw_layer_set_metadata ( vtl, c_md );
342        c_md = NULL;
343        break;
344
345      case tt_gpx_name:
346        vik_layer_rename ( VIK_LAYER(vtl), c_cdata->str );
347        g_string_erase ( c_cdata, 0, -1 );
348        break;
349
350      case tt_gpx_author:
351        if ( c_md->author )
352          g_free ( c_md->author );
353        c_md->author = g_strdup ( c_cdata->str );
354        g_string_erase ( c_cdata, 0, -1 );
355        break;
356
357      case tt_gpx_desc:
358        if ( c_md->description )
359          g_free ( c_md->description );
360        c_md->description = g_strdup ( c_cdata->str );
361        g_string_erase ( c_cdata, 0, -1 );
362        break;
363
364      case tt_gpx_keywords:
365        if ( c_md->keywords )
366          g_free ( c_md->keywords );
367        c_md->keywords = g_strdup ( c_cdata->str );
368        g_string_erase ( c_cdata, 0, -1 );
369        break;
370
371      case tt_gpx_time:
372        if ( c_md->timestamp )
373          g_free ( c_md->timestamp );
374        c_md->timestamp = g_strdup ( c_cdata->str );
375        g_string_erase ( c_cdata, 0, -1 );
376        break;
377
378      case tt_waypoint:
379      case tt_wpt:
380        if ( ! c_wp_name )
381          c_wp_name = g_strdup_printf("VIKING_WP%04d", unnamed_waypoints++);
382        vik_trw_layer_filein_add_waypoint ( vtl, c_wp_name, c_wp );
383        g_free ( c_wp_name );
384        c_wp = NULL;
385        c_wp_name = NULL;
386        break;
387
388      case tt_trk:
389        if ( ! c_tr_name )
390          c_tr_name = g_strdup_printf("VIKING_TR%03d", unnamed_tracks++);
391        // Delibrate fall through
392      case tt_rte:
393        if ( ! c_tr_name )
394          c_tr_name = g_strdup_printf("VIKING_RT%03d", unnamed_routes++);
395        vik_trw_layer_filein_add_track ( vtl, c_tr_name, c_tr );
396        g_free ( c_tr_name );
397        c_tr = NULL;
398        c_tr_name = NULL;
399        break;
400
401      case tt_wpt_name:
402        if ( c_wp_name )
403          g_free ( c_wp_name );
404        c_wp_name = g_strdup ( c_cdata->str );
405        g_string_erase ( c_cdata, 0, -1 );
406        break;
407
408      case tt_trk_name:
409        if ( c_tr_name )
410          g_free ( c_tr_name );
411        c_tr_name = g_strdup ( c_cdata->str );
412        g_string_erase ( c_cdata, 0, -1 );
413        break;
414
415      case tt_wpt_ele:
416        c_wp->altitude = g_ascii_strtod ( c_cdata->str, NULL );
417        g_string_erase ( c_cdata, 0, -1 );
418        break;
419
420      case tt_trk_trkseg_trkpt_ele:
421        c_tp->altitude = g_ascii_strtod ( c_cdata->str, NULL );
422        g_string_erase ( c_cdata, 0, -1 );
423        break;
424
425      case tt_waypoint_name: /* .loc name is really description. */
426      case tt_wpt_desc:
427        vik_waypoint_set_description ( c_wp, c_cdata->str );
428        g_string_erase ( c_cdata, 0, -1 );
429        break;
430
431      case tt_wpt_cmt:
432        vik_waypoint_set_comment ( c_wp, c_cdata->str );
433        g_string_erase ( c_cdata, 0, -1 );
434        break;
435
436      case tt_wpt_src:
437        vik_waypoint_set_source ( c_wp, c_cdata->str );
438        g_string_erase ( c_cdata, 0, -1 );
439        break;
440
441      case tt_wpt_url:
442        vik_waypoint_set_url ( c_wp, c_cdata->str );
443        g_string_erase ( c_cdata, 0, -1 );
444        break;
445
446      case tt_wpt_link:
447        vik_waypoint_set_image ( c_wp, c_cdata->str );
448        g_string_erase ( c_cdata, 0, -1 );
449        break;
450
451      case tt_wpt_sym: {
452        vik_waypoint_set_symbol ( c_wp, c_cdata->str );
453        g_string_erase ( c_cdata, 0, -1 );
454        break;
455        }
456
457      case tt_trk_desc:
458        vik_track_set_description ( c_tr, c_cdata->str );
459        g_string_erase ( c_cdata, 0, -1 );
460        break;
461
462      case tt_trk_src:
463        vik_track_set_source ( c_tr, c_cdata->str );
464        g_string_erase ( c_cdata, 0, -1 );
465        break;
466
467      case tt_trk_cmt:
468        vik_track_set_comment ( c_tr, c_cdata->str );
469        g_string_erase ( c_cdata, 0, -1 );
470        break;
471
472      case tt_wpt_time:
473        if ( g_time_val_from_iso8601(c_cdata->str, &wp_time) ) {
474          c_wp->timestamp = wp_time.tv_sec;
475          c_wp->has_timestamp = TRUE;
476        }
477        g_string_erase ( c_cdata, 0, -1 );
478        break;
479
480      case tt_trk_trkseg_trkpt_name:
481        vik_trackpoint_set_name ( c_tp, c_cdata->str );
482        g_string_erase ( c_cdata, 0, -1 );
483        break;
484
485      case tt_trk_trkseg_trkpt_time:
486        if ( g_time_val_from_iso8601(c_cdata->str, &tp_time) ) {
487          c_tp->timestamp = tp_time.tv_sec;
488          c_tp->has_timestamp = TRUE;
489        }
490        g_string_erase ( c_cdata, 0, -1 );
491        break;
492
493      case tt_trk_trkseg_trkpt_course:
494        c_tp->course = g_ascii_strtod ( c_cdata->str, NULL );
495        g_string_erase ( c_cdata, 0, -1 );
496        break;
497
498      case tt_trk_trkseg_trkpt_speed:
499        c_tp->speed = g_ascii_strtod ( c_cdata->str, NULL );
500        g_string_erase ( c_cdata, 0, -1 );
501        break;
502
503      case tt_trk_trkseg_trkpt_fix:
504        if (!strcmp("2d", c_cdata->str))
505          c_tp->fix_mode = VIK_GPS_MODE_2D;
506        else if (!strcmp("3d", c_cdata->str))
507          c_tp->fix_mode = VIK_GPS_MODE_3D;
508        else if (!strcmp("dgps", c_cdata->str))
509          c_tp->fix_mode = VIK_GPS_MODE_DGPS;
510        else if (!strcmp("pps", c_cdata->str))
511          c_tp->fix_mode = VIK_GPS_MODE_PPS;
512        else
513          c_tp->fix_mode = VIK_GPS_MODE_NOT_SEEN;
514        g_string_erase ( c_cdata, 0, -1 );
515        break;
516
517      case tt_trk_trkseg_trkpt_sat:
518        c_tp->nsats = atoi ( c_cdata->str );
519        g_string_erase ( c_cdata, 0, -1 );
520        break;
521
522      case tt_trk_trkseg_trkpt_hdop:
523        c_tp->hdop = g_strtod ( c_cdata->str, NULL );
524        g_string_erase ( c_cdata, 0, -1 );
525        break;
526
527      case tt_trk_trkseg_trkpt_vdop:
528        c_tp->vdop = g_strtod ( c_cdata->str, NULL );
529        g_string_erase ( c_cdata, 0, -1 );
530        break;
531
532      case tt_trk_trkseg_trkpt_pdop:
533        c_tp->pdop = g_strtod ( c_cdata->str, NULL );
534        g_string_erase ( c_cdata, 0, -1 );
535        break;
536
537      default: break;
538   }
539
540   current_tag = get_tag ( xpath->str );
541 }
542
543 static void gpx_cdata(void *dta, const XML_Char *s, int len)
544 {
545   switch ( current_tag ) {
546     case tt_gpx_name:
547     case tt_gpx_author:
548     case tt_gpx_desc:
549     case tt_gpx_keywords:
550     case tt_gpx_time:
551     case tt_wpt_name:
552     case tt_trk_name:
553     case tt_wpt_ele:
554     case tt_trk_trkseg_trkpt_ele:
555     case tt_wpt_cmt:
556     case tt_wpt_desc:
557     case tt_wpt_src:
558     case tt_wpt_sym:
559     case tt_wpt_url:
560     case tt_wpt_link:
561     case tt_trk_cmt:
562     case tt_trk_desc:
563     case tt_trk_src:
564     case tt_trk_trkseg_trkpt_time:
565     case tt_wpt_time:
566     case tt_trk_trkseg_trkpt_name:
567     case tt_trk_trkseg_trkpt_course:
568     case tt_trk_trkseg_trkpt_speed:
569     case tt_trk_trkseg_trkpt_fix:
570     case tt_trk_trkseg_trkpt_sat:
571     case tt_trk_trkseg_trkpt_hdop:
572     case tt_trk_trkseg_trkpt_vdop:
573     case tt_trk_trkseg_trkpt_pdop:
574     case tt_waypoint_name: /* .loc name is really description. */
575       g_string_append_len ( c_cdata, s, len );
576       break;
577
578     default: break;  /* ignore cdata from other things */
579   }
580 }
581
582 // make like a "stack" of tag names
583 // like gpspoint's separated like /gpx/wpt/whatever
584
585 gboolean a_gpx_read_file( VikTrwLayer *vtl, FILE *f ) {
586   XML_Parser parser = XML_ParserCreate(NULL);
587   int done=0, len;
588   enum XML_Status status = XML_STATUS_ERROR;
589
590   XML_SetElementHandler(parser, (XML_StartElementHandler) gpx_start, (XML_EndElementHandler) gpx_end);
591   XML_SetUserData(parser, vtl); /* in the future we could remove all global variables */
592   XML_SetCharacterDataHandler(parser, (XML_CharacterDataHandler) gpx_cdata);
593
594   gchar buf[4096];
595
596   g_assert ( f != NULL && vtl != NULL );
597
598   xpath = g_string_new ( "" );
599   c_cdata = g_string_new ( "" );
600
601   unnamed_waypoints = 1;
602   unnamed_tracks = 1;
603   unnamed_routes = 1;
604
605   while (!done) {
606     len = fread(buf, 1, sizeof(buf)-7, f);
607     done = feof(f) || !len;
608     status = XML_Parse(parser, buf, len, done);
609   }
610  
611   XML_ParserFree (parser);
612   g_string_free ( xpath, TRUE );
613   g_string_free ( c_cdata, TRUE );
614
615   return status != XML_STATUS_ERROR;
616 }
617
618 /**** entitize from GPSBabel ****/
619 typedef struct {
620         const char * text;
621         const char * entity;
622         int  not_html;
623 } entity_types;
624
625 static
626 entity_types stdentities[] =  {
627         { "&",  "&amp;", 0 },
628         { "'",  "&apos;", 1 },
629         { "<",  "&lt;", 0 },
630         { ">",  "&gt;", 0 },
631         { "\"", "&quot;", 0 },
632         { NULL, NULL, 0 }
633 };
634
635 void utf8_to_int( const char *cp, int *bytes, int *value )
636 {
637         if ( (*cp & 0xe0) == 0xc0 ) {
638                 if ( (*(cp+1) & 0xc0) != 0x80 ) goto dodefault;
639                 *bytes = 2;
640                 *value = ((*cp & 0x1f) << 6) |
641                         (*(cp+1) & 0x3f);
642         }
643         else if ( (*cp & 0xf0) == 0xe0 ) {
644                 if ( (*(cp+1) & 0xc0) != 0x80 ) goto dodefault;
645                 if ( (*(cp+2) & 0xc0) != 0x80 ) goto dodefault;
646                 *bytes = 3;
647                 *value = ((*cp & 0x0f) << 12) |
648                         ((*(cp+1) & 0x3f) << 6) |
649                         (*(cp+2) & 0x3f);
650         }
651         else if ( (*cp & 0xf8) == 0xf0 ) {
652                 if ( (*(cp+1) & 0xc0) != 0x80 ) goto dodefault;
653                 if ( (*(cp+2) & 0xc0) != 0x80 ) goto dodefault;
654                 if ( (*(cp+3) & 0xc0) != 0x80 ) goto dodefault;
655                 *bytes = 4;
656                 *value = ((*cp & 0x07) << 18) |
657                         ((*(cp+1) & 0x3f) << 12) |
658                         ((*(cp+2) & 0x3f) << 6) |
659                         (*(cp+3) & 0x3f);
660         }
661         else if ( (*cp & 0xfc) == 0xf8 ) {
662                 if ( (*(cp+1) & 0xc0) != 0x80 ) goto dodefault;
663                 if ( (*(cp+2) & 0xc0) != 0x80 ) goto dodefault;
664                 if ( (*(cp+3) & 0xc0) != 0x80 ) goto dodefault;
665                 if ( (*(cp+4) & 0xc0) != 0x80 ) goto dodefault;
666                 *bytes = 5;
667                 *value = ((*cp & 0x03) << 24) |
668                         ((*(cp+1) & 0x3f) << 18) |
669                         ((*(cp+2) & 0x3f) << 12) |
670                         ((*(cp+3) & 0x3f) << 6) |
671                         (*(cp+4) & 0x3f);
672         }
673         else if ( (*cp & 0xfe) == 0xfc ) {
674                 if ( (*(cp+1) & 0xc0) != 0x80 ) goto dodefault;
675                 if ( (*(cp+2) & 0xc0) != 0x80 ) goto dodefault;
676                 if ( (*(cp+3) & 0xc0) != 0x80 ) goto dodefault;
677                 if ( (*(cp+4) & 0xc0) != 0x80 ) goto dodefault;
678                 if ( (*(cp+5) & 0xc0) != 0x80 ) goto dodefault;
679                 *bytes = 6;
680                 *value = ((*cp & 0x01) << 30) |
681                         ((*(cp+1) & 0x3f) << 24) |
682                         ((*(cp+2) & 0x3f) << 18) |
683                         ((*(cp+3) & 0x3f) << 12) |
684                         ((*(cp+4) & 0x3f) << 6) |
685                         (*(cp+5) & 0x3f);
686         }
687         else {
688 dodefault:
689                 *bytes = 1;
690                 *value = (unsigned char)*cp;
691         }
692 }
693
694 static
695 char *
696 entitize(const char * str)
697 {
698         int elen, ecount, nsecount;
699         entity_types *ep;
700         const char * cp;
701         char * p, * tmp, * xstr;
702
703         char tmpsub[20];
704         int bytes = 0;
705         int value = 0;
706         ep = stdentities;
707         elen = ecount = nsecount = 0;
708
709         /* figure # of entity replacements and additional size. */
710         while (ep->text) {
711                 cp = str;
712                 while ((cp = strstr(cp, ep->text)) != NULL) {
713                         elen += strlen(ep->entity) - strlen(ep->text);
714                         ecount++;
715                         cp += strlen(ep->text);
716                 }
717                 ep++;
718         }
719
720         /* figure the same for other than standard entities (i.e. anything
721          * that isn't in the range U+0000 to U+007F */
722         for ( cp = str; *cp; cp++ ) {
723                 if ( *cp & 0x80 ) {
724
725                         utf8_to_int( cp, &bytes, &value );
726                         cp += bytes-1;
727                         elen += sprintf( tmpsub, "&#x%x;", value ) - bytes;
728                         nsecount++;
729                 }
730         }
731
732         /* enough space for the whole string plus entity replacements, if any */
733         tmp = g_malloc((strlen(str) + elen + 1));
734         strcpy(tmp, str);
735
736         /* no entity replacements */
737         if (ecount == 0 && nsecount == 0)
738                 return (tmp);
739
740         if ( ecount != 0 ) {
741                 for (ep = stdentities; ep->text; ep++) {
742                         p = tmp;
743                         while ((p = strstr(p, ep->text)) != NULL) {
744                                 elen = strlen(ep->entity);
745
746                                 xstr = g_strdup(p + strlen(ep->text));
747
748                                 strcpy(p, ep->entity);
749                                 strcpy(p + elen, xstr);
750
751                                 g_free(xstr);
752
753                                 p += elen;
754                         }
755                 }
756         }
757
758         if ( nsecount != 0 ) {
759                 p = tmp;
760                 while (*p) {
761                         if ( *p & 0x80 ) {
762                                 utf8_to_int( p, &bytes, &value );
763                                 if ( p[bytes] ) {
764                                         xstr = g_strdup( p + bytes );
765                                 }
766                                 else {
767                                         xstr = NULL;
768                                 }
769                                 sprintf( p, "&#x%x;", value );
770                                 p = p+strlen(p);
771                                 if ( xstr ) {
772                                         strcpy( p, xstr );
773                                         g_free(xstr);
774                                 }
775                         }
776                         else {
777                                 p++;
778                         }
779                 }
780         }
781         return (tmp);
782 }
783 /**** end GPSBabel code ****/
784
785 /* export GPX */
786
787 static void gpx_write_waypoint ( VikWaypoint *wp, GpxWritingContext *context )
788 {
789   // Don't write invisible waypoints when specified
790   if (context->options && !context->options->hidden && !wp->visible)
791     return;
792
793   FILE *f = context->file;
794   static struct LatLon ll;
795   gchar *s_lat,*s_lon;
796   gchar *tmp;
797   vik_coord_to_latlon ( &(wp->coord), &ll );
798   s_lat = a_coords_dtostr( ll.lat );
799   s_lon = a_coords_dtostr( ll.lon );
800   // NB 'hidden' is not part of any GPX standard - this appears to be a made up Viking 'extension'
801   //  luckily most other GPX processing software ignores things they don't understand
802   fprintf ( f, "<wpt lat=\"%s\" lon=\"%s\"%s>\n",
803                s_lat, s_lon, wp->visible ? "" : " hidden=\"hidden\"" );
804   g_free ( s_lat );
805   g_free ( s_lon );
806
807   // Sanity clause
808   if ( wp->name )
809     tmp = entitize ( wp->name );
810   else
811     tmp = g_strdup ("waypoint");
812
813   fprintf ( f, "  <name>%s</name>\n", tmp );
814   g_free ( tmp);
815
816   if ( wp->altitude != VIK_DEFAULT_ALTITUDE )
817   {
818     tmp = a_coords_dtostr ( wp->altitude );
819     fprintf ( f, "  <ele>%s</ele>\n", tmp );
820     g_free ( tmp );
821   }
822
823   if ( wp->has_timestamp ) {
824     GTimeVal timestamp;
825     timestamp.tv_sec = wp->timestamp;
826     timestamp.tv_usec = 0;
827
828     gchar *time_iso8601 = g_time_val_to_iso8601 ( &timestamp );
829     if ( time_iso8601 != NULL )
830       fprintf ( f, "  <time>%s</time>\n", time_iso8601 );
831     g_free ( time_iso8601 );
832   }
833
834   if ( wp->comment )
835   {
836     tmp = entitize(wp->comment);
837     fprintf ( f, "  <cmt>%s</cmt>\n", tmp );
838     g_free ( tmp );
839   }
840   if ( wp->description )
841   {
842     tmp = entitize(wp->description);
843     fprintf ( f, "  <desc>%s</desc>\n", tmp );
844     g_free ( tmp );
845   }
846   if ( wp->source )
847   {
848     tmp = entitize(wp->source);
849     fprintf ( f, "  <src>%s</src>\n", tmp );
850     g_free ( tmp );
851   }
852   if ( wp->url )
853   {
854     tmp = entitize(wp->url);
855     fprintf ( f, "  <url>%s</url>\n", tmp );
856     g_free ( tmp );
857   }
858   if ( wp->image )
859   {
860     tmp = entitize(wp->image);
861     fprintf ( f, "  <link>%s</link>\n", tmp );
862     g_free ( tmp );
863   }
864   if ( wp->symbol ) 
865   {
866     tmp = entitize(wp->symbol);
867     if ( a_vik_gpx_export_wpt_sym_name ( ) ) {
868        // Lowercase the symbol name
869        gchar *tmp2 = g_utf8_strdown ( tmp, -1 );
870        fprintf ( f, "  <sym>%s</sym>\n",  tmp2 );
871        g_free ( tmp2 );
872     }
873     else
874       fprintf ( f, "  <sym>%s</sym>\n", tmp);
875     g_free ( tmp );
876   }
877
878   fprintf ( f, "</wpt>\n" );
879 }
880
881 static void gpx_write_trackpoint ( VikTrackpoint *tp, GpxWritingContext *context )
882 {
883   FILE *f = context->file;
884   static struct LatLon ll;
885   gchar *s_lat,*s_lon, *s_alt, *s_dop;
886   gchar *time_iso8601;
887   vik_coord_to_latlon ( &(tp->coord), &ll );
888
889   // No such thing as a rteseg! So make sure we don't put them in
890   if ( context->options && !context->options->is_route && tp->newsegment )
891     fprintf ( f, "  </trkseg>\n  <trkseg>\n" );
892
893   s_lat = a_coords_dtostr( ll.lat );
894   s_lon = a_coords_dtostr( ll.lon );
895   fprintf ( f, "  <%spt lat=\"%s\" lon=\"%s\">\n", (context->options && context->options->is_route) ? "rte" : "trk", s_lat, s_lon );
896   g_free ( s_lat ); s_lat = NULL;
897   g_free ( s_lon ); s_lon = NULL;
898
899   if (tp->name) {
900     gchar *s_name = entitize(tp->name);
901     fprintf ( f, "    <name>%s</name>\n", s_name );
902     g_free(s_name);
903   }
904
905   s_alt = NULL;
906   if ( tp->altitude != VIK_DEFAULT_ALTITUDE )
907   {
908     s_alt = a_coords_dtostr ( tp->altitude );
909   }
910   else if ( context->options != NULL && context->options->force_ele )
911   {
912     s_alt = a_coords_dtostr ( 0 );
913   }
914   if (s_alt != NULL)
915     fprintf ( f, "    <ele>%s</ele>\n", s_alt );
916   g_free ( s_alt ); s_alt = NULL;
917   
918   time_iso8601 = NULL;
919   if ( tp->has_timestamp ) {
920     GTimeVal timestamp;
921     timestamp.tv_sec = tp->timestamp;
922     timestamp.tv_usec = 0;
923   
924     time_iso8601 = g_time_val_to_iso8601 ( &timestamp );
925   }
926   else if ( context->options != NULL && context->options->force_time )
927   {
928     GTimeVal current;
929     g_get_current_time ( &current );
930   
931     time_iso8601 = g_time_val_to_iso8601 ( &current );
932   }
933   if ( time_iso8601 != NULL )
934     fprintf ( f, "    <time>%s</time>\n", time_iso8601 );
935   g_free(time_iso8601);
936   time_iso8601 = NULL;
937   
938   if (!isnan(tp->course)) {
939     gchar *s_course = a_coords_dtostr(tp->course);
940     fprintf ( f, "    <course>%s</course>\n", s_course );
941     g_free(s_course);
942   }
943   if (!isnan(tp->speed)) {
944     gchar *s_speed = a_coords_dtostr(tp->speed);
945     fprintf ( f, "    <speed>%s</speed>\n", s_speed );
946     g_free(s_speed);
947   }
948   if (tp->fix_mode == VIK_GPS_MODE_2D)
949     fprintf ( f, "    <fix>2d</fix>\n");
950   if (tp->fix_mode == VIK_GPS_MODE_3D)
951     fprintf ( f, "    <fix>3d</fix>\n");
952   if (tp->fix_mode == VIK_GPS_MODE_DGPS)
953     fprintf ( f, "    <fix>dgps</fix>\n");
954   if (tp->fix_mode == VIK_GPS_MODE_PPS)
955     fprintf ( f, "    <fix>pps</fix>\n");
956   if (tp->nsats > 0)
957     fprintf ( f, "    <sat>%d</sat>\n", tp->nsats );
958
959   s_dop = NULL;
960   if ( tp->hdop != VIK_DEFAULT_DOP )
961   {
962     s_dop = a_coords_dtostr ( tp->hdop );
963   }
964   if (s_dop != NULL)
965     fprintf ( f, "    <hdop>%s</hdop>\n", s_dop );
966   g_free ( s_dop ); s_dop = NULL;
967
968   if ( tp->vdop != VIK_DEFAULT_DOP )
969   {
970     s_dop = a_coords_dtostr ( tp->vdop );
971   }
972   if (s_dop != NULL)
973     fprintf ( f, "    <vdop>%s</vdop>\n", s_dop );
974   g_free ( s_dop ); s_dop = NULL;
975
976   if ( tp->pdop != VIK_DEFAULT_DOP )
977   {
978     s_dop = a_coords_dtostr ( tp->pdop );
979   }
980   if (s_dop != NULL)
981     fprintf ( f, "    <pdop>%s</pdop>\n", s_dop );
982   g_free ( s_dop ); s_dop = NULL;
983
984   fprintf ( f, "  </%spt>\n", (context->options && context->options->is_route) ? "rte" : "trk" );
985 }
986
987
988 static void gpx_write_track ( VikTrack *t, GpxWritingContext *context )
989 {
990   // Don't write invisible tracks when specified
991   if (context->options && !context->options->hidden && !t->visible)
992     return;
993
994   FILE *f = context->file;
995   gchar *tmp;
996   gboolean first_tp_is_newsegment = FALSE; /* must temporarily make it not so, but we want to restore state. not that it matters. */
997
998   // Sanity clause
999   if ( t->name )
1000     tmp = entitize ( t->name );
1001   else
1002     tmp = g_strdup ("track");
1003
1004   // NB 'hidden' is not part of any GPX standard - this appears to be a made up Viking 'extension'
1005   //  luckily most other GPX processing software ignores things they don't understand
1006   fprintf ( f, "<%s%s>\n  <name>%s</name>\n",
1007             t->is_route ? "rte" : "trk",
1008             t->visible ? "" : " hidden=\"hidden\"",
1009             tmp );
1010   g_free ( tmp );
1011
1012   if ( t->comment )
1013   {
1014     tmp = entitize ( t->comment );
1015     fprintf ( f, "  <cmt>%s</cmt>\n", tmp );
1016     g_free ( tmp );
1017   }
1018
1019   if ( t->description )
1020   {
1021     tmp = entitize ( t->description );
1022     fprintf ( f, "  <desc>%s</desc>\n", tmp );
1023     g_free ( tmp );
1024   }
1025
1026   if ( t->source )
1027   {
1028     tmp = entitize ( t->source );
1029     fprintf ( f, "  <src>%s</src>\n", tmp );
1030     g_free ( tmp );
1031   }
1032
1033   /* No such thing as a rteseg! */
1034   if ( !t->is_route )
1035     fprintf ( f, "  <trkseg>\n" );
1036
1037   if ( t->trackpoints && t->trackpoints->data ) {
1038     first_tp_is_newsegment = VIK_TRACKPOINT(t->trackpoints->data)->newsegment;
1039     VIK_TRACKPOINT(t->trackpoints->data)->newsegment = FALSE; /* so we won't write </trkseg><trkseg> already */
1040     g_list_foreach ( t->trackpoints, (GFunc) gpx_write_trackpoint, context );
1041     VIK_TRACKPOINT(t->trackpoints->data)->newsegment = first_tp_is_newsegment; /* restore state */
1042   }
1043
1044   /* NB apparently no such thing as a rteseg! */
1045   if (!t->is_route)
1046     fprintf ( f, "  </trkseg>\n");
1047
1048   fprintf ( f, "</%s>\n", t->is_route ? "rte" : "trk" );
1049 }
1050
1051 static void gpx_write_header( FILE *f )
1052 {
1053   fprintf(f, "<?xml version=\"1.0\"?>\n"
1054           "<gpx version=\"1.0\" creator=\"Viking -- http://viking.sf.net/\"\n"
1055           "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
1056           "xmlns=\"http://www.topografix.com/GPX/1/0\"\n"
1057           "xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd\">\n");
1058 }
1059
1060 static void gpx_write_footer( FILE *f )
1061 {
1062   fprintf(f, "</gpx>\n");
1063 }
1064
1065 static int gpx_waypoint_compare(const void *x, const void *y)
1066 {
1067   VikWaypoint *a = (VikWaypoint *)x;
1068   VikWaypoint *b = (VikWaypoint *)y;
1069   return strcmp(a->name,b->name);
1070 }
1071
1072 static int gpx_track_compare_name(const void *x, const void *y)
1073 {
1074   VikTrack *a = (VikTrack *)x;
1075   VikTrack *b = (VikTrack *)y;
1076   return strcmp(a->name,b->name);
1077 }
1078
1079 void a_gpx_write_file ( VikTrwLayer *vtl, FILE *f, GpxWritingOptions *options )
1080 {
1081   GpxWritingContext context = { options, f };
1082
1083   gpx_write_header ( f );
1084
1085   gchar *tmp;
1086   const gchar *name = vik_layer_get_name(VIK_LAYER(vtl));
1087   if ( name ) {
1088     tmp = entitize ( name );
1089     fprintf ( f, "  <name>%s</name>\n", tmp );
1090     g_free ( tmp );
1091   }
1092
1093   VikTRWMetadata *md = vik_trw_layer_get_metadata (vtl);
1094   if ( md ) {
1095     if ( md->author ) {
1096       tmp = entitize ( md->author );
1097       fprintf ( f, "  <author>%s</author>\n", tmp );
1098       g_free ( tmp );
1099     }
1100     if ( md->description ) {
1101       tmp = entitize ( md->description );
1102       fprintf ( f, "  <desc>%s</desc>\n", tmp );
1103       g_free ( tmp );
1104     }
1105     if ( md->timestamp ) {
1106       tmp = entitize ( md->timestamp );
1107       fprintf ( f, "  <time>%s</time>\n", tmp );
1108       g_free ( tmp );
1109     }
1110     if ( md->keywords ) {
1111       tmp = entitize ( md->keywords );
1112       fprintf ( f, "  <keywords>%s</keywords>\n", tmp );
1113       g_free ( tmp );
1114     }
1115   }
1116
1117   if ( vik_trw_layer_get_waypoints_visibility(vtl) || (options && options->hidden) ) {
1118     // gather waypoints in a list, then sort
1119     GList *gl = g_hash_table_get_values ( vik_trw_layer_get_waypoints ( vtl ) );
1120     gl = g_list_sort ( gl, gpx_waypoint_compare );
1121
1122     for (GList *iter = g_list_first (gl); iter != NULL; iter = g_list_next (iter)) {
1123       gpx_write_waypoint ( (VikWaypoint*)iter->data, &context );
1124     }
1125     g_list_free ( gl );
1126   }
1127
1128   GList *gl = NULL;
1129   if ( vik_trw_layer_get_tracks_visibility(vtl) || (options && options->hidden) ) {
1130     //gl = g_hash_table_get_values ( vik_trw_layer_get_tracks ( vtl ) );
1131     // Forming the list manually seems to produce one that is more likely to be nearer to the creation order
1132     gpointer key, value;
1133     GHashTableIter ght_iter;
1134     g_hash_table_iter_init ( &ght_iter, vik_trw_layer_get_tracks ( vtl ) );
1135     while ( g_hash_table_iter_next (&ght_iter, &key, &value) ) {
1136       gl = g_list_prepend ( gl ,value );
1137     }
1138     gl = g_list_reverse ( gl );
1139
1140     // Sort method determined by preference
1141     if ( a_vik_get_gpx_export_trk_sort() == VIK_GPX_EXPORT_TRK_SORT_TIME )
1142       gl = g_list_sort ( gl, vik_track_compare_timestamp );
1143     else if ( a_vik_get_gpx_export_trk_sort() == VIK_GPX_EXPORT_TRK_SORT_ALPHA )
1144       gl = g_list_sort ( gl, gpx_track_compare_name );
1145   }
1146
1147   GList *glrte = NULL;
1148   // Routes sorted by name
1149   if ( vik_trw_layer_get_routes_visibility(vtl) || (options && options->hidden) ) {
1150     glrte = g_hash_table_get_values ( vik_trw_layer_get_routes ( vtl ) );
1151     glrte = g_list_sort ( glrte, gpx_track_compare_name );
1152   }
1153
1154   // g_list_concat doesn't copy memory properly
1155   // so process each list separately
1156
1157   GpxWritingContext context_tmp = context;
1158   GpxWritingOptions opt_tmp = { FALSE, FALSE, FALSE, FALSE };
1159   // Force trackpoints on tracks
1160   if ( !context.options )
1161     context_tmp.options = &opt_tmp;
1162   context_tmp.options->is_route = FALSE;
1163
1164   // Loop around each list and write each one
1165   for (GList *iter = g_list_first (gl); iter != NULL; iter = g_list_next (iter)) {
1166     gpx_write_track ( (VikTrack*)iter->data, &context_tmp );
1167   }
1168
1169   // Routes (to get routepoints)
1170   context_tmp.options->is_route = TRUE;
1171   for (GList *iter = g_list_first (glrte); iter != NULL; iter = g_list_next (iter)) {
1172     gpx_write_track ( (VikTrack*)iter->data, &context_tmp );
1173   }
1174
1175   g_list_free ( gl );
1176   g_list_free ( glrte );
1177
1178   gpx_write_footer ( f );
1179 }
1180
1181 void a_gpx_write_track_file ( VikTrack *trk, FILE *f, GpxWritingOptions *options )
1182 {
1183   GpxWritingContext context = {options, f};
1184   gpx_write_header ( f );
1185   gpx_write_track ( trk, &context );
1186   gpx_write_footer ( f );
1187 }
1188
1189 /**
1190  * Common write of a temporary GPX file
1191  */
1192 static gchar* write_tmp_file ( VikTrwLayer *vtl, VikTrack *trk, GpxWritingOptions *options )
1193 {
1194         gchar *tmp_filename = NULL;
1195         GError *error = NULL;
1196         // Opening temporary file
1197         int fd = g_file_open_tmp("viking_XXXXXX.gpx", &tmp_filename, &error);
1198         if (fd < 0) {
1199                 g_warning ( _("failed to open temporary file: %s"), error->message );
1200                 g_clear_error ( &error );
1201                 return NULL;
1202         }
1203         g_debug ("%s: temporary file = %s", __FUNCTION__, tmp_filename);
1204
1205         FILE *ff = fdopen (fd, "w");
1206
1207         if ( trk )
1208                 a_gpx_write_track_file ( trk, ff, options );
1209         else
1210                 a_gpx_write_file ( vtl, ff, options );
1211
1212         fclose (ff);
1213
1214         return tmp_filename;
1215 }
1216
1217 /*
1218  * a_gpx_write_tmp_file:
1219  * @vtl:     The #VikTrwLayer to write
1220  * @options: Possible ways of writing the file data (can be NULL)
1221  *
1222  * Returns: The name of newly created temporary GPX file
1223  *          This file should be removed once used and the string freed.
1224  *          If NULL then the process failed.
1225  */
1226 gchar* a_gpx_write_tmp_file ( VikTrwLayer *vtl, GpxWritingOptions *options )
1227 {
1228         return write_tmp_file ( vtl, NULL, options );
1229 }
1230
1231 /*
1232  * a_gpx_write_track_tmp_file:
1233  * @trk:     The #VikTrack to write
1234  * @options: Possible ways of writing the file data (can be NULL)
1235  *
1236  * Returns: The name of newly created temporary GPX file
1237  *          This file should be removed once used and the string freed.
1238  *          If NULL then the process failed.
1239  */
1240 gchar* a_gpx_write_track_tmp_file ( VikTrack *trk, GpxWritingOptions *options )
1241 {
1242         return write_tmp_file ( NULL, trk, options );
1243 }