2 * This file is part of mapper
4 * Copyright (C) 2008 Kaj-Michael Lang
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include <libxml/parser.h>
26 #include <libgnomevfs/gnome-vfs.h>
35 struct sql_select_stmt {
36 sqlite3_stmt *select_paths;
37 sqlite3_stmt *select_path_nodes;
39 sqlite3_stmt *insert_path;
40 sqlite3_stmt *insert_path_node;
42 sqlite3_stmt *delete_path;
43 sqlite3_stmt *delete_path_nodes;
45 static struct sql_select_stmt sql;
47 #define PATH_TABLE_PATHS "create table IF NOT EXISTS paths ( \
48 nid int primary key, \
53 #define PATH_TABLE_NODES "create table IF NOT EXISTS path_nodes ( \
63 name text default null, \
67 NEW_POINT, /* A new point was appended to track track */
68 NEW_BREAK, /* A break was appended to the track */
69 NEW_WAYPOINT, /* A new waypoint/marker has been added */
70 NEAR_WAYPOINT, /* We are near the next route waypoint, announce it */
71 REACHED_WAYPOINT, /* We have reached the next route waypoint, announce it */
72 REACHED_DESTINATION, /* We have reached the last route waypoint */
73 CLEARED, /* Path was cleared */
76 static guint32 signals[LAST_SIGNAL] = {0};
78 /** This enum defines the states of the SAX parsing state machine. */
86 INSIDE_PATH_POINT_ELE,
87 INSIDE_PATH_POINT_TIME,
88 INSIDE_PATH_POINT_DESC,
89 INSIDE_PATH_POINT_NAME,
95 /** Data used during the SAX parsing operation. */
96 typedef struct _SaxData SaxData;
102 gboolean at_least_one_trkpt;
106 static gchar XML_TZONE[7];
108 G_DEFINE_TYPE(Path, path, G_TYPE_OBJECT);
110 #define GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), PATH_TYPE, PathPrivate))
113 path_dispose(GObject *object)
115 g_debug("path_dispose");
117 G_OBJECT_CLASS(path_parent_class)->dispose(object);
121 path_finalize(GObject *object)
123 Path *path=PATH(object);
125 g_debug("path_finalize");
126 MACRO_PATH_FREE(*path);
133 g_free(path->author);
135 g_free(path->keywords);
137 g_free(path->copyright);
143 path_class_init(PathClass *klass)
145 GObjectClass *object_class=G_OBJECT_CLASS(klass);
147 g_debug("path_class_init");
149 object_class->dispose=path_dispose;
150 object_class->finalize=path_finalize;
151 /* g_type_class_add_private (klass, sizeof(PathPrivate)); */
153 signals[NEW_POINT]=g_signal_new("new-point", G_OBJECT_CLASS_TYPE(object_class),
154 G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET(PathClass, new_point),
155 NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, NULL);
156 signals[NEW_BREAK]=g_signal_new("new-break", G_OBJECT_CLASS_TYPE(object_class),
157 G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET(PathClass, new_break),
158 NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, NULL);
159 signals[NEW_WAYPOINT]=g_signal_new("new-waypoint", G_OBJECT_CLASS_TYPE(object_class),
160 G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET(PathClass, new_waypoint),
161 NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, NULL);
165 path_init(Path *path)
167 g_debug("path_init");
168 MACRO_PATH_INIT(*path);
172 path_new(PathType type, guint id)
175 static time_t time1=0;
178 p=g_object_new(PATH_TYPE, NULL);
185 localtime_r(&time1, &time2);
186 g_snprintf(XML_TZONE, sizeof(XML_TZONE), "%+03ld:%02ld", (time2.tm_gmtoff / 60 / 60), (time2.tm_gmtoff / 60) % 60);
193 path_free(Path *path)
195 g_return_if_fail(path);
196 g_object_unref(path);
200 path_clear(Path *path)
202 g_return_if_fail(path);
203 MACRO_PATH_FREE(*path);
204 path->length=path->avgspeed=0.0;
209 path_resize(Path *path, guint size)
211 g_return_val_if_fail(path, FALSE);
213 if (path->head + size != path->cap) {
215 Point *old_head = path->head;
217 path->head = g_renew(Point, old_head, size);
218 g_assert(path->head);
219 path->cap = path->head + size;
220 if (path->head != old_head) {
221 path->tail = path->head + (path->tail - old_head);
223 /* Adjust all of the waypoints. */
224 for (curr = path->whead - 1; curr++ != path->wtail;)
225 curr->point = path->head + (curr->point - old_head);
233 path_wresize(Path *path, guint wsize)
235 g_return_val_if_fail(path, FALSE);
237 if (path->whead + wsize != path->wcap) {
238 WayPoint *old_whead = path->whead;
240 path->whead = g_renew(WayPoint, old_whead, wsize);
241 path->wtail = path->whead + (path->wtail - old_whead);
242 path->wcap = path->whead + wsize;
256 * Append a waypoint to path at given lat, lon with description desc.
261 path_add_waypoint(Path *path, gdouble lat, gdouble lon, gchar *desc)
265 latlon2unit(lat, lon, unitx, unity);
266 MACRO_PATH_INCREMENT_TAIL(*path);
267 path->tail->unitx=unitx;
268 path->tail->unity=unity;
270 path->tail->altitude=NAN;
272 MACRO_PATH_INCREMENT_WTAIL(*path);
273 path->wtail->point=path->tail;
274 path->wtail->desc=desc;
276 path_find_nearest_point(path);
278 g_signal_emit(G_OBJECT(path), signals[NEW_WAYPOINT], 0, NULL);
288 * Append a point using given gps data. Adds a path break if gps is not valid.
290 * Returns: TRUE if the new point was added. FALSE is returned if new point distance was under sensitivity setting.
293 path_add_point(Path *path, GpsData *gps)
297 g_return_val_if_fail(path, FALSE);
300 path_add_break(path);
304 return path_add_latlon(path, gps->lat, gps->lon, gps->time, gps->speed, gps->altitude);
316 * Append a point with given lat,lon,ptime,speed and altitude to given path.
318 * Returns: TRUE if the new point was added. FALSE is returned if new point distance was under sensitivity setting.
321 path_add_latlon(Path *path, gdouble lat, gdouble lon, time_t ptime, gfloat speed, gfloat altitude)
325 latlon2unit(lat, lon, unitx, unity);
327 if (abs((gint)unitx-path->tail->unitx) > path->sensitivity || abs((gint)unity-path->tail->unity) > path->sensitivity) {
328 if (path->tail->unity && path->tail->unitx) {
331 unit2latlon(path->tail->unitx, path->tail->unity, lat, lon);
332 path->length+=calculate_distance(plat, plon, lat, lon);
334 MACRO_PATH_INCREMENT_TAIL(*path);
335 path->tail->unitx=unitx;
336 path->tail->unity=unity;
337 path->tail->time=ptime;
338 path->tail->altitude=altitude;
339 if (speed>path->maxspeed)
340 path->maxspeed=speed;
342 path->avgspeed=(path->points>0) ? path->tspeed/path->points : 0.0;
344 g_debug("TRACK: %f %f (%d)", path->length, path->avgspeed, path->points);
346 g_signal_emit(G_OBJECT(path), signals[NEW_POINT], 0, NULL);
358 * Add a break point to the path.
360 * Returns: TRUE if break was added, FALSE if last point was a break already.
363 path_add_break(Path *path)
365 g_return_val_if_fail(path, FALSE);
366 g_return_val_if_fail(path->tail, FALSE);
368 if (path->tail->unity && path->tail->unitx) {
369 /* To mark a "break" in a track, we'll add a (0, 0) point and then
370 another instance of the most recent track point. */
372 MACRO_PATH_INCREMENT_TAIL(*path);
373 *path->tail=_point_null;
374 MACRO_PATH_INCREMENT_TAIL(*path);
375 *path->tail=path->tail[-2];
377 g_signal_emit(G_OBJECT(path), signals[NEW_BREAK], 0, NULL);
388 * Checks if given path has any path points
390 * Returns: TRUE if there are points, FALSE otherwise
393 path_has_points(Path *path)
395 g_return_val_if_fail(path, FALSE);
396 return path->head==path->tail ? FALSE : TRUE;
400 * path_has_waypoints:
402 * Checks if given path has any waypoints
404 * Returns: TRUE if there are waypoints, FALSE otherwise
407 path_has_waypoints(Path *path)
409 g_return_val_if_fail(path, FALSE);
410 return path->whead==path->wtail ? FALSE : TRUE;
414 * path_find_last_point:
417 * Returns: The last path point or NULL if path is empty
420 path_find_last_point(Path *path)
424 g_return_val_if_fail(path, NULL);
426 if (!path_has_points(path))
429 for (p=path->tail; !p->unity; p--) {
435 * Updates near_point, next_way, and next_wpt. If quick is FALSE (as
436 * it is when this function is called from route_find_nearest_point), then
437 * the entire list (starting from near_point) is searched. Otherwise, we
438 * stop searching when we find a point that is farther away.
441 path_update_nears(Path *path, Point *point, gboolean quick)
443 gboolean ret = FALSE;
445 WayPoint *wcurr, *wnext;
446 guint64 near_dist_squared;
448 g_return_val_if_fail(path, FALSE);
450 /* If we have waypoints (_next_way != NULL), then determine the "next
451 * waypoint", which is defined as the waypoint after the nearest point,
452 * UNLESS we've passed that waypoint, in which case the waypoint after
453 * that waypoint becomes the "next" waypoint. */
454 if (path->next_way) {
455 /* First, set near_dist_squared with the new distance from
457 near = path->near_point;
458 near_dist_squared = DISTANCE_SQUARED(*point, *near);
460 /* Now, search path for a closer point. If quick is TRUE, then we'll
461 * only search forward, only as long as we keep finding closer points.
463 for (curr = path->near_point; curr++ != path->tail;) {
465 guint dist_squared = DISTANCE_SQUARED(*point, *curr);
466 if (dist_squared <= near_dist_squared) {
468 near_dist_squared = dist_squared;
474 /* Update _near_point. */
475 path->near_point = near;
476 path->near_point_dist_squared = near_dist_squared;
478 for (wnext = wcurr = path->next_way; wcurr != path->wtail; wcurr++) {
479 if (wcurr->point < near || (wcurr->point == near && quick
480 && (path->next_wpt && (DISTANCE_SQUARED(*point, *near) > path->next_way_dist_squared
481 && DISTANCE_SQUARED(*point, *path->next_wpt) < path->next_wpt_dist_squared))))
482 /* Okay, this else if expression warrants explanation. If the
483 * nearest track point happens to be a waypoint, then we want to
484 * check if we have "passed" that waypoint. To check this, we
485 * test the distance from _gps to the waypoint and from _gps to
486 * _next_wpt, and if the former is increasing and the latter is
487 * decreasing, then we have passed the waypoint, and thus we
488 * should skip it. Note that if there is no _next_wpt, then
489 * there is no next waypoint, so we do not skip it in that case. */
495 if (wnext == path->wtail && (wnext->point < near || (wnext->point == near && quick
496 && (path->next_wpt && (DISTANCE_SQUARED (*point, *near) > path->next_way_dist_squared
497 && DISTANCE_SQUARED(*point, *path->next_wpt) < path->next_wpt_dist_squared)))))
499 path->next_way = NULL;
500 path->next_wpt = NULL;
501 path->next_way_dist_squared = -1;
502 path->next_wpt_dist_squared = -1;
505 /* Only update next_way (and consequently _next_wpt) if _next_way is
506 * different, and record that fact for return. */
508 if (!quick || path->next_way != wnext) {
509 path->next_way = wnext;
510 path->next_wpt = wnext->point;
511 if (path->next_wpt == path->tail)
512 path->next_wpt = NULL;
514 while (!(++path->next_wpt)->unity) {
515 if (path->next_wpt == path->tail) {
516 path->next_wpt = NULL;
523 path->next_way_dist_squared = DISTANCE_SQUARED(*point, *wnext->point);
525 path->next_wpt_dist_squared = DISTANCE_SQUARED(*point, *path->next_wpt);
532 * path_find_nearest_point:
534 * Reset the near_point data by searching the entire path for the nearest point and waypoint.
537 path_find_nearest_point(Path *path)
539 g_return_if_fail(path);
541 /* Initialize near_point to first non-zero point. */
542 path->near_point=path->head;
543 while (!path->near_point->unity && path->near_point != path->tail)
546 /* Initialize next_way */
547 if (path->wtail==path->whead)
550 path->next_way=path->whead;
551 path->next_way_dist_squared=-1;
553 /* Initialize next_wpt */
555 path->next_wpt_dist_squared=-1;
560 * path_find_nearest_waypoint:
564 path_find_nearest_waypoint(Path *path, guint unitx, guint unity)
568 guint64 nearest_squared;
569 Point pos = { unitx, unity, 0, NAN };
571 g_return_val_if_fail(path, NULL);
573 wcurr=wnear=path->whead;
574 if (wcurr && wcurr->point && wcurr!=path->wtail) {
575 nearest_squared=DISTANCE_SQUARED(pos, *(wcurr->point));
577 while (wcurr++!=path->wtail) {
578 guint64 test_squared=DISTANCE_SQUARED(pos, *(wcurr->point));
579 if (test_squared < nearest_squared) {
581 nearest_squared=test_squared;
586 if (wnear && wnear->point) {
587 if (abs(unitx - wnear->point->unitx) < path->sensitivity && abs(unity - wnear->point->unity) < path->sensitivity)
595 * path_check_waypoint_announce:
599 * Check if we should announce upcoming waypoint.
603 path_check_waypoint_announce(Path *path, GpsData *gps)
605 guint a_thres_near, a_thres_at;
607 g_return_if_fail(path);
608 g_return_if_fail(gps);
613 a_thres_near=(20+(guint)gps->speed)*path->announce_notice_ratio*3;
614 a_thres_at=(20+(guint)gps->speed);
616 if (path->next_way_dist_squared<(a_thres_near * a_thres_near) && path->next_way!=path->announced_waypoint) {
617 g_signal_emit(G_OBJECT(path), signals[NEAR_WAYPOINT], 0, NULL);
618 path->announced_waypoint=path->next_way;
619 } else if (path->next_way_dist_squared<(a_thres_at * a_thres_at) && path->next_way!=path->announced_waypoint) {
620 g_signal_emit(G_OBJECT(path), signals[REACHED_WAYPOINT], 0, NULL);
621 path->announced_waypoint=path->next_way;
625 /******************************************************************************/
628 path_get_distance_to(Path *path, Point *point, gdouble lat, gdouble lon)
630 gdouble lat1, lon1, lat2, lon2;
633 g_return_val_if_fail(path, 0.0);
635 /* If point is NULL, use the next waypoint. */
636 if (point == NULL && path->next_way)
637 point = path->next_way->point;
639 /* If point is still NULL, return an error. */
646 if (point > path->near_point) {
648 /* Skip _near_point in case we have already passed it. */
649 for (curr = path->near_point + 1; curr <= point; ++curr) {
651 unit2latlon(curr->unitx, curr->unity, lat2, lon2);
652 sum += calculate_distance(lat1, lon1, lat2, lon2);
657 } else if (point < path->near_point) {
659 /* Skip near_point in case we have already passed it. */
660 for (curr = path->near_point - 1; curr >= point; --curr) {
662 unit2latlon(curr->unitx, curr->unity, lat2, lon2);
663 sum += calculate_distance(lat1, lon1, lat2, lon2);
669 /* Waypoint _is_ the nearest point. */
670 unit2latlon(path->near_point->unitx, path->near_point->unity, lat2, lon2);
671 sum += calculate_distance(lat1, lon1, lat2, lon2);
676 /******************************************************************************/
679 path_load(Path *path, const gchar *file)
685 g_return_val_if_fail(path, FALSE);
686 g_return_val_if_fail(file, FALSE);
688 if (gnome_vfs_read_entire_file(file, &size, &bytes)==GNOME_VFS_OK)
689 path_gpx_parse(path, bytes, size, GPX_PATH_NEW);
695 path_save(Path *path, const gchar *file)
697 GnomeVFSHandle *handle;
700 g_return_val_if_fail(path, FALSE);
701 g_return_val_if_fail(file, FALSE);
703 if (gnome_vfs_create(&handle, file, GNOME_VFS_OPEN_WRITE, FALSE, 0600)==GNOME_VFS_OK) {
704 path_gpx_write(path, handle, NULL);
705 gnome_vfs_close(handle);
711 /******************************************************************************/
714 path_set_destination_from_last(Path *path, Position *pos)
719 g_return_val_if_fail(path, FALSE);
720 g_return_val_if_fail(pos, FALSE);
722 if (path->head==path->tail) {
723 position_set(pos, FALSE, NAN, NAN, NAN);
727 p=path_find_last_point(path);
729 unit2latlon(p->unitx, p->unity, &lat, &lon);
730 position_set(pos, TRUE, lat, lon, 0);
732 position_set(pos, FALSE, NAN, NAN, NAN);
739 * path_get_waypoint_latlon:
744 * Get the real latitude and longitude of given waypoint
746 * Returns: TRUE if waypoint was valid, FALSE otherwise.
749 path_get_waypoint_latlon(WayPoint *way, gdouble *lat, gdouble *lon)
753 g_return_val_if_fail(way, FALSE);
754 g_return_val_if_fail(way->point, FALSE);
755 g_return_val_if_fail(lat, FALSE);
756 g_return_val_if_fail(lon, FALSE);
758 unit2latlon(way->point->unitx, way->point->unity, tlat, tlon);
767 * path_insert_mark_text:
771 * Add a new waypoint to path with given text at the last point.
775 path_insert_mark_text(Path *path, gchar *text)
777 g_return_if_fail(path);
778 MACRO_PATH_INCREMENT_WTAIL(*path);
779 path->wtail->point=path->tail;
781 path->wtail->desc=text;
784 path->wtail->desc=g_strdup_printf("WPT:#%u", path->wpcnt);
786 g_signal_emit(G_OBJECT(path), signals[NEW_WAYPOINT], 0, NULL);
790 * path_insert_mark_autonumber:
793 * Add autonumbered waypoint to given path
797 path_insert_mark_autonumber(Path *path)
799 path_insert_mark_text(path, NULL);
802 /******************************************************************************/
804 #define PATH_GPX_WRITE_ERROR path_gpx_write_error_quark()
807 path_gpx_write_error_quark(void)
809 return g_quark_from_static_string ("path-gpx-write-error-quark");
812 #define XML_DATE_FORMAT "%FT%T"
814 #define WRITE_STRING(string) { \
815 if(GNOME_VFS_OK != (vfs_result = gnome_vfs_write(handle, (string), strlen((string)), &size))) { \
817 PATH_GPX_WRITE_ERROR, G_FILE_ERROR_FAILED, \
819 _("Error while writing to file"), \
820 _("File is incomplete."), \
821 gnome_vfs_result_to_string(vfs_result)); \
827 path_gpx_write(Path *path, GnomeVFSHandle *handle, GError **error)
830 WayPoint *wcurr = NULL;
831 gboolean trkseg_break = FALSE;
834 GnomeVFSResult vfs_result;
835 GnomeVFSFileSize size;
837 g_return_val_if_fail((error == NULL || *error == NULL), FALSE);
839 gpx_time = time(NULL);
841 /* Find first non-zero point. */
842 for (curr = path->head - 1, wcurr = path->whead; curr++ != path->tail;) {
845 else if (wcurr && curr == wcurr->point)
849 /* Write the header. */
850 WRITE_STRING("<?xml version=\"1.0\"?>\n"
851 "<gpx version=\"1.0\" creator=\"Mapper\" xmlns=\"http://www.topografix.com/GPX/1/0\">\n");
853 /* Write any metadata */
854 WRITE_STRING("<metadata>\n");
856 WRITE_STRING("<time>");
857 strftime(buffer, sizeof(buffer), XML_DATE_FORMAT, localtime(&gpx_time));
858 WRITE_STRING(buffer);
859 WRITE_STRING(XML_TZONE);
860 WRITE_STRING("</time>\n");
862 WRITE_STRING("</metadata>\n");
864 /* Write track(s) and waypoint(s) */
865 WRITE_STRING("<trk>\n<trkseg>\n");
867 /* Curr points to first non-zero point. */
868 for (curr--; curr++ != path->tail;) {
871 gboolean first_sub = TRUE;
873 /* First trkpt of the segment - write trkseg header. */
874 WRITE_STRING("</trkseg>\n<trkseg>\n");
875 trkseg_break = FALSE;
877 unit2latlon(curr->unitx, curr->unity, &lat, &lon);
878 WRITE_STRING("<trkpt lat=\"");
879 g_ascii_formatd(buffer, sizeof(buffer), "%.06f", lat);
880 WRITE_STRING(buffer);
881 WRITE_STRING("\" lon=\"");
882 g_ascii_formatd(buffer, sizeof(buffer), "%.06f", lon);
883 WRITE_STRING(buffer);
886 /* write the elevation */
887 if (!isnan(curr->altitude)) {
892 WRITE_STRING("<ele>");
893 g_ascii_formatd(buffer, sizeof(buffer), "%.2f", curr->altitude);
894 WRITE_STRING(buffer);
895 WRITE_STRING("</ele>\n");
904 WRITE_STRING("<time>");
905 strftime(buffer, sizeof(buffer), XML_DATE_FORMAT, localtime(&curr->time));
906 WRITE_STRING(buffer);
907 WRITE_STRING(XML_TZONE);
908 WRITE_STRING("</time>\n");
911 if (wcurr && curr == wcurr->point) {
918 desc=g_markup_printf_escaped("<desc>%s</desc>\n", wcurr->desc);
925 WRITE_STRING("/>\n");
927 WRITE_STRING("</trkpt>\n");
933 /* Write the footer. */
934 WRITE_STRING("</trkseg>\n</trk>\n</gpx>\n");
940 * Handle a start tag in the parsing of a GPX file.
942 #define MACRO_SET_UNKNOWN(utag) { \
943 data->prev_state = data->state; \
944 data->state = UNKNOWN; \
945 data->unknown_depth = 1; \
946 g_debug("GPX: unknown tag [%s]", (gchar *)utag); }
949 gpx_start_element(SaxData *data, const xmlChar *name, const xmlChar **attrs)
951 switch (data->state) {
955 if (!strcmp((gchar *) name, "gpx"))
956 data->state = INSIDE_GPX;
958 MACRO_SET_UNKNOWN(name);
961 if (!strcmp((gchar *) name, "trk"))
962 data->state = INSIDE_PATH;
963 else if (!strcmp((gchar *) name, "metadata"))
964 data->state = INSIDE_METADATA;
966 MACRO_SET_UNKNOWN(name);
968 case INSIDE_METADATA:
971 if (!strcmp((gchar *) name, "trkseg")) {
972 data->state = INSIDE_PATH_SEGMENT;
973 data->at_least_one_trkpt = FALSE;
975 MACRO_SET_UNKNOWN(name);
977 case INSIDE_PATH_SEGMENT:
978 if (!strcmp((gchar *) name, "trkpt")) {
979 const xmlChar **curr_attr;
981 gdouble lat = 0.f, lon = 0.f;
982 gboolean has_lat, has_lon;
985 for (curr_attr = attrs; *curr_attr != NULL;) {
986 const gchar *attr_name = *curr_attr++;
987 const gchar *attr_val = *curr_attr++;
988 if (!strcmp(attr_name, "lat")) {
989 lat = g_ascii_strtod(attr_val, &error_check);
990 if (error_check != attr_val)
992 } else if (!strcmp(attr_name, "lon")) {
993 lon = g_ascii_strtod(attr_val, &error_check);
994 if (error_check != attr_val)
998 if (has_lat && has_lon) {
999 path_add_latlon(data->path, lat, lon, 0, 0, NAN);
1000 data->state = INSIDE_PATH_POINT;
1002 data->state = ERROR;
1004 MACRO_SET_UNKNOWN(name);
1006 case INSIDE_PATH_POINT:
1007 if (!strcmp((gchar *) name, "time"))
1008 data->state = INSIDE_PATH_POINT_TIME;
1009 else if (!strcmp((gchar *) name, "ele"))
1010 data->state = INSIDE_PATH_POINT_ELE;
1011 else if (!strcmp((gchar *) name, "desc"))
1012 data->state = INSIDE_PATH_POINT_DESC;
1013 else if (!strcmp((gchar *) name, "name"))
1014 data->state = INSIDE_PATH_POINT_NAME;
1016 MACRO_SET_UNKNOWN(name);
1019 data->unknown_depth++;
1027 * Handle an end tag in the parsing of a GPX file.
1030 gpx_end_element(SaxData * data, const xmlChar * name)
1032 switch (data->state) {
1037 data->state = ERROR;
1040 if (!strcmp((gchar *) name, "gpx"))
1041 data->state = FINISH;
1043 data->state = ERROR;
1045 case INSIDE_METADATA:
1046 if (!strcmp((gchar *) name, "metadata"))
1047 data->state = INSIDE_GPX;
1050 if (!strcmp((gchar *) name, "trk"))
1051 data->state = INSIDE_GPX;
1053 data->state = ERROR;
1055 case INSIDE_PATH_SEGMENT:
1056 if (!strcmp((gchar *) name, "trkseg")) {
1057 if (data->at_least_one_trkpt) {
1058 path_add_break(data->path);
1060 data->state = INSIDE_PATH;
1062 data->state = ERROR;
1064 case INSIDE_PATH_POINT:
1065 if (!strcmp((gchar *) name, "trkpt")) {
1066 data->state = INSIDE_PATH_SEGMENT;
1067 data->at_least_one_trkpt = TRUE;
1069 data->state = ERROR;
1071 case INSIDE_PATH_POINT_ELE:
1072 if (!strcmp((gchar *) name, "ele")) {
1074 data->path->tail->altitude = g_ascii_strtod(data->chars->str, &error_check);
1075 if (error_check == data->chars->str)
1076 data->path->tail->altitude = NAN;
1077 data->state = INSIDE_PATH_POINT;
1078 g_string_free(data->chars, TRUE);
1079 data->chars = g_string_new("");
1081 data->state = ERROR;
1083 case INSIDE_PATH_POINT_TIME:
1084 if (!strcmp((gchar *) name, "time")) {
1088 if (NULL == (ptr = strptime(data->chars->str, XML_DATE_FORMAT, &time)))
1089 /* Failed to parse dateTime format. */
1090 data->state = ERROR;
1092 /* Parse was successful. Now we have to parse timezone.
1093 * From here on, if there is an error, I just assume local
1094 * timezone. Yes, this is not proper XML, but I don't
1098 /* First, set time in "local" time zone. */
1099 data->path->tail->time = (mktime(&time));
1101 /* Now, skip inconsequential characters */
1102 while (*ptr && *ptr != 'Z' && *ptr != '-' && *ptr != '+')
1105 /* Check if we ran to the end of the string. */
1107 /* Next character is either 'Z', '-', or '+' */
1109 /* Zulu (UTC) time. Undo the local time zone's offset. */
1110 data->path->tail->time += time.tm_gmtoff;
1112 /* Not Zulu (UTC). Must parse hours and minutes. */
1113 gint offhours = strtol(ptr, &error_check, 10);
1114 if (error_check != ptr && *(ptr = error_check) == ':') {
1115 /* Parse of hours worked. Check minutes. */
1116 gint offmins = strtol(ptr + 1, &error_check, 10);
1117 if (error_check != (ptr + 1)) {
1118 /* Parse of minutes worked. Calculate. */
1119 data->path->tail->time += (time.tm_gmtoff - (offhours * 60 * 60 + offmins * 60));
1124 /* Successfully parsed dateTime. */
1125 data->state = INSIDE_PATH_POINT;
1128 g_string_free(data->chars, TRUE);
1129 data->chars = g_string_new("");
1131 data->state = ERROR;
1134 case INSIDE_PATH_POINT_DESC:
1135 /* only parse description for routes */
1136 if (!strcmp((gchar *) name, "desc")) {
1137 path_insert_mark_text(data->path, g_string_free(data->chars, FALSE));
1138 data->chars=g_string_new("");
1139 data->state=INSIDE_PATH_POINT;
1144 case INSIDE_PATH_POINT_NAME:
1145 /* Just ignore these for now */
1146 g_string_free(data->chars, FALSE);
1147 data->chars=g_string_new("");
1148 data->state=INSIDE_PATH_POINT;
1151 if (!--data->unknown_depth)
1152 data->state=data->prev_state;
1162 * Handle char data in the parsing of a GPX file.
1165 gpx_chars(SaxData *data, const xmlChar *ch, int len)
1169 switch (data->state) {
1173 case INSIDE_PATH_POINT_ELE:
1174 case INSIDE_PATH_POINT_TIME:
1175 case INSIDE_PATH_POINT_DESC:
1176 case INSIDE_PATH_POINT_NAME:
1177 for (i = 0; i < len; i++)
1178 data->chars = g_string_append_c(data->chars, ch[i]);
1179 /* g_debug("GPXC: %s", data->chars->str); */
1188 * Handle an entity in the parsing of a GPX file. We don't do anything
1192 gpx_get_entity(SaxData *data, const xmlChar *name)
1194 return xmlGetPredefinedEntity(name);
1198 * Handle an error in the parsing of a GPX file.
1201 gpx_error(SaxData *data, const gchar *msg, ...)
1205 va_start(args, msg);
1206 g_logv("GPX", G_LOG_LEVEL_WARNING, msg, args);
1209 data->state = ERROR;
1219 * Parse a buffer of GPX data.
1220 * XXX: Add support for parsing directly from file if the file is local.
1224 path_gpx_parse(Path *path, gchar *buffer, gint size, gpx_path_policy policy)
1227 xmlSAXHandler sax_handler;
1231 data.chars=g_string_new("");
1233 if (policy==GPX_PATH_NEW)
1236 memset(&sax_handler, 0, sizeof(sax_handler));
1237 sax_handler.characters=(charactersSAXFunc) gpx_chars;
1238 sax_handler.startElement=(startElementSAXFunc) gpx_start_element;
1239 sax_handler.endElement=(endElementSAXFunc) gpx_end_element;
1240 sax_handler.entityDecl=(entityDeclSAXFunc) gpx_get_entity;
1241 sax_handler.warning=(warningSAXFunc) gpx_error;
1242 sax_handler.error=(errorSAXFunc) gpx_error;
1243 sax_handler.fatalError=(fatalErrorSAXFunc) gpx_error;
1245 xmlSAXUserParseMemory(&sax_handler, &data, buffer, size);
1247 g_string_free(data.chars, TRUE);
1249 if (data.state!=FINISH) {
1250 g_warning("GPX: Parser stopped in error state %d", data.state);
1255 case GPX_PATH_APPEND:
1256 case GPX_PATH_PREPEND:
1261 if (policy==GPX_PATH_APPEND) {
1262 /* Append to current path. Make sure last path point is zero. */
1263 path_add_break(path);
1267 /* Prepend to current route. */
1272 /* Find src_first non-zero point. */
1273 for (src_first = src->head; src_first++ != src->tail;)
1274 if (src_first->unity && src_first->unitx)
1277 /* Append route points from src to dest. */
1278 if (src->tail >= src_first) {
1280 guint num_dest_points = dest->tail - dest->head + 1;
1281 guint num_src_points = src->tail - src_first + 1;
1283 /* Adjust dest->tail to be able to fit src route data
1284 * plus room for more route data. */
1285 path_resize(dest, num_dest_points + num_src_points);
1287 memcpy(dest->tail + 1, src_first, num_src_points * sizeof(Point));
1289 dest->tail += num_src_points;
1291 /* Append waypoints from src to dest->. */
1292 path_wresize(dest, (dest->wtail - dest->whead) + (src->wtail - src->whead) + 2);
1293 for (curr = src->whead - 1; curr++ != src->wtail;) {
1294 (++(dest->wtail))->point = dest->head + num_dest_points + (curr->point - src_first);
1295 dest->wtail->desc = curr->desc;
1299 /* Kill old route - don't use MACRO_PATH_FREE(), because that
1300 * would free the string desc's that we just moved to data.route. */
1303 if (policy==GPX_PATH_PREPEND)
1311 g_assert_not_reached();
1318 /******************************************************************************/
1322 path_store_append_waypoint(GtkListStore *, WayPoint *w)
1324 gchar tmp1[16], tmp2[16];
1327 unit2latlon(wcurr->point->unitx, wcurr->point->unity, lat2, lon2);
1328 lat_format(_degformat, lat2, tmp1);
1329 lon_format(_degformat, lon2, tmp2);
1331 g_snprintf(buffer1, sizeof(buffer1), "%s,%s", tmp1, tmp2);
1332 sum += calculate_distance(lat1, lon1, lat2, lon2);
1333 g_snprintf(buffer2, sizeof(buffer2), "%.02f %s", sum * UNITS_CONVERT[_units], UNITS_TEXT[_units]);
1335 gtk_list_store_append(store, &iter);
1336 gtk_list_store_set(store, &iter,
1337 PATH_LATLON, buffer1,
1338 PATH_DISTANCE, buffer2,
1339 PATH_WAYPOINT, wcurr->desc,
1350 * Generate a GtkListStore with information about path waypoints (location, distance)
1353 path_get_waypoints_store(Path *path)
1357 GtkListStore *store;
1360 gchar tmp1[16], tmp2[16];
1361 gdouble lat1, lon1, lat2, lon2;
1364 g_return_val_if_fail(path!=NULL, NULL);
1368 g_return_val_if_fail(wcurr!=NULL, NULL);
1369 g_return_val_if_fail(wcurr->point!=NULL, NULL);
1370 if (!path_has_waypoints(path))
1373 store=gtk_list_store_new(PATH_NUM_COLUMNS, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_DOUBLE, G_TYPE_DOUBLE);
1375 unit2latlon(wcurr->point->unitx, wcurr->point->unity, lat1, lon1);
1377 while (wcurr!=path->wtail) {
1381 if (!wcurr->point) {
1382 g_debug("PSTORE: No point for waypoint (%s) skipping", wcurr->desc);
1387 unit2latlon(wcurr->point->unitx, wcurr->point->unity, lat2, lon2);
1388 lat_format(_degformat, lat2, tmp1);
1389 lon_format(_degformat, lon2, tmp2);
1391 g_snprintf(buffer1, sizeof(buffer1), "%s,%s", tmp1, tmp2);
1392 sum += calculate_distance(lat1, lon1, lat2, lon2);
1393 g_snprintf(buffer2, sizeof(buffer2), "%.02f %s", sum * UNITS_CONVERT[_units], UNITS_TEXT[_units]);
1395 gtk_list_store_append(store, &iter);
1396 gtk_list_store_set(store, &iter,
1397 PATH_LATLON, buffer1,
1398 PATH_DISTANCE, buffer2,
1399 PATH_WAYPOINT, wcurr->desc,