]> git.street.me.uk Git - andy/viking.git/blob - src/gpx.c
f290831fdf27ae95e21e38ec913b0e5c230fb967
[andy/viking.git] / src / gpx.c
1 /*
2  * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
3  *
4  * Copyright (C) 2003-2005, Evan Battaglia <gtoevan@gmx.net>
5  *
6  * Some of the code adapted from GPSBabel 1.2.7
7  * http://gpsbabel.sf.net/
8  * Copyright (C) 2002, 2003, 2004, 2005 Robert Lipe, robertlipe@usa.net
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23  *
24  */
25
26
27 #define _XOPEN_SOURCE /* glibc2 needs this */
28
29 #include "viking.h"
30 #include <expat.h>
31 #include <string.h>
32
33 #define GPX_TIME_FORMAT "%Y-%m-%dT%H:%M:%SZ"
34
35 typedef enum {
36         tt_unknown = 0,
37
38         tt_gpx,
39
40         tt_wpt,
41         tt_wpt_desc,
42         tt_wpt_name,
43         tt_wpt_ele,
44         tt_wpt_sym,
45         tt_wpt_link,            /* New in GPX 1.1 */
46
47         tt_trk,
48         tt_trk_desc,
49         tt_trk_name,
50
51         tt_trk_trkseg,
52         tt_trk_trkseg_trkpt,
53         tt_trk_trkseg_trkpt_ele,
54         tt_trk_trkseg_trkpt_time,
55
56         tt_waypoint,
57         tt_waypoint_coord,
58         tt_waypoint_name,
59 } tag_type;
60
61 typedef struct tag_mapping {
62         tag_type tag_type;              /* enum from above for this tag */
63         const char *tag_name;           /* xpath-ish tag name */
64 } tag_mapping;
65
66 /*
67  * xpath(ish) mappings between full tag paths and internal identifers.
68  * These appear in the order they appear in the GPX specification.
69  * If it's not a tag we explictly handle, it doesn't go here.
70  */
71
72 tag_mapping tag_path_map[] = {
73
74         { tt_wpt, "/gpx/wpt" },
75
76         { tt_waypoint, "/loc/waypoint" },
77         { tt_waypoint_coord, "/loc/waypoint/coord" },
78         { tt_waypoint_name, "/loc/waypoint/name" },
79
80         { tt_wpt_ele, "/gpx/wpt/ele" },
81         { tt_wpt_name, "/gpx/wpt/name" },
82         { tt_wpt_desc, "/gpx/wpt/desc" },
83         { tt_wpt_sym, "/gpx/wpt/sym" },
84         { tt_wpt_link, "/gpx/wpt/link" },                    /* GPX 1.1 */
85
86         { tt_trk, "/gpx/trk" },
87         { tt_trk, "/gpx/rte" },
88         { tt_trk_name, "/gpx/trk/name" },
89         { tt_trk_desc, "/gpx/trk/desc" },
90         { tt_trk_trkseg, "/gpx/trk/trkseg" },
91         { tt_trk_trkseg_trkpt, "/gpx/trk/trkseg/trkpt" },
92         { tt_trk_trkseg_trkpt, "/gpx/rte/rtept" },
93         { tt_trk_trkseg_trkpt_ele, "/gpx/trk/trkseg/trkpt/ele" },
94         { tt_trk_trkseg_trkpt_time, "/gpx/trk/trkseg/trkpt/time" },
95
96         {0}
97 };
98
99 static tag_type get_tag(const char *t)
100 {
101         tag_mapping *tm;
102         for (tm = tag_path_map; tm->tag_type != 0; tm++)
103                 if (0 == strcmp(tm->tag_name, t))
104                         return tm->tag_type;
105         return tt_unknown;
106 }
107
108 /******************************************/
109
110 tag_type current_tag = tt_unknown;
111 GString *xpath = NULL;
112 GString *c_cdata = NULL;
113
114 /* current ("c_") objects */
115 VikTrackpoint *c_tp = NULL;
116 VikWaypoint *c_wp = NULL;
117 VikTrack *c_tr = NULL;
118
119 gchar *c_wp_name = NULL;
120 gchar *c_tr_name = NULL;
121
122 /* temporary things so we don't have to create them lots of times */
123 const gchar *c_slat, *c_slon;
124 struct LatLon c_ll;
125
126 /* specialty flags / etc */
127 gboolean f_tr_newseg;
128 guint unnamed_waypoints = 0;
129 guint unnamed_tracks = 0;
130
131
132 static const char *get_attr ( const char **attr, const char *key )
133 {
134   while ( *attr ) {
135     if ( strcmp(*attr,key) == 0 )
136       return *(attr + 1);
137     attr += 2;
138   }
139   return NULL;
140 }
141
142 static gboolean set_c_ll ( const char **attr )
143 {
144   if ( (c_slat = get_attr ( attr, "lat" )) && (c_slon = get_attr ( attr, "lon" )) ) {
145     c_ll.lat = g_strtod(c_slat, NULL);
146     c_ll.lon = g_strtod(c_slon, NULL);
147     return TRUE;
148   }
149   return FALSE;
150 }
151
152 static void gpx_start(VikTrwLayer *vtl, const char *el, const char **attr)
153 {
154   static const gchar *tmp;
155
156   g_string_append_c ( xpath, '/' );
157   g_string_append ( xpath, el );
158   current_tag = get_tag ( xpath->str );
159
160   switch ( current_tag ) {
161
162      case tt_wpt:
163        if ( set_c_ll( attr ) ) {
164          c_wp = vik_waypoint_new ();
165          c_wp->altitude = VIK_DEFAULT_ALTITUDE;
166          if ( ! get_attr ( attr, "hidden" ) )
167            c_wp->visible = TRUE;
168
169          vik_coord_load_from_latlon ( &(c_wp->coord), vik_trw_layer_get_coord_mode ( vtl ), &c_ll );
170        }
171        break;
172
173      case tt_trk:
174        c_tr = vik_track_new ();
175        if ( ! get_attr ( attr, "hidden" ) )
176          c_tr->visible = TRUE;
177        break;
178
179      case tt_trk_trkseg:
180        f_tr_newseg = TRUE;
181        break;
182
183      case tt_trk_trkseg_trkpt:
184        if ( set_c_ll( attr ) ) {
185          c_tp = vik_trackpoint_new ();
186          c_tp->altitude = VIK_DEFAULT_ALTITUDE;
187          vik_coord_load_from_latlon ( &(c_tp->coord), vik_trw_layer_get_coord_mode ( vtl ), &c_ll );
188          if ( f_tr_newseg ) {
189            c_tp->newsegment = TRUE;
190            f_tr_newseg = FALSE;
191          }
192          c_tr->trackpoints = g_list_append ( c_tr->trackpoints, c_tp );
193        }
194        break;
195
196      case tt_trk_trkseg_trkpt_ele:
197      case tt_trk_trkseg_trkpt_time:
198      case tt_wpt_desc:
199      case tt_wpt_name:
200      case tt_wpt_ele:
201      case tt_wpt_link:
202      case tt_trk_desc:
203      case tt_trk_name:
204        g_string_erase ( c_cdata, 0, -1 ); /* clear the cdata buffer */
205        break;
206
207      case tt_waypoint:
208        c_wp = vik_waypoint_new ();
209        c_wp->altitude = VIK_DEFAULT_ALTITUDE;
210        c_wp->visible = TRUE;
211        break;
212
213      case tt_waypoint_coord:
214        if ( set_c_ll( attr ) )
215          vik_coord_load_from_latlon ( &(c_wp->coord), vik_trw_layer_get_coord_mode ( vtl ), &c_ll );
216        break;
217
218      case tt_waypoint_name:
219        if ( ( tmp = get_attr(attr, "id") ) ) {
220          if ( c_wp_name )
221            g_free ( c_wp_name );
222          c_wp_name = g_strdup ( tmp );
223        }
224        g_string_erase ( c_cdata, 0, -1 ); /* clear the cdata buffer for description */
225        break;
226         
227      default: break;
228   }
229 }
230
231 static void gpx_end(VikTrwLayer *vtl, const char *el)
232 {
233   static struct tm tm;
234   g_string_truncate ( xpath, xpath->len - strlen(el) - 1 );
235
236   switch ( current_tag ) {
237
238      case tt_waypoint:
239      case tt_wpt:
240        if ( ! c_wp_name )
241          c_wp_name = g_strdup_printf("VIKING_WP%d", unnamed_waypoints++);
242        g_hash_table_insert ( vik_trw_layer_get_waypoints ( vtl ), c_wp_name, c_wp );
243        c_wp = NULL;
244        c_wp_name = NULL;
245        break;
246
247      case tt_trk:
248        if ( ! c_tr_name )
249          c_tr_name = g_strdup_printf("VIKING_TR%d", unnamed_waypoints++);
250        g_hash_table_insert ( vik_trw_layer_get_tracks ( vtl ), c_tr_name, c_tr );
251        c_tr = NULL;
252        c_tr_name = NULL;
253        break;
254
255      case tt_wpt_name:
256        if ( c_wp_name )
257          g_free ( c_wp_name );
258        c_wp_name = g_strdup ( c_cdata->str );
259        g_string_erase ( c_cdata, 0, -1 );
260        break;
261
262      case tt_trk_name:
263        if ( c_tr_name )
264          g_free ( c_tr_name );
265        c_tr_name = g_strdup ( c_cdata->str );
266        g_string_erase ( c_cdata, 0, -1 );
267        break;
268
269      case tt_wpt_ele:
270        c_wp->altitude = g_strtod ( c_cdata->str, NULL );
271        g_string_erase ( c_cdata, 0, -1 );
272        break;
273
274      case tt_trk_trkseg_trkpt_ele:
275        c_tp->altitude = g_strtod ( c_cdata->str, NULL );
276        g_string_erase ( c_cdata, 0, -1 );
277        break;
278
279      case tt_waypoint_name: /* .loc name is really description. */
280      case tt_wpt_desc:
281        vik_waypoint_set_comment ( c_wp, c_cdata->str );
282        g_string_erase ( c_cdata, 0, -1 );
283        break;
284
285      case tt_wpt_link:
286        vik_waypoint_set_image ( c_wp, c_cdata->str );
287        g_string_erase ( c_cdata, 0, -1 );
288        break;
289
290      case tt_wpt_sym:
291        vik_waypoint_set_symbol ( c_wp, c_cdata->str );
292        g_string_erase ( c_cdata, 0, -1 );
293        break;
294
295      case tt_trk_desc:
296        vik_track_set_comment ( c_tr, c_cdata->str );
297        g_string_erase ( c_cdata, 0, -1 );
298        break;
299
300      case tt_trk_trkseg_trkpt_time:
301        if ( strptime(c_cdata->str, GPX_TIME_FORMAT, &tm) != c_cdata->str ) { /* it read at least one char */
302          c_tp->timestamp = mktime(&tm);
303          c_tp->has_timestamp = TRUE;
304        }
305        g_string_erase ( c_cdata, 0, -1 );
306        break;
307
308      default: break;
309   }
310
311   current_tag = get_tag ( xpath->str );
312 }
313
314 static void gpx_cdata(void *dta, const XML_Char *s, int len)
315 {
316   switch ( current_tag ) {
317     case tt_wpt_name:
318     case tt_trk_name:
319     case tt_wpt_ele:
320     case tt_trk_trkseg_trkpt_ele:
321     case tt_wpt_desc:
322     case tt_wpt_sym:
323     case tt_wpt_link:
324     case tt_trk_desc:
325     case tt_trk_trkseg_trkpt_time:
326     case tt_waypoint_name: /* .loc name is really description. */
327       g_string_append_len ( c_cdata, s, len );
328       break;
329
330     default: break;  /* ignore cdata from other things */
331   }
332 }
333
334 // make like a "stack" of tag names
335 // like gpspoint's separated like /gpx/wpt/whatever
336
337 void a_gpx_read_file( VikTrwLayer *vtl, FILE *f ) {
338   XML_Parser parser = XML_ParserCreate(NULL);
339   int done=0, len;
340
341   XML_SetElementHandler(parser, (XML_StartElementHandler) gpx_start, (XML_EndElementHandler) gpx_end);
342   XML_SetUserData(parser, vtl); /* in the future we could remove all global variables */
343   XML_SetCharacterDataHandler(parser, (XML_CharacterDataHandler) gpx_cdata);
344
345   gchar buf[4096];
346
347   g_assert ( f != NULL && vtl != NULL );
348
349   xpath = g_string_new ( "" );
350   c_cdata = g_string_new ( "" );
351
352   unnamed_waypoints = 0;
353   unnamed_tracks = 0;
354
355   while (!done) {
356     len = fread(buf, 1, sizeof(buf)-7, f);
357     done = feof(f) || !len;
358     XML_Parse(parser, buf, len, done);
359   }
360  
361   g_string_free ( xpath, TRUE );
362   g_string_free ( c_cdata, TRUE );
363 }
364
365 /**** entitize from GPSBabel ****/
366 typedef struct {
367         const char * text;
368         const char * entity;
369         int  not_html;
370 } entity_types;
371
372 static
373 entity_types stdentities[] =  {
374         { "&",  "&amp;", 0 },
375         { "'",  "&apos;", 1 },
376         { "<",  "&lt;", 0 },
377         { ">",  "&gt;", 0 },
378         { "\"", "&quot;", 0 },
379         { NULL, NULL, 0 }
380 };
381
382 void utf8_to_int( const char *cp, int *bytes, int *value )
383 {
384         if ( (*cp & 0xe0) == 0xc0 ) {
385                 if ( (*(cp+1) & 0xc0) != 0x80 ) goto dodefault;
386                 *bytes = 2;
387                 *value = ((*cp & 0x1f) << 6) |
388                         (*(cp+1) & 0x3f);
389         }
390         else if ( (*cp & 0xf0) == 0xe0 ) {
391                 if ( (*(cp+1) & 0xc0) != 0x80 ) goto dodefault;
392                 if ( (*(cp+2) & 0xc0) != 0x80 ) goto dodefault;
393                 *bytes = 3;
394                 *value = ((*cp & 0x0f) << 12) |
395                         ((*(cp+1) & 0x3f) << 6) |
396                         (*(cp+2) & 0x3f);
397         }
398         else if ( (*cp & 0xf8) == 0xf0 ) {
399                 if ( (*(cp+1) & 0xc0) != 0x80 ) goto dodefault;
400                 if ( (*(cp+2) & 0xc0) != 0x80 ) goto dodefault;
401                 if ( (*(cp+3) & 0xc0) != 0x80 ) goto dodefault;
402                 *bytes = 4;
403                 *value = ((*cp & 0x07) << 18) |
404                         ((*(cp+1) & 0x3f) << 12) |
405                         ((*(cp+2) & 0x3f) << 6) |
406                         (*(cp+3) & 0x3f);
407         }
408         else if ( (*cp & 0xfc) == 0xf8 ) {
409                 if ( (*(cp+1) & 0xc0) != 0x80 ) goto dodefault;
410                 if ( (*(cp+2) & 0xc0) != 0x80 ) goto dodefault;
411                 if ( (*(cp+3) & 0xc0) != 0x80 ) goto dodefault;
412                 if ( (*(cp+4) & 0xc0) != 0x80 ) goto dodefault;
413                 *bytes = 5;
414                 *value = ((*cp & 0x03) << 24) |
415                         ((*(cp+1) & 0x3f) << 18) |
416                         ((*(cp+2) & 0x3f) << 12) |
417                         ((*(cp+3) & 0x3f) << 6) |
418                         (*(cp+4) & 0x3f);
419         }
420         else if ( (*cp & 0xfe) == 0xfc ) {
421                 if ( (*(cp+1) & 0xc0) != 0x80 ) goto dodefault;
422                 if ( (*(cp+2) & 0xc0) != 0x80 ) goto dodefault;
423                 if ( (*(cp+3) & 0xc0) != 0x80 ) goto dodefault;
424                 if ( (*(cp+4) & 0xc0) != 0x80 ) goto dodefault;
425                 if ( (*(cp+5) & 0xc0) != 0x80 ) goto dodefault;
426                 *bytes = 6;
427                 *value = ((*cp & 0x01) << 30) |
428                         ((*(cp+1) & 0x3f) << 24) |
429                         ((*(cp+2) & 0x3f) << 18) |
430                         ((*(cp+3) & 0x3f) << 12) |
431                         ((*(cp+4) & 0x3f) << 6) |
432                         (*(cp+5) & 0x3f);
433         }
434         else {
435 dodefault:
436                 *bytes = 1;
437                 *value = (unsigned char)*cp;
438         }
439 }
440
441 static
442 char *
443 entitize(const char * str)
444 {
445         int elen, ecount, nsecount;
446         entity_types *ep;
447         const char * cp;
448         char * p, * tmp, * xstr;
449
450         char tmpsub[20];
451         int bytes = 0;
452         int value = 0;
453         ep = stdentities;
454         elen = ecount = nsecount = 0;
455
456         /* figure # of entity replacements and additional size. */
457         while (ep->text) {
458                 cp = str;
459                 while ((cp = strstr(cp, ep->text)) != NULL) {
460                         elen += strlen(ep->entity) - strlen(ep->text);
461                         ecount++;
462                         cp += strlen(ep->text);
463                 }
464                 ep++;
465         }
466
467         /* figure the same for other than standard entities (i.e. anything
468          * that isn't in the range U+0000 to U+007F */
469         for ( cp = str; *cp; cp++ ) {
470                 if ( *cp & 0x80 ) {
471
472                         utf8_to_int( cp, &bytes, &value );
473                         cp += bytes-1;
474                         elen += sprintf( tmpsub, "&#x%x;", value ) - bytes;
475                         nsecount++;
476                 }
477         }
478
479         /* enough space for the whole string plus entity replacements, if any */
480         tmp = g_malloc((strlen(str) + elen + 1));
481         strcpy(tmp, str);
482
483         /* no entity replacements */
484         if (ecount == 0 && nsecount == 0)
485                 return (tmp);
486
487         if ( ecount != 0 ) {
488                 for (ep = stdentities; ep->text; ep++) {
489                         p = tmp;
490                         while ((p = strstr(p, ep->text)) != NULL) {
491                                 elen = strlen(ep->entity);
492
493                                 xstr = g_strdup(p + strlen(ep->text));
494
495                                 strcpy(p, ep->entity);
496                                 strcpy(p + elen, xstr);
497
498                                 g_free(xstr);
499
500                                 p += elen;
501                         }
502                 }
503         }
504
505         if ( nsecount != 0 ) {
506                 p = tmp;
507                 while (*p) {
508                         if ( *p & 0x80 ) {
509                                 utf8_to_int( p, &bytes, &value );
510                                 if ( p[bytes] ) {
511                                         xstr = g_strdup( p + bytes );
512                                 }
513                                 else {
514                                         xstr = NULL;
515                                 }
516                                 sprintf( p, "&#x%x;", value );
517                                 p = p+strlen(p);
518                                 if ( xstr ) {
519                                         strcpy( p, xstr );
520                                         g_free(xstr);
521                                 }
522                         }
523                         else {
524                                 p++;
525                         }
526                 }
527         }
528         return (tmp);
529 }
530 /**** end GPSBabel code ****/
531
532 /* export GPX */
533 static void gpx_write_waypoint ( const gchar *name, VikWaypoint *wp, FILE *f ) 
534 {
535   static struct LatLon ll;
536   gchar *tmp;
537   vik_coord_to_latlon ( &(wp->coord), &ll );
538   fprintf ( f, "<wpt lat=\"%f\" lon=\"%f\"%s>\n",
539                ll.lat, ll.lon, wp->visible ? "" : " hidden=\"hidden\"" );
540
541   tmp = entitize ( name );
542   fprintf ( f, "  <name>%s</name>\n", tmp );
543   g_free ( tmp);
544
545   if ( wp->altitude != VIK_DEFAULT_ALTITUDE )
546     fprintf ( f, "  <ele>%f</ele>\n", wp->altitude );
547   if ( wp->comment )
548   {
549     tmp = entitize(wp->comment);
550     fprintf ( f, "  <desc>%s</desc>\n", tmp );
551     g_free ( tmp );
552   }
553   if ( wp->image )
554   {
555     tmp = entitize(wp->image);
556     fprintf ( f, "  <link>%s</link>\n", tmp );
557     g_free ( tmp );
558   }
559   if ( wp->symbol ) 
560   {
561     tmp = entitize(wp->symbol);
562     fprintf ( f, "  <sym>%s</sym>\n", tmp);
563     g_free ( tmp );
564   }
565
566   fprintf ( f, "</wpt>\n" );
567 }
568
569 static void gpx_write_trackpoint ( VikTrackpoint *tp, FILE *f )
570 {
571   static struct LatLon ll;
572   static gchar time_buf[30];
573   vik_coord_to_latlon ( &(tp->coord), &ll );
574
575   if ( tp->newsegment )
576     fprintf ( f, "  </trkseg>\n  <trkseg>\n" );
577
578   fprintf ( f, "  <trkpt lat=\"%f\" lon=\"%f\">\n", ll.lat, ll.lon );
579
580   if ( tp->altitude != VIK_DEFAULT_ALTITUDE )
581     fprintf ( f, "    <ele>%f</ele>\n", tp->altitude );
582   if ( tp->has_timestamp ) {
583     time_buf [ strftime ( time_buf, sizeof(time_buf)-1, GPX_TIME_FORMAT, localtime(&(tp->timestamp)) ) ] = '\0';
584     fprintf ( f, "    <time>%s</time>\n", time_buf );
585   }
586   fprintf ( f, "  </trkpt>\n" );
587 }
588
589
590 static void gpx_write_track ( const gchar *name, VikTrack *t, FILE *f )
591 {
592   gchar *tmp;
593   gboolean first_tp_is_newsegment; /* must temporarily make it not so, but we want to restore state. not that it matters. */
594
595   tmp = entitize ( name );
596   fprintf ( f, "<trk%s>\n  <name>%s</name>\n", t->visible ? "" : " hidden=\"hidden\"", tmp );
597   g_free ( tmp );
598
599   if ( t->comment )
600   {
601     tmp = entitize ( t->comment );
602     fprintf ( f, "  <desc>%s</desc>\n", tmp );
603     g_free ( tmp );
604   }
605
606   fprintf ( f, "  <trkseg>\n" );
607
608   if ( t->trackpoints && t->trackpoints->data ) {
609     first_tp_is_newsegment = VIK_TRACKPOINT(t->trackpoints->data)->newsegment;
610     VIK_TRACKPOINT(t->trackpoints->data)->newsegment = FALSE; /* so we won't write </trkseg><trkseg> already */
611   }
612   g_list_foreach ( t->trackpoints, (GFunc) gpx_write_trackpoint, f );
613   if ( t->trackpoints && t->trackpoints->data )
614     VIK_TRACKPOINT(t->trackpoints->data)->newsegment = first_tp_is_newsegment; /* restore state */
615
616   fprintf ( f, "</trkseg>\n</trk>\n" );
617 }
618
619 void a_gpx_write_file( VikTrwLayer *vtl, FILE *f )
620 {
621   fprintf(f, "<?xml version=\"1.0\"?>\n"
622           "<gpx version=\"1.0\" creator=\"Viking -- http://viking.sf.net/\"\n"
623           "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
624           "xmlns=\"http://www.topografix.com/GPX/1/0\"\n"
625           "xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd\">\n");
626   g_hash_table_foreach ( vik_trw_layer_get_waypoints ( vtl ), (GHFunc) gpx_write_waypoint, f );
627   g_hash_table_foreach ( vik_trw_layer_get_tracks ( vtl ), (GHFunc) gpx_write_track, f );
628   fprintf(f, "</gpx>\n");
629
630
631 }