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>
34 struct sql_select_stmt {
35 sqlite3_stmt *select_paths;
36 sqlite3_stmt *select_path_nodes;
38 sqlite3_stmt *insert_path;
39 sqlite3_stmt *insert_path_node;
41 sqlite3_stmt *delete_path;
42 sqlite3_stmt *delete_path_nodes;
44 static struct sql_select_stmt sql;
46 #define PATH_TABLE_PATHS "create table IF NOT EXISTS paths ( \
47 nid int primary key, \
52 #define PATH_TABLE_NODES "create table IF NOT EXISTS path_nodes ( \
62 name text default null, \
66 NEW_POINT, /* A new point was appended to track track */
67 NEW_BREAK, /* A break was appended to the track */
68 NEW_WAYPOINT, /* A new waypoint/marker has been added */
69 NEAR_WAYPOINT, /* We are near the next route waypoint, announce it */
70 REACHED_WAYPOINT, /* We have reached the next route waypoint, announce it */
71 REACHED_DESTINATION, /* We have reached the last route waypoint */
72 CLEARED, /* Path was cleared */
75 static guint32 signals[LAST_SIGNAL] = {0};
77 /** This enum defines the states of the SAX parsing state machine. */
85 INSIDE_PATH_POINT_ELE,
86 INSIDE_PATH_POINT_TIME,
87 INSIDE_PATH_POINT_DESC,
88 INSIDE_PATH_POINT_NAME,
94 /** Data used during the SAX parsing operation. */
95 typedef struct _SaxData SaxData;
101 gboolean at_least_one_trkpt;
105 static gchar XML_TZONE[7];
107 G_DEFINE_TYPE(Path, path, G_TYPE_OBJECT);
109 #define GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), PATH_TYPE, PathPrivate))
112 path_dispose(GObject *object)
114 g_debug("path_dispose");
116 G_OBJECT_CLASS(path_parent_class)->dispose(object);
120 path_finalize(GObject *object)
122 Path *path=PATH(object);
124 g_debug("path_finalize");
125 MACRO_PATH_FREE(*path);
132 g_free(path->author);
134 g_free(path->keywords);
136 g_free(path->copyright);
142 path_class_init(PathClass *klass)
144 GObjectClass *object_class=G_OBJECT_CLASS(klass);
146 g_debug("path_class_init");
148 object_class->dispose=path_dispose;
149 object_class->finalize=path_finalize;
150 /* g_type_class_add_private (klass, sizeof(PathPrivate)); */
152 signals[NEW_POINT]=g_signal_new("new-point", G_OBJECT_CLASS_TYPE(object_class),
153 G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET(PathClass, new_point),
154 NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, NULL);
155 signals[NEW_BREAK]=g_signal_new("new-break", G_OBJECT_CLASS_TYPE(object_class),
156 G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET(PathClass, new_break),
157 NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, NULL);
158 signals[NEW_WAYPOINT]=g_signal_new("new-waypoint", G_OBJECT_CLASS_TYPE(object_class),
159 G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET(PathClass, new_waypoint),
160 NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, NULL);
164 path_init(Path *path)
166 g_debug("path_init");
167 MACRO_PATH_INIT(*path);
171 path_new(PathType type, guint id)
174 static time_t time1=0;
177 p=g_object_new(PATH_TYPE, NULL);
184 localtime_r(&time1, &time2);
185 g_snprintf(XML_TZONE, sizeof(XML_TZONE), "%+03ld:%02ld", (time2.tm_gmtoff / 60 / 60), (time2.tm_gmtoff / 60) % 60);
192 path_free(Path *path)
194 g_return_if_fail(path);
195 g_object_unref(path);
199 path_clear(Path *path)
201 g_return_if_fail(path);
202 MACRO_PATH_FREE(*path);
203 path->length=path->avgspeed=0.0;
208 path_resize(Path *path, guint size)
210 g_return_val_if_fail(path, FALSE);
212 if (path->head + size != path->cap) {
214 Point *old_head = path->head;
216 path->head = g_renew(Point, old_head, size);
217 g_assert(path->head);
218 path->cap = path->head + size;
219 if (path->head != old_head) {
220 path->tail = path->head + (path->tail - old_head);
222 /* Adjust all of the waypoints. */
223 for (curr = path->whead - 1; curr++ != path->wtail;)
224 curr->point = path->head + (curr->point - old_head);
232 path_wresize(Path *path, guint wsize)
234 g_return_val_if_fail(path, FALSE);
236 if (path->whead + wsize != path->wcap) {
237 WayPoint *old_whead = path->whead;
239 path->whead = g_renew(WayPoint, old_whead, wsize);
240 path->wtail = path->whead + (path->wtail - old_whead);
241 path->wcap = path->whead + wsize;
255 * Append a waypoint to path at given lat, lon with description desc.
260 path_add_waypoint(Path *path, gdouble lat, gdouble lon, gchar *desc)
264 latlon2unit(lat, lon, unitx, unity);
265 MACRO_PATH_INCREMENT_TAIL(*path);
266 path->tail->unitx=unitx;
267 path->tail->unity=unity;
269 path->tail->altitude=NAN;
271 MACRO_PATH_INCREMENT_WTAIL(*path);
272 path->wtail->point=path->tail;
273 path->wtail->desc=desc;
275 path_find_nearest_point(path);
277 g_signal_emit(G_OBJECT(path), signals[NEW_WAYPOINT], 0, NULL);
291 * Append a point with given lat,lon,ptime,speed and altitude to given path.
293 * Returns: TRUE if the new point was added. FALSE is returned if new point distance was under sensitivity setting.
296 path_add_latlon(Path *path, gdouble lat, gdouble lon, time_t ptime, gfloat speed, gfloat altitude)
300 latlon2unit(lat, lon, unitx, unity);
302 if (abs((gint)unitx-path->tail->unitx) > path->sensitivity || abs((gint)unity-path->tail->unity) > path->sensitivity) {
303 if (path->tail->unity && path->tail->unitx) {
306 unit2latlon(path->tail->unitx, path->tail->unity, lat, lon);
307 path->length+=calculate_distance(plat, plon, lat, lon);
309 MACRO_PATH_INCREMENT_TAIL(*path);
310 path->tail->unitx=unitx;
311 path->tail->unity=unity;
312 path->tail->time=ptime;
313 path->tail->altitude=altitude;
314 if (speed>path->maxspeed)
315 path->maxspeed=speed;
317 path->avgspeed=(path->points>0) ? path->tspeed/path->points : 0.0;
319 g_debug("TRACK: %f %f (%d)", path->length, path->avgspeed, path->points);
321 g_signal_emit(G_OBJECT(path), signals[NEW_POINT], 0, NULL);
333 * Add a break point to the path.
335 * Returns: TRUE if break was added, FALSE if last point was a break already.
338 path_add_break(Path *path)
340 g_return_val_if_fail(path, FALSE);
341 g_return_val_if_fail(path->tail, FALSE);
343 if (path->tail->unity && path->tail->unitx) {
344 /* To mark a "break" in a track, we'll add a (0, 0) point and then
345 another instance of the most recent track point. */
347 MACRO_PATH_INCREMENT_TAIL(*path);
348 *path->tail=_point_null;
349 MACRO_PATH_INCREMENT_TAIL(*path);
350 *path->tail=path->tail[-2];
352 g_signal_emit(G_OBJECT(path), signals[NEW_BREAK], 0, NULL);
363 * Checks if given path has any path points
365 * Returns: TRUE if there are points, FALSE otherwise
368 path_has_points(Path *path)
370 g_return_val_if_fail(path, FALSE);
371 return path->head==path->tail ? FALSE : TRUE;
375 * path_has_waypoints:
377 * Checks if given path has any waypoints
379 * Returns: TRUE if there are waypoints, FALSE otherwise
382 path_has_waypoints(Path *path)
384 g_return_val_if_fail(path, FALSE);
385 return path->whead==path->wtail ? FALSE : TRUE;
389 * path_find_last_point:
392 * Returns: The last path point or NULL if path is empty
395 path_find_last_point(Path *path)
399 g_return_val_if_fail(path, NULL);
401 if (!path_has_points(path))
404 for (p=path->tail; !p->unity; p--) {
410 * Updates near_point, next_way, and next_wpt. If quick is FALSE (as
411 * it is when this function is called from route_find_nearest_point), then
412 * the entire list (starting from near_point) is searched. Otherwise, we
413 * stop searching when we find a point that is farther away.
416 path_update_nears(Path *path, Point *point, gboolean quick)
418 gboolean ret = FALSE;
420 WayPoint *wcurr, *wnext;
421 guint64 near_dist_squared;
423 g_return_val_if_fail(path, FALSE);
425 /* If we have waypoints (_next_way != NULL), then determine the "next
426 * waypoint", which is defined as the waypoint after the nearest point,
427 * UNLESS we've passed that waypoint, in which case the waypoint after
428 * that waypoint becomes the "next" waypoint. */
429 if (path->next_way) {
430 /* First, set near_dist_squared with the new distance from
432 near = path->near_point;
433 near_dist_squared = DISTANCE_SQUARED(*point, *near);
435 /* Now, search path for a closer point. If quick is TRUE, then we'll
436 * only search forward, only as long as we keep finding closer points.
438 for (curr = path->near_point; curr++ != path->tail;) {
440 guint dist_squared = DISTANCE_SQUARED(*point, *curr);
441 if (dist_squared <= near_dist_squared) {
443 near_dist_squared = dist_squared;
449 /* Update _near_point. */
450 path->near_point = near;
451 path->near_point_dist_squared = near_dist_squared;
453 for (wnext = wcurr = path->next_way; wcurr != path->wtail; wcurr++) {
454 if (wcurr->point < near || (wcurr->point == near && quick
455 && (path->next_wpt && (DISTANCE_SQUARED(*point, *near) > path->next_way_dist_squared
456 && DISTANCE_SQUARED(*point, *path->next_wpt) < path->next_wpt_dist_squared))))
457 /* Okay, this else if expression warrants explanation. If the
458 * nearest track point happens to be a waypoint, then we want to
459 * check if we have "passed" that waypoint. To check this, we
460 * test the distance from _gps to the waypoint and from _gps to
461 * _next_wpt, and if the former is increasing and the latter is
462 * decreasing, then we have passed the waypoint, and thus we
463 * should skip it. Note that if there is no _next_wpt, then
464 * there is no next waypoint, so we do not skip it in that case. */
470 if (wnext == path->wtail && (wnext->point < near || (wnext->point == near && quick
471 && (path->next_wpt && (DISTANCE_SQUARED (*point, *near) > path->next_way_dist_squared
472 && DISTANCE_SQUARED(*point, *path->next_wpt) < path->next_wpt_dist_squared)))))
474 path->next_way = NULL;
475 path->next_wpt = NULL;
476 path->next_way_dist_squared = -1;
477 path->next_wpt_dist_squared = -1;
480 /* Only update next_way (and consequently _next_wpt) if _next_way is
481 * different, and record that fact for return. */
483 if (!quick || path->next_way != wnext) {
484 path->next_way = wnext;
485 path->next_wpt = wnext->point;
486 if (path->next_wpt == path->tail)
487 path->next_wpt = NULL;
489 while (!(++path->next_wpt)->unity) {
490 if (path->next_wpt == path->tail) {
491 path->next_wpt = NULL;
498 path->next_way_dist_squared = DISTANCE_SQUARED(*point, *wnext->point);
500 path->next_wpt_dist_squared = DISTANCE_SQUARED(*point, *path->next_wpt);
507 * path_find_nearest_point:
509 * Reset the near_point data by searching the entire path for the nearest point and waypoint.
512 path_find_nearest_point(Path *path)
514 g_return_if_fail(path);
516 /* Initialize near_point to first non-zero point. */
517 path->near_point=path->head;
518 while (!path->near_point->unity && path->near_point != path->tail)
521 /* Initialize next_way */
522 if (path->wtail==path->whead)
525 path->next_way=path->whead;
526 path->next_way_dist_squared=-1;
528 /* Initialize next_wpt */
530 path->next_wpt_dist_squared=-1;
535 * path_find_nearest_waypoint:
539 path_find_nearest_waypoint(Path *path, guint unitx, guint unity)
543 guint64 nearest_squared;
544 Point pos = { unitx, unity, 0, NAN };
546 g_return_val_if_fail(path, NULL);
548 wcurr=wnear=path->whead;
549 if (wcurr && wcurr->point && wcurr!=path->wtail) {
550 nearest_squared=DISTANCE_SQUARED(pos, *(wcurr->point));
552 while (wcurr++!=path->wtail) {
553 guint64 test_squared=DISTANCE_SQUARED(pos, *(wcurr->point));
554 if (test_squared < nearest_squared) {
556 nearest_squared=test_squared;
561 if (wnear && wnear->point) {
562 if (abs(unitx - wnear->point->unitx) < path->sensitivity && abs(unity - wnear->point->unity) < path->sensitivity)
570 * path_check_waypoint_announce:
574 * Check if we should announce upcoming waypoint.
578 path_check_waypoint_announce(Path *path, GpsData *gps)
580 guint a_thres_near, a_thres_at;
582 g_return_if_fail(path);
583 g_return_if_fail(gps);
588 a_thres_near=(20+(guint)gps->speed)*path->announce_notice_ratio*3;
589 a_thres_at=(20+(guint)gps->speed);
591 if (path->next_way_dist_squared<(a_thres_near * a_thres_near) && path->next_way!=path->announced_waypoint) {
592 g_signal_emit(G_OBJECT(path), signals[NEAR_WAYPOINT], 0, NULL);
593 path->announced_waypoint=path->next_way;
594 } else if (path->next_way_dist_squared<(a_thres_at * a_thres_at) && path->next_way!=path->announced_waypoint) {
595 g_signal_emit(G_OBJECT(path), signals[REACHED_WAYPOINT], 0, NULL);
596 path->announced_waypoint=path->next_way;
600 /******************************************************************************/
603 path_get_distance_to(Path *path, Point *point, gdouble lat, gdouble lon)
605 gdouble lat1, lon1, lat2, lon2;
608 g_return_val_if_fail(path, 0.0);
610 /* If point is NULL, use the next waypoint. */
611 if (point == NULL && path->next_way)
612 point = path->next_way->point;
614 /* If point is still NULL, return an error. */
621 if (point > path->near_point) {
623 /* Skip _near_point in case we have already passed it. */
624 for (curr = path->near_point + 1; curr <= point; ++curr) {
626 unit2latlon(curr->unitx, curr->unity, lat2, lon2);
627 sum += calculate_distance(lat1, lon1, lat2, lon2);
632 } else if (point < path->near_point) {
634 /* Skip near_point in case we have already passed it. */
635 for (curr = path->near_point - 1; curr >= point; --curr) {
637 unit2latlon(curr->unitx, curr->unity, lat2, lon2);
638 sum += calculate_distance(lat1, lon1, lat2, lon2);
644 /* Waypoint _is_ the nearest point. */
645 unit2latlon(path->near_point->unitx, path->near_point->unity, lat2, lon2);
646 sum += calculate_distance(lat1, lon1, lat2, lon2);
651 /******************************************************************************/
654 path_load(Path *path, const gchar *file)
660 g_return_val_if_fail(path, FALSE);
661 g_return_val_if_fail(file, FALSE);
663 if (gnome_vfs_read_entire_file(file, &size, &bytes)==GNOME_VFS_OK)
664 path_gpx_parse(path, bytes, size, GPX_PATH_NEW);
670 path_save(Path *path, const gchar *file)
672 GnomeVFSHandle *handle;
675 g_return_val_if_fail(path, FALSE);
676 g_return_val_if_fail(file, FALSE);
678 if (gnome_vfs_create(&handle, file, GNOME_VFS_OPEN_WRITE, FALSE, 0600)==GNOME_VFS_OK) {
679 path_gpx_write(path, handle, NULL);
680 gnome_vfs_close(handle);
686 /******************************************************************************/
689 path_set_destination_from_last(Path *path, Position *pos)
694 g_return_val_if_fail(path, FALSE);
695 g_return_val_if_fail(pos, FALSE);
697 if (path->head==path->tail) {
698 position_set(pos, FALSE, NAN, NAN, NAN);
702 p=path_find_last_point(path);
704 unit2latlon(p->unitx, p->unity, &lat, &lon);
705 position_set(pos, TRUE, lat, lon, 0);
707 position_set(pos, FALSE, NAN, NAN, NAN);
714 * path_get_waypoint_latlon:
719 * Get the real latitude and longitude of given waypoint
721 * Returns: TRUE if waypoint was valid, FALSE otherwise.
724 path_get_waypoint_latlon(WayPoint *way, gdouble *lat, gdouble *lon)
728 g_return_val_if_fail(way, FALSE);
729 g_return_val_if_fail(way->point, FALSE);
730 g_return_val_if_fail(lat, FALSE);
731 g_return_val_if_fail(lon, FALSE);
733 unit2latlon(way->point->unitx, way->point->unity, tlat, tlon);
742 * path_insert_mark_text:
746 * Add a new waypoint to path with given text at the last point.
750 path_insert_mark_text(Path *path, gchar *text)
752 g_return_if_fail(path);
753 MACRO_PATH_INCREMENT_WTAIL(*path);
754 path->wtail->point=path->tail;
756 path->wtail->desc=text;
759 path->wtail->desc=g_strdup_printf("WPT:#%u", path->wpcnt);
761 g_signal_emit(G_OBJECT(path), signals[NEW_WAYPOINT], 0, NULL);
765 * path_insert_mark_autonumber:
768 * Add autonumbered waypoint to given path
772 path_insert_mark_autonumber(Path *path)
774 path_insert_mark_text(path, NULL);
777 /******************************************************************************/
779 #define PATH_GPX_WRITE_ERROR path_gpx_write_error_quark()
782 path_gpx_write_error_quark(void)
784 return g_quark_from_static_string ("path-gpx-write-error-quark");
787 #define XML_DATE_FORMAT "%FT%T"
789 #define WRITE_STRING(string) { \
790 if(GNOME_VFS_OK != (vfs_result = gnome_vfs_write(handle, (string), strlen((string)), &size))) { \
792 PATH_GPX_WRITE_ERROR, G_FILE_ERROR_FAILED, \
794 _("Error while writing to file"), \
795 _("File is incomplete."), \
796 gnome_vfs_result_to_string(vfs_result)); \
802 path_gpx_write(Path *path, GnomeVFSHandle *handle, GError **error)
805 WayPoint *wcurr = NULL;
806 gboolean trkseg_break = FALSE;
809 GnomeVFSResult vfs_result;
810 GnomeVFSFileSize size;
812 g_return_val_if_fail((error == NULL || *error == NULL), FALSE);
814 gpx_time = time(NULL);
816 /* Find first non-zero point. */
817 for (curr = path->head - 1, wcurr = path->whead; curr++ != path->tail;) {
820 else if (wcurr && curr == wcurr->point)
824 /* Write the header. */
825 WRITE_STRING("<?xml version=\"1.0\"?>\n"
826 "<gpx version=\"1.0\" creator=\"Mapper\" xmlns=\"http://www.topografix.com/GPX/1/0\">\n");
828 /* Write any metadata */
829 WRITE_STRING("<metadata>\n");
831 WRITE_STRING("<time>");
832 strftime(buffer, sizeof(buffer), XML_DATE_FORMAT, localtime(&gpx_time));
833 WRITE_STRING(buffer);
834 WRITE_STRING(XML_TZONE);
835 WRITE_STRING("</time>\n");
837 WRITE_STRING("</metadata>\n");
839 /* Write track(s) and waypoint(s) */
840 WRITE_STRING("<trk>\n<trkseg>\n");
842 /* Curr points to first non-zero point. */
843 for (curr--; curr++ != path->tail;) {
846 gboolean first_sub = TRUE;
848 /* First trkpt of the segment - write trkseg header. */
849 WRITE_STRING("</trkseg>\n<trkseg>\n");
850 trkseg_break = FALSE;
852 unit2latlon(curr->unitx, curr->unity, &lat, &lon);
853 WRITE_STRING("<trkpt lat=\"");
854 g_ascii_formatd(buffer, sizeof(buffer), "%.06f", lat);
855 WRITE_STRING(buffer);
856 WRITE_STRING("\" lon=\"");
857 g_ascii_formatd(buffer, sizeof(buffer), "%.06f", lon);
858 WRITE_STRING(buffer);
861 /* write the elevation */
862 if (!isnan(curr->altitude)) {
867 WRITE_STRING("<ele>");
868 g_ascii_formatd(buffer, sizeof(buffer), "%.2f", curr->altitude);
869 WRITE_STRING(buffer);
870 WRITE_STRING("</ele>\n");
879 WRITE_STRING("<time>");
880 strftime(buffer, sizeof(buffer), XML_DATE_FORMAT, localtime(&curr->time));
881 WRITE_STRING(buffer);
882 WRITE_STRING(XML_TZONE);
883 WRITE_STRING("</time>\n");
886 if (wcurr && curr == wcurr->point) {
893 desc=g_markup_printf_escaped("<desc>%s</desc>\n", wcurr->desc);
900 WRITE_STRING("/>\n");
902 WRITE_STRING("</trkpt>\n");
908 /* Write the footer. */
909 WRITE_STRING("</trkseg>\n</trk>\n</gpx>\n");
915 * Handle a start tag in the parsing of a GPX file.
917 #define MACRO_SET_UNKNOWN(utag) { \
918 data->prev_state = data->state; \
919 data->state = UNKNOWN; \
920 data->unknown_depth = 1; \
921 g_debug("GPX: unknown tag [%s]", (gchar *)utag); }
924 gpx_start_element(SaxData *data, const xmlChar *name, const xmlChar **attrs)
926 switch (data->state) {
930 if (!strcmp((gchar *) name, "gpx"))
931 data->state = INSIDE_GPX;
933 MACRO_SET_UNKNOWN(name);
936 if (!strcmp((gchar *) name, "trk"))
937 data->state = INSIDE_PATH;
938 else if (!strcmp((gchar *) name, "metadata"))
939 data->state = INSIDE_METADATA;
941 MACRO_SET_UNKNOWN(name);
943 case INSIDE_METADATA:
946 if (!strcmp((gchar *) name, "trkseg")) {
947 data->state = INSIDE_PATH_SEGMENT;
948 data->at_least_one_trkpt = FALSE;
950 MACRO_SET_UNKNOWN(name);
952 case INSIDE_PATH_SEGMENT:
953 if (!strcmp((gchar *) name, "trkpt")) {
954 const xmlChar **curr_attr;
956 gdouble lat = 0.f, lon = 0.f;
957 gboolean has_lat, has_lon;
960 for (curr_attr = attrs; *curr_attr != NULL;) {
961 const gchar *attr_name = *curr_attr++;
962 const gchar *attr_val = *curr_attr++;
963 if (!strcmp(attr_name, "lat")) {
964 lat = g_ascii_strtod(attr_val, &error_check);
965 if (error_check != attr_val)
967 } else if (!strcmp(attr_name, "lon")) {
968 lon = g_ascii_strtod(attr_val, &error_check);
969 if (error_check != attr_val)
973 if (has_lat && has_lon) {
974 path_add_latlon(data->path, lat, lon, 0, 0, NAN);
975 data->state = INSIDE_PATH_POINT;
979 MACRO_SET_UNKNOWN(name);
981 case INSIDE_PATH_POINT:
982 if (!strcmp((gchar *) name, "time"))
983 data->state = INSIDE_PATH_POINT_TIME;
984 else if (!strcmp((gchar *) name, "ele"))
985 data->state = INSIDE_PATH_POINT_ELE;
986 else if (!strcmp((gchar *) name, "desc"))
987 data->state = INSIDE_PATH_POINT_DESC;
988 else if (!strcmp((gchar *) name, "name"))
989 data->state = INSIDE_PATH_POINT_NAME;
991 MACRO_SET_UNKNOWN(name);
994 data->unknown_depth++;
1002 * Handle an end tag in the parsing of a GPX file.
1005 gpx_end_element(SaxData * data, const xmlChar * name)
1007 switch (data->state) {
1012 data->state = ERROR;
1015 if (!strcmp((gchar *) name, "gpx"))
1016 data->state = FINISH;
1018 data->state = ERROR;
1020 case INSIDE_METADATA:
1021 if (!strcmp((gchar *) name, "metadata"))
1022 data->state = INSIDE_GPX;
1025 if (!strcmp((gchar *) name, "trk"))
1026 data->state = INSIDE_GPX;
1028 data->state = ERROR;
1030 case INSIDE_PATH_SEGMENT:
1031 if (!strcmp((gchar *) name, "trkseg")) {
1032 if (data->at_least_one_trkpt) {
1033 path_add_break(data->path);
1035 data->state = INSIDE_PATH;
1037 data->state = ERROR;
1039 case INSIDE_PATH_POINT:
1040 if (!strcmp((gchar *) name, "trkpt")) {
1041 data->state = INSIDE_PATH_SEGMENT;
1042 data->at_least_one_trkpt = TRUE;
1044 data->state = ERROR;
1046 case INSIDE_PATH_POINT_ELE:
1047 if (!strcmp((gchar *) name, "ele")) {
1049 data->path->tail->altitude = g_ascii_strtod(data->chars->str, &error_check);
1050 if (error_check == data->chars->str)
1051 data->path->tail->altitude = NAN;
1052 data->state = INSIDE_PATH_POINT;
1053 g_string_free(data->chars, TRUE);
1054 data->chars = g_string_new("");
1056 data->state = ERROR;
1058 case INSIDE_PATH_POINT_TIME:
1059 if (!strcmp((gchar *) name, "time")) {
1063 if (NULL == (ptr = strptime(data->chars->str, XML_DATE_FORMAT, &time)))
1064 /* Failed to parse dateTime format. */
1065 data->state = ERROR;
1067 /* Parse was successful. Now we have to parse timezone.
1068 * From here on, if there is an error, I just assume local
1069 * timezone. Yes, this is not proper XML, but I don't
1073 /* First, set time in "local" time zone. */
1074 data->path->tail->time = (mktime(&time));
1076 /* Now, skip inconsequential characters */
1077 while (*ptr && *ptr != 'Z' && *ptr != '-' && *ptr != '+')
1080 /* Check if we ran to the end of the string. */
1082 /* Next character is either 'Z', '-', or '+' */
1084 /* Zulu (UTC) time. Undo the local time zone's offset. */
1085 data->path->tail->time += time.tm_gmtoff;
1087 /* Not Zulu (UTC). Must parse hours and minutes. */
1088 gint offhours = strtol(ptr, &error_check, 10);
1089 if (error_check != ptr && *(ptr = error_check) == ':') {
1090 /* Parse of hours worked. Check minutes. */
1091 gint offmins = strtol(ptr + 1, &error_check, 10);
1092 if (error_check != (ptr + 1)) {
1093 /* Parse of minutes worked. Calculate. */
1094 data->path->tail->time += (time.tm_gmtoff - (offhours * 60 * 60 + offmins * 60));
1099 /* Successfully parsed dateTime. */
1100 data->state = INSIDE_PATH_POINT;
1103 g_string_free(data->chars, TRUE);
1104 data->chars = g_string_new("");
1106 data->state = ERROR;
1109 case INSIDE_PATH_POINT_DESC:
1110 /* only parse description for routes */
1111 if (!strcmp((gchar *) name, "desc")) {
1112 path_insert_mark_text(data->path, g_string_free(data->chars, FALSE));
1113 data->chars=g_string_new("");
1114 data->state=INSIDE_PATH_POINT;
1119 case INSIDE_PATH_POINT_NAME:
1120 /* Just ignore these for now */
1121 g_string_free(data->chars, FALSE);
1122 data->chars=g_string_new("");
1123 data->state=INSIDE_PATH_POINT;
1126 if (!--data->unknown_depth)
1127 data->state=data->prev_state;
1137 * Handle char data in the parsing of a GPX file.
1140 gpx_chars(SaxData *data, const xmlChar *ch, int len)
1144 switch (data->state) {
1148 case INSIDE_PATH_POINT_ELE:
1149 case INSIDE_PATH_POINT_TIME:
1150 case INSIDE_PATH_POINT_DESC:
1151 case INSIDE_PATH_POINT_NAME:
1152 for (i = 0; i < len; i++)
1153 data->chars = g_string_append_c(data->chars, ch[i]);
1154 /* g_debug("GPXC: %s", data->chars->str); */
1163 * Handle an entity in the parsing of a GPX file. We don't do anything
1167 gpx_get_entity(SaxData *data, const xmlChar *name)
1169 return xmlGetPredefinedEntity(name);
1173 * Handle an error in the parsing of a GPX file.
1176 gpx_error(SaxData *data, const gchar *msg, ...)
1180 va_start(args, msg);
1181 g_logv("GPX", G_LOG_LEVEL_WARNING, msg, args);
1184 data->state = ERROR;
1194 * Parse a buffer of GPX data.
1195 * XXX: Add support for parsing directly from file if the file is local.
1199 path_gpx_parse(Path *path, gchar *buffer, gint size, gpx_path_policy policy)
1202 xmlSAXHandler sax_handler;
1206 data.chars=g_string_new("");
1208 if (policy==GPX_PATH_NEW)
1211 memset(&sax_handler, 0, sizeof(sax_handler));
1212 sax_handler.characters=(charactersSAXFunc) gpx_chars;
1213 sax_handler.startElement=(startElementSAXFunc) gpx_start_element;
1214 sax_handler.endElement=(endElementSAXFunc) gpx_end_element;
1215 sax_handler.entityDecl=(entityDeclSAXFunc) gpx_get_entity;
1216 sax_handler.warning=(warningSAXFunc) gpx_error;
1217 sax_handler.error=(errorSAXFunc) gpx_error;
1218 sax_handler.fatalError=(fatalErrorSAXFunc) gpx_error;
1220 xmlSAXUserParseMemory(&sax_handler, &data, buffer, size);
1222 g_string_free(data.chars, TRUE);
1224 if (data.state!=FINISH) {
1225 g_warning("GPX: Parser stopped in error state %d", data.state);
1230 case GPX_PATH_APPEND:
1231 case GPX_PATH_PREPEND:
1236 if (policy==GPX_PATH_APPEND) {
1237 /* Append to current path. Make sure last path point is zero. */
1238 path_add_break(path);
1242 /* Prepend to current route. */
1247 /* Find src_first non-zero point. */
1248 for (src_first = src->head; src_first++ != src->tail;)
1249 if (src_first->unity && src_first->unitx)
1252 /* Append route points from src to dest. */
1253 if (src->tail >= src_first) {
1255 guint num_dest_points = dest->tail - dest->head + 1;
1256 guint num_src_points = src->tail - src_first + 1;
1258 /* Adjust dest->tail to be able to fit src route data
1259 * plus room for more route data. */
1260 path_resize(dest, num_dest_points + num_src_points);
1262 memcpy(dest->tail + 1, src_first, num_src_points * sizeof(Point));
1264 dest->tail += num_src_points;
1266 /* Append waypoints from src to dest->. */
1267 path_wresize(dest, (dest->wtail - dest->whead) + (src->wtail - src->whead) + 2);
1268 for (curr = src->whead - 1; curr++ != src->wtail;) {
1269 (++(dest->wtail))->point = dest->head + num_dest_points + (curr->point - src_first);
1270 dest->wtail->desc = curr->desc;
1274 /* Kill old route - don't use MACRO_PATH_FREE(), because that
1275 * would free the string desc's that we just moved to data.route. */
1278 if (policy==GPX_PATH_PREPEND)
1286 g_assert_not_reached();
1293 /******************************************************************************/
1297 path_store_append_waypoint(GtkListStore *, WayPoint *w)
1299 gchar tmp1[16], tmp2[16];
1302 unit2latlon(wcurr->point->unitx, wcurr->point->unity, lat2, lon2);
1303 lat_format(_degformat, lat2, tmp1);
1304 lon_format(_degformat, lon2, tmp2);
1306 g_snprintf(buffer1, sizeof(buffer1), "%s,%s", tmp1, tmp2);
1307 sum += calculate_distance(lat1, lon1, lat2, lon2);
1308 g_snprintf(buffer2, sizeof(buffer2), "%.02f %s", sum * UNITS_CONVERT[_units], UNITS_TEXT[_units]);
1310 gtk_list_store_append(store, &iter);
1311 gtk_list_store_set(store, &iter,
1312 PATH_LATLON, buffer1,
1313 PATH_DISTANCE, buffer2,
1314 PATH_WAYPOINT, wcurr->desc,
1325 * Generate a GtkListStore with information about path waypoints (location, distance)
1328 path_get_waypoints_store(Path *path)
1332 GtkListStore *store;
1335 gchar tmp1[16], tmp2[16];
1336 gdouble lat1, lon1, lat2, lon2;
1339 g_return_val_if_fail(path!=NULL, NULL);
1343 g_return_val_if_fail(wcurr!=NULL, NULL);
1344 g_return_val_if_fail(wcurr->point!=NULL, NULL);
1345 if (!path_has_waypoints(path))
1348 store=gtk_list_store_new(PATH_NUM_COLUMNS, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_DOUBLE, G_TYPE_DOUBLE);
1350 unit2latlon(wcurr->point->unitx, wcurr->point->unity, lat1, lon1);
1352 while (wcurr!=path->wtail) {
1356 if (!wcurr->point) {
1357 g_debug("PSTORE: No point for waypoint (%s) skipping", wcurr->desc);
1362 unit2latlon(wcurr->point->unitx, wcurr->point->unity, lat2, lon2);
1363 lat_format(_degformat, lat2, tmp1);
1364 lon_format(_degformat, lon2, tmp2);
1366 g_snprintf(buffer1, sizeof(buffer1), "%s,%s", tmp1, tmp2);
1367 sum += calculate_distance(lat1, lon1, lat2, lon2);
1368 g_snprintf(buffer2, sizeof(buffer2), "%.02f %s", sum * UNITS_CONVERT[_units], UNITS_TEXT[_units]);
1370 gtk_list_store_append(store, &iter);
1371 gtk_list_store_set(store, &iter,
1372 PATH_LATLON, buffer1,
1373 PATH_DISTANCE, buffer2,
1374 PATH_WAYPOINT, wcurr->desc,