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