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