]> git.itanic.dy.fi Git - maemo-mapper/blob - src/path.c
Added button to swap contents of origin and destination in "Download
[maemo-mapper] / src / path.c
1 /*
2  * Copyright (C) 2006, 2007 John Costigan.
3  *
4  * POI and GPS-Info code originally written by Cezary Jackiewicz.
5  *
6  * Default map data provided by http://www.openstreetmap.org/
7  *
8  * This file is part of Maemo Mapper.
9  *
10  * Maemo Mapper 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 3 of the License, or
13  * (at your option) any later version.
14  *
15  * Maemo Mapper 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 Maemo Mapper.  If not, see <http://www.gnu.org/licenses/>.
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #    include "config.h"
26 #endif
27
28 #define _GNU_SOURCE
29
30 #include <stdlib.h>
31 #include <string.h>
32 #include <math.h>
33 #include <bt-dbus.h>
34 #include <sqlite3.h>
35
36 #ifndef LEGACY
37 #    include <hildon/hildon-help.h>
38 #    include <hildon/hildon-note.h>
39 #    include <hildon/hildon-banner.h>
40 #    include <hildon/hildon-sound.h>
41 #else
42 #    include <osso-helplib.h>
43 #    include <hildon-widgets/hildon-note.h>
44 #    include <hildon-widgets/hildon-banner.h>
45 #    include <hildon-widgets/hildon-system-sound.h>
46 #    include <hildon-widgets/hildon-input-mode-hint.h>
47 #endif
48
49 #include "types.h"
50 #include "data.h"
51 #include "defines.h"
52
53 #include "display.h"
54 #include "gdk-pixbuf-rotate.h"
55 #include "gpx.h"
56 #include "main.h"
57 #include "path.h"
58 #include "poi.h"
59 #include "util.h"
60
61 typedef struct _RouteDownloadInfo RouteDownloadInfo;
62 struct _RouteDownloadInfo {
63     GtkWidget *rad_use_gps;
64     GtkWidget *rad_use_route;
65     GtkWidget *rad_use_text;
66     GtkWidget *chk_avoid_highways;
67     GtkWidget *chk_auto;
68     GtkWidget *txt_from;
69     GtkWidget *txt_to;
70 };
71
72 /* _near_point is the route point to which we are closest. */
73 static Point *_near_point = NULL;
74
75 /* _next_way is what we currently interpret to be the next waypoint. */
76 static WayPoint *_next_way;
77 static gint64 _next_way_dist_squared = INT64_MAX;
78
79 /* _next_wpt is the route point immediately following _next_way. */
80 static Point *_next_wpt = NULL;
81 static gint64 _next_wpt_dist_squared = INT64_MAX;
82
83 static gfloat _initial_distance_from_waypoint = -1.f;
84 static WayPoint *_initial_distance_waypoint = NULL;
85
86 static sqlite3 *_path_db = NULL;
87 static sqlite3_stmt *_track_stmt_select = NULL;
88 static sqlite3_stmt *_track_stmt_delete_path = NULL;
89 static sqlite3_stmt *_track_stmt_delete_way = NULL;
90 static sqlite3_stmt *_track_stmt_insert_path = NULL;
91 static sqlite3_stmt *_track_stmt_insert_way = NULL;
92 static sqlite3_stmt *_route_stmt_select = NULL;
93 static sqlite3_stmt *_route_stmt_delete_path = NULL;
94 static sqlite3_stmt *_route_stmt_delete_way = NULL;
95 static sqlite3_stmt *_route_stmt_insert_path = NULL;
96 static sqlite3_stmt *_route_stmt_insert_way = NULL;
97 static sqlite3_stmt *_path_stmt_trans_begin = NULL;
98 static sqlite3_stmt *_path_stmt_trans_commit = NULL;
99 static sqlite3_stmt *_path_stmt_trans_rollback = NULL;
100
101 static gchar *_last_spoken_phrase;
102
103 void
104 path_resize(Path *path, gint size)
105 {
106     printf("%s()\n", __PRETTY_FUNCTION__);
107
108     if(path->head + size != path->cap)
109     {
110         Point *old_head = path->head;
111         WayPoint *curr;
112         path->head = g_renew(Point, old_head, size);
113         path->cap = path->head + size;
114         if(path->head != old_head)
115         {
116             path->tail = path->head + (path->tail - old_head);
117
118             /* Adjust all of the waypoints. */
119             for(curr = path->whead - 1; curr++ != path->wtail; )
120                 curr->point = path->head + (curr->point - old_head);
121         }
122     }
123
124     vprintf("%s(): return\n", __PRETTY_FUNCTION__);
125 }
126
127 void
128 path_wresize(Path *path, gint wsize)
129 {
130     printf("%s()\n", __PRETTY_FUNCTION__);
131
132     if(path->whead + wsize != path->wcap)
133     {
134         WayPoint *old_whead = path->whead;
135         path->whead = g_renew(WayPoint, old_whead, wsize);
136         path->wtail = path->whead + (path->wtail - old_whead);
137         path->wcap = path->whead + wsize;
138     }
139
140     vprintf("%s(): return\n", __PRETTY_FUNCTION__);
141 }
142
143 static void
144 read_path_from_db(Path *path, sqlite3_stmt *select_stmt)
145 {
146     printf("%s()\n", __PRETTY_FUNCTION__);
147
148     MACRO_PATH_INIT(*path);
149     while(SQLITE_ROW == sqlite3_step(select_stmt))
150     {
151         const gchar *desc;
152
153         MACRO_PATH_INCREMENT_TAIL(*path);
154         path->tail->unitx = sqlite3_column_int(select_stmt, 0);
155         path->tail->unity = sqlite3_column_int(select_stmt, 1);
156         path->tail->time = sqlite3_column_int(select_stmt, 2);
157         path->tail->altitude = sqlite3_column_int(select_stmt, 3);
158
159         desc = sqlite3_column_text(select_stmt, 4);
160         if(desc)
161         {
162             MACRO_PATH_INCREMENT_WTAIL(*path);
163             path->wtail->point = path->tail;
164             path->wtail->desc = g_strdup(desc);
165         }
166     }
167     sqlite3_reset(select_stmt);
168
169     /* If the last point isn't null, then add another null point. */
170     if(path->tail->unity)
171     {
172         MACRO_PATH_INCREMENT_TAIL(*path);
173         *path->tail = _point_null;
174     }
175
176     vprintf("%s(): return\n", __PRETTY_FUNCTION__);
177 }
178
179 /* Returns the new next_update_index. */
180 static gint
181 write_path_to_db(Path *path,
182         sqlite3_stmt *delete_path_stmt,
183         sqlite3_stmt *delete_way_stmt,
184         sqlite3_stmt *insert_path_stmt,
185         sqlite3_stmt *insert_way_stmt,
186         gint index_last_saved)
187 {
188     Point *curr;
189     WayPoint *wcurr;
190     gint num;
191     gboolean success = TRUE;
192     printf("%s(%d)\n", __PRETTY_FUNCTION__, index_last_saved);
193
194     /* Start transaction. */
195     sqlite3_step(_path_stmt_trans_begin);
196     sqlite3_reset(_path_stmt_trans_begin);
197
198     if(index_last_saved == 0)
199     {
200         /* Replace the whole thing, so delete the table first. */
201         if(SQLITE_DONE != sqlite3_step(delete_way_stmt)
202                 || SQLITE_DONE != sqlite3_step(delete_path_stmt))
203         {
204             gchar buffer[BUFFER_SIZE];
205             snprintf(buffer, sizeof(buffer), "%s\n%s",
206                     _("Failed to write to path database. "
207                         "Tracks and routes may not be saved."),
208                     sqlite3_errmsg(_path_db));
209             popup_error(_window, buffer);
210             success = FALSE;
211         }
212         sqlite3_reset(delete_way_stmt);
213         sqlite3_reset(delete_path_stmt);
214     }
215
216     for(num = index_last_saved, curr = path->head + num, wcurr = path->whead;
217             success && ++curr <= path->tail; ++num)
218     {
219         /* If this is the last point, and it is null, don't write it. */
220         if(curr == path->tail && !curr->unity)
221             break;
222
223         /* Insert the path point. */
224         if(SQLITE_OK != sqlite3_bind_int(insert_path_stmt, 1, curr->unitx)
225         || SQLITE_OK != sqlite3_bind_int(insert_path_stmt, 2, curr->unity)
226         || SQLITE_OK != sqlite3_bind_int(insert_path_stmt, 3, curr->time)
227         || SQLITE_OK != sqlite3_bind_int(insert_path_stmt, 4, curr->altitude)
228         || SQLITE_DONE != sqlite3_step(insert_path_stmt))
229         {
230             gchar buffer[BUFFER_SIZE];
231             snprintf(buffer, sizeof(buffer), "%s\n%s",
232                     _("Failed to write to path database. "
233                         "Tracks and routes may not be saved."),
234                     sqlite3_errmsg(_path_db));
235             popup_error(_window, buffer);
236             success = FALSE;
237         }
238         sqlite3_reset(insert_path_stmt);
239
240         /* Now, check if curr is a waypoint. */
241         if(success && wcurr <= path->wtail && wcurr->point == curr)
242         {
243             gint num = sqlite3_last_insert_rowid(_path_db);
244             if(SQLITE_OK != sqlite3_bind_int(insert_way_stmt, 1, num)
245             || SQLITE_OK != sqlite3_bind_text(insert_way_stmt, 2, wcurr->desc,
246                 -1, SQLITE_STATIC)
247             || SQLITE_DONE != sqlite3_step(insert_way_stmt))
248             {
249                 gchar buffer[BUFFER_SIZE];
250                 snprintf(buffer, sizeof(buffer), "%s\n%s",
251                         _("Failed to write to path database. "
252                             "Tracks and routes may not be saved."),
253                         sqlite3_errmsg(_path_db));
254                 popup_error(_window, buffer);
255                 success = FALSE;
256             }
257             sqlite3_reset(insert_way_stmt);
258             wcurr++;
259         }
260     }
261     if(success)
262     {
263         sqlite3_step(_path_stmt_trans_commit);
264         sqlite3_reset(_path_stmt_trans_commit);
265         vprintf("%s(): return TRUE\n", __PRETTY_FUNCTION__);
266         return num;
267     }
268     else
269     {
270         sqlite3_step(_path_stmt_trans_rollback);
271         sqlite3_reset(_path_stmt_trans_rollback);
272         vprintf("%s(): return 0\n", __PRETTY_FUNCTION__);
273         return index_last_saved;
274     }
275 }
276
277 void
278 path_save_route_to_db()
279 {
280     if(_path_db)
281     {
282         write_path_to_db(&_route,
283                           _route_stmt_delete_path,
284                           _route_stmt_delete_way,
285                           _route_stmt_insert_path,
286                           _route_stmt_insert_way,
287                           0);
288     }
289 }
290
291 static void
292 path_save_track_to_db()
293 {
294     if(_path_db)
295     {
296         write_path_to_db(&_track,
297                           _track_stmt_delete_path,
298                           _track_stmt_delete_way,
299                           _track_stmt_insert_path,
300                           _track_stmt_insert_way,
301                           0);
302     }
303 }
304
305 static void
306 path_update_track_in_db()
307 {
308     if(_path_db)
309     {
310         _track_index_last_saved = write_path_to_db(&_track,
311                           _track_stmt_delete_path,
312                           _track_stmt_delete_way,
313                           _track_stmt_insert_path,
314                           _track_stmt_insert_way,
315                           _track_index_last_saved);
316     }
317 }
318
319 /**
320  * Updates _near_point, _next_way, and _next_wpt.  If quick is FALSE (as
321  * it is when this function is called from route_find_nearest_point), then
322  * the entire list (starting from _near_point) is searched.  Otherwise, we
323  * stop searching when we find a point that is farther away.
324  */
325 static gboolean
326 route_update_nears(gboolean quick)
327 {
328     gboolean ret = FALSE;
329     Point *curr, *near;
330     WayPoint *wcurr, *wnext;
331     gint64 near_dist_squared;
332     printf("%s(%d)\n", __PRETTY_FUNCTION__, quick);
333
334     /* If we have waypoints (_next_way != NULL), then determine the "next
335      * waypoint", which is defined as the waypoint after the nearest point,
336      * UNLESS we've passed that waypoint, in which case the waypoint after
337      * that waypoint becomes the "next" waypoint. */
338     if(_next_way)
339     {
340         /* First, set near_dist_squared with the new distance from
341          * _near_point. */
342         near = _near_point;
343         near_dist_squared = DISTANCE_SQUARED(_pos, *near);
344
345         /* Now, search _route for a closer point.  If quick is TRUE, then we'll
346          * only search forward, only as long as we keep finding closer points.
347          */
348         for(curr = _near_point; curr++ != _route.tail; )
349         {
350             if(curr->unity)
351             {
352                 gint64 dist_squared = DISTANCE_SQUARED(_pos, *curr);
353                 if(dist_squared <= near_dist_squared)
354                 {
355                     near = curr;
356                     near_dist_squared = dist_squared;
357                 }
358                 else if(quick)
359                     break;
360             }
361         }
362
363         /* Update _near_point. */
364         _near_point = near;
365
366         for(wnext = wcurr = _next_way; wcurr < _route.wtail; wcurr++)
367         {
368             if(wcurr->point < near
369             /* Okay, this else if expression warrants explanation.  If the
370              * nearest track point happens to be a waypoint, then we want to
371              * check if we have "passed" that waypoint.  To check this, we
372              * test the distance from _pos to the waypoint and from _pos to
373              * _next_wpt, and if the former is increasing and the latter is
374              * decreasing, then we have passed the waypoint, and thus we
375              * should skip it.  Note that if there is no _next_wpt, then
376              * there is no next waypoint, so we do not skip it in that case. */
377                 || (wcurr->point == near && quick
378                     && (_next_wpt
379                      && (DISTANCE_SQUARED(_pos, *near) > _next_way_dist_squared
380                       && DISTANCE_SQUARED(_pos, *_next_wpt)
381                                                    < _next_wpt_dist_squared))))
382             {
383                 wnext = wcurr + 1;
384             }
385             else
386                 break;
387         }
388
389         if(wnext == _route.wtail && (wnext->point < near
390                 || (wnext->point == near && quick
391                     && (_next_wpt
392                      && (DISTANCE_SQUARED(_pos, *near) > _next_way_dist_squared
393                       &&DISTANCE_SQUARED(_pos, *_next_wpt)
394                                                  < _next_wpt_dist_squared)))))
395         {
396             _next_way = NULL;
397             _next_wpt = NULL;
398             _next_way_dist_squared = INT64_MAX;
399             _next_wpt_dist_squared = INT64_MAX;
400             ret = TRUE;
401         }
402         /* Only update _next_way (and consequently _next_wpt) if _next_way is
403          * different, and record that fact for return. */
404         else
405         {
406             if(!quick || _next_way != wnext)
407             {
408                 _next_way = wnext;
409                 _next_wpt = wnext->point;
410                 if(_next_wpt == _route.tail)
411                     _next_wpt = NULL;
412                 else
413                 {
414                     while(!(++_next_wpt)->unity)
415                     {
416                         if(_next_wpt == _route.tail)
417                         {
418                             _next_wpt = NULL;
419                             break;
420                         }
421                     }
422                 }
423                 ret = TRUE;
424             }
425             _next_way_dist_squared = DISTANCE_SQUARED(_pos, *wnext->point);
426             if(_next_wpt)
427                 _next_wpt_dist_squared = DISTANCE_SQUARED(_pos, *_next_wpt);
428         }
429     }
430
431     vprintf("%s(): return %d\n", __PRETTY_FUNCTION__, ret);
432     return ret;
433 }
434
435 /**
436  * Reset the _near_point data by searching the entire route for the nearest
437  * route point and waypoint.
438  */
439 void
440 route_find_nearest_point()
441 {
442     printf("%s()\n", __PRETTY_FUNCTION__);
443
444     /* Initialize _near_point to first non-zero point. */
445     _near_point = _route.head;
446     while(!_near_point->unity && _near_point != _route.tail)
447         _near_point++;
448
449     /* Initialize _next_way. */
450     if(_route.wtail < _route.whead
451             || (_autoroute_data.enabled && _route.wtail == _route.whead))
452         _next_way = NULL;
453     else
454         /* We have at least one waypoint. */
455         _next_way = _autoroute_data.enabled ? _route.whead + 1 : _route.whead;
456     _next_way_dist_squared = INT64_MAX;
457
458     /* Initialize _next_wpt. */
459     _next_wpt = NULL;
460     _next_wpt_dist_squared = INT64_MAX;
461
462     route_update_nears(FALSE);
463
464     vprintf("%s(): return\n", __PRETTY_FUNCTION__);
465 }
466
467 /**
468  * Show the distance from the current GPS location to the given point,
469  * following the route.  If point is NULL, then the distance is shown to the
470  * next waypoint.
471  */
472 gboolean
473 route_show_distance_to(Point *point)
474 {
475     gchar buffer[80];
476     gdouble lat1, lon1, lat2, lon2;
477     gdouble sum = 0.0;
478     printf("%s()\n", __PRETTY_FUNCTION__);
479
480     /* If point is NULL, use the next waypoint. */
481     if(point == NULL && _next_way)
482         point = _next_way->point;
483
484     /* If point is still NULL, return an error. */
485     if(point == NULL)
486     {
487         printf("%s(): return FALSE\n", __PRETTY_FUNCTION__);
488         return FALSE;
489     }
490
491     unit2latlon(_pos.unitx, _pos.unity, lat1, lon1);
492     if(point > _near_point)
493     {
494         Point *curr;
495         /* Skip _near_point in case we have already passed it. */
496         for(curr = _near_point + 1; curr <= point; ++curr)
497         {
498             if(curr->unity)
499             {
500                 unit2latlon(curr->unitx, curr->unity, lat2, lon2);
501                 sum += calculate_distance(lat1, lon1, lat2, lon2);
502                 lat1 = lat2;
503                 lon1 = lon2;
504             }
505         }
506     }
507     else if(point < _near_point)
508     {
509         Point *curr;
510         /* Skip _near_point in case we have already passed it. */
511         for(curr = _near_point - 1; curr >= point; --curr)
512         {
513             if(curr->unity)
514             {
515                 unit2latlon(curr->unitx, curr->unity, lat2, lon2);
516                 sum += calculate_distance(lat1, lon1, lat2, lon2);
517                 lat1 = lat2;
518                 lon1 = lon2;
519             }
520         }
521     }
522     else
523     {
524         /* Waypoint _is_ the nearest point. */
525         unit2latlon(_near_point->unitx, _near_point->unity, lat2, lon2);
526         sum += calculate_distance(lat1, lon1, lat2, lon2);
527     }
528
529     snprintf(buffer, sizeof(buffer), "%s: %.02f %s", _("Distance"),
530             sum * UNITS_CONVERT[_units], UNITS_ENUM_TEXT[_units]);
531     MACRO_BANNER_SHOW_INFO(_window, buffer);
532
533     return TRUE;
534     printf("%s(): return TRUE\n", __PRETTY_FUNCTION__);
535 }
536
537 void
538 route_show_distance_to_next()
539 {
540     printf("%s()\n", __PRETTY_FUNCTION__);
541
542     if(!route_show_distance_to(NULL))
543     {
544         MACRO_BANNER_SHOW_INFO(_window, _("There is no next waypoint."));
545     }
546     printf("%s(): return\n", __PRETTY_FUNCTION__);
547 }
548
549 void
550 route_show_distance_to_last()
551 {
552     printf("%s()\n", __PRETTY_FUNCTION__);
553
554     if(_route.head != _route.tail)
555     {
556         /* Find last non-zero point. */
557         Point *p;
558         for(p = _route.tail; !p->unity; p--) { }
559         route_show_distance_to(p);
560     }
561     else
562     {
563         MACRO_BANNER_SHOW_INFO(_window, _("The current route is empty."));
564     }
565     printf("%s(): return\n", __PRETTY_FUNCTION__);
566 }
567
568 static void
569 track_show_distance_from(Point *point)
570 {
571     gchar buffer[80];
572     gdouble lat1, lon1, lat2, lon2;
573     gdouble sum = 0.0;
574     Point *curr;
575     unit2latlon(_pos.unitx, _pos.unity, lat1, lon1);
576
577     /* Skip _track.tail because that should be _pos. */
578     for(curr = _track.tail; curr > point; --curr)
579     {
580         if(curr->unity)
581         {
582             unit2latlon(curr->unitx, curr->unity, lat2, lon2);
583             sum += calculate_distance(lat1, lon1, lat2, lon2);
584             lat1 = lat2;
585             lon1 = lon2;
586         }
587     }
588
589     snprintf(buffer, sizeof(buffer), "%s: %.02f %s", _("Distance"),
590             sum * UNITS_CONVERT[_units], UNITS_ENUM_TEXT[_units]);
591     MACRO_BANNER_SHOW_INFO(_window, buffer);
592 }
593
594 void
595 track_show_distance_from_last()
596 {
597     printf("%s()\n", __PRETTY_FUNCTION__);
598
599     /* Find last zero point. */
600     if(_track.head != _track.tail)
601     {
602         Point *point;
603         /* Find last zero point. */
604         for(point = _track.tail; point->unity; point--) { }
605         track_show_distance_from(point);
606     }
607     else
608     {
609         MACRO_BANNER_SHOW_INFO(_window, _("The current track is empty."));
610     }
611     printf("%s(): return\n", __PRETTY_FUNCTION__);
612 }
613
614 void
615 track_show_distance_from_first()
616 {
617     printf("%s()\n", __PRETTY_FUNCTION__);
618
619     /* Find last zero point. */
620     if(_track.head != _track.tail)
621         track_show_distance_from(_track.head);
622     else
623     {
624         MACRO_BANNER_SHOW_INFO(_window, _("The current track is empty."));
625     }
626     printf("%s(): return\n", __PRETTY_FUNCTION__);
627 }
628
629 static gboolean
630 route_download_and_setup(GtkWidget *parent, const gchar *source_url,
631         const gchar *from, const gchar *to,
632         gboolean avoid_highways, gint replace_policy)
633 {
634     gchar *from_escaped;
635     gchar *to_escaped;
636     gchar *buffer;
637     gchar *bytes;
638     gint size;
639     GnomeVFSResult vfs_result;
640     printf("%s(%s, %s)\n", __PRETTY_FUNCTION__, from, to);
641
642     from_escaped = gnome_vfs_escape_string(from);
643     to_escaped = gnome_vfs_escape_string(to);
644     buffer = g_strdup_printf(source_url, from_escaped, to_escaped);
645     g_free(from_escaped);
646     g_free(to_escaped);
647
648     if(avoid_highways)
649     {
650         gchar *old = buffer;
651         buffer = g_strconcat(old, "&avoid_highways=on", NULL);
652         g_free(old);
653     }
654
655     /* Attempt to download the route from the server. */
656     vfs_result = gnome_vfs_read_entire_file(buffer, &size, &bytes);
657     g_free (buffer);
658
659     if(vfs_result != GNOME_VFS_OK)
660     {
661         g_free(bytes);
662         popup_error(parent, gnome_vfs_result_to_string(vfs_result));
663         vprintf("%s(): return FALSE\n", __PRETTY_FUNCTION__);
664         return FALSE;
665     }
666
667     if(strncmp(bytes, "<?xml", strlen("<?xml")))
668     {
669         /* Not an XML document - must be bad locations. */
670         popup_error(parent,
671                 _("Invalid source or destination."));
672         g_free(bytes);
673         vprintf("%s(): return FALSE\n", __PRETTY_FUNCTION__);
674         return FALSE;
675     }
676     /* Else, if GPS is enabled, replace the route, otherwise append it. */
677     else if(gpx_path_parse(&_route, bytes, size, replace_policy))
678     {
679         path_save_route_to_db();
680
681         /* Find the nearest route point, if we're connected. */
682         route_find_nearest_point();
683
684         map_force_redraw();
685
686         MACRO_BANNER_SHOW_INFO(_window, _("Route Downloaded"));
687         g_free(bytes);
688
689         vprintf("%s(): return TRUE\n", __PRETTY_FUNCTION__);
690         return TRUE;
691     }
692     popup_error(parent, _("Error parsing GPX file."));
693     g_free(bytes);
694
695     vprintf("%s(): return FALSE\n", __PRETTY_FUNCTION__);
696     return FALSE;
697 }
698
699 /**
700  * This function is periodically run to download updated auto-route data
701  * from the route source.
702  */
703 static gboolean
704 auto_route_dl_idle()
705 {
706     gchar latstr[32], lonstr[32], latlonstr[80];
707     printf("%s(%f, %f, %s)\n", __PRETTY_FUNCTION__,
708             _gps.lat, _gps.lon, _autoroute_data.dest);
709
710     g_ascii_dtostr(latstr, 32, _gps.lat);
711     g_ascii_dtostr(lonstr, 32, _gps.lon);
712     snprintf(latlonstr, sizeof(latlonstr), "%s, %s", latstr, lonstr);
713
714     if(!route_download_and_setup(_window, _autoroute_data.source_url, latlonstr,
715             _autoroute_data.dest, _autoroute_data.avoid_highways,0))
716         cancel_autoroute();
717
718     _autoroute_data.in_progress = FALSE;
719
720     vprintf("%s(): return\n", __PRETTY_FUNCTION__);
721     return FALSE;
722 }
723
724 void
725 path_reset_route()
726 {
727     printf("%s()\n", __PRETTY_FUNCTION__);
728
729     route_find_nearest_point();
730     MACRO_MAP_RENDER_DATA();
731     MACRO_QUEUE_DRAW_AREA();
732
733     vprintf("%s(): return TRUE\n", __PRETTY_FUNCTION__);
734 }
735
736 /**
737  * Add a point to the _track list.  This function is slightly overloaded,
738  * since it is what houses the check for "have we moved
739  * significantly": it also initiates the re-calculation of the _near_point
740  * data, as well as calling osso_display_state_on() when we have the focus.
741  *
742  * If a non-zero time is given, then the current position (as taken from the
743  * _pos variable) is appended to _track with the given time.  If time is zero,
744  * then _point_null is appended to _track with time zero (this produces a
745  * "break" in the track).
746  */
747 gboolean
748 track_add(time_t time, gboolean newly_fixed)
749 {
750     gboolean show_directions = TRUE;
751     gint announce_thres_unsquared;
752     gboolean ret = FALSE;
753     printf("%s(%d, %d, %d, %d)\n", __PRETTY_FUNCTION__,
754             (guint)time, newly_fixed, _pos.unitx, _pos.unity);
755
756     if(!time)
757     {
758         /* This is a null point. */
759         MACRO_PATH_INCREMENT_TAIL(_track);
760         *_track.tail = _point_null;
761     }
762     else
763     {
764         gboolean moving = FALSE;
765         gboolean approaching_waypoint = FALSE;
766         gint xdiff, ydiff, dopcand;
767
768         announce_thres_unsquared = (20+_gps.speed) * _announce_notice_ratio*32;
769
770         if(!_track.tail->unity
771                 || ((xdiff = _pos.unitx - _track.tail->unitx), /* comma op */
772                     (ydiff = _pos.unity - _track.tail->unity), /* comma op */
773                     /* Check if xdiff or ydiff are huge. */
774                     ((abs(xdiff) >> 12) || (abs(ydiff) >> 12)
775                     /* Okay, let's see if we've moved enough to justify adding
776                      * to the track.  It depends on our error.  I'd like to
777                      * make the threshold roughly linear with respect to the
778                      * P/HDOP (completely arbitrary, I know), but I also
779                      * want to keep the threshold at a minimum of 2
780                      * zoom-level-4 pixel, and I want dop's of less than 2 to
781                      * also have a 1-pixel threshold.  I also throw in some
782                      * PDOP into the mix, just for fun. */
783                     || ((dopcand = 8 * (_gps.pdop - 6 +(_gps.hdop*_gps.hdop))),
784                         ((xdiff * xdiff) + (ydiff * ydiff)
785                              >= (MAX(2, dopcand) << 8))))))
786         {
787             /* We moved enough to actually register a move. */
788             ret = TRUE;
789
790             /* Update the nearest-waypoint data. */
791             if(_route.head != _route.tail
792                     && (newly_fixed ? (route_find_nearest_point(), TRUE)
793                                     : route_update_nears(TRUE)))
794             {
795                 /* Nearest waypoint has changed - re-render paths. */
796                 map_render_paths();
797                 MACRO_QUEUE_DRAW_AREA();
798             }
799             if(_show_paths & TRACKS_MASK)
800             {
801                 /* Instead of calling map_render_paths(), we'll draw the new
802                  * line ourselves and call gtk_widget_queue_draw_area(). */
803                 gint tx1, ty1, tx2, ty2;
804                 map_render_segment(_gc[COLORABLE_TRACK],
805                         _gc[COLORABLE_TRACK_BREAK],
806                         _track.tail->unitx, _track.tail->unity,
807                         _pos.unitx, _pos.unity);
808                 if(_track.tail->unity)
809                 {
810                     unit2screen(_track.tail->unitx, _track.tail->unity,
811                             tx1, ty1);
812                     unit2screen(_pos.unitx, _pos.unity, tx2, ty2);
813                     gtk_widget_queue_draw_area(_map_widget,
814                             MIN(tx1, tx2) - _draw_width,
815                             MIN(ty1, ty2) - _draw_width,
816                             abs(tx1 - tx2) + (2 * _draw_width),
817                             abs(ty1 - ty2) + (2 * _draw_width));
818                 }
819             }
820             MACRO_PATH_INCREMENT_TAIL(_track);
821
822             *_track.tail = _pos;
823
824             /* Calculate distance to route. (point to line) */
825             if(_near_point)
826             {
827                 gint route_x1, route_x2, route_y1, route_y2;
828                 gint64 route_dist_squared_1 = INT64_MAX;
829                 gint64 route_dist_squared_2 = INT64_MAX;
830                 gfloat slope;
831
832                 route_x1 = _near_point->unitx;
833                 route_y1 = _near_point->unity;
834
835                 /* Try previous point first. */
836                 if(_near_point != _route.head && _near_point[-1].unity)
837                 {
838                     route_x2 = _near_point[-1].unitx;
839                     route_y2 = _near_point[-1].unity;
840                     slope = (gfloat)(route_y2 - route_y1)
841                         / (gfloat)(route_x2 - route_x1);
842
843                     if(route_x1 == route_x2)
844                     {
845                         /* Vertical line special case. */
846                         route_dist_squared_1 = (_pos.unitx - route_x1)
847                             * (_pos.unitx - route_x1);
848                     }
849                     else
850                     {
851                         route_dist_squared_1 = abs((slope * _pos.unitx)
852                             - _pos.unity + (route_y1 - (slope * route_x1)));
853                         route_dist_squared_1 =
854                             route_dist_squared_1 * route_dist_squared_1
855                             / ((slope * slope) + 1);
856                     }
857                 }
858                 if(_near_point != _route.tail && _near_point[1].unity)
859                 {
860                     route_x2 = _near_point[1].unitx;
861                     route_y2 = _near_point[1].unity;
862                     slope = (gfloat)(route_y2 - route_y1)
863                         / (gfloat)(route_x2 - route_x1);
864
865                     if(route_x1 == route_x2)
866                     {
867                         /* Vertical line special case. */
868                         route_dist_squared_2 = (_pos.unitx - route_x1)
869                             * (_pos.unitx - route_x1);
870                     }
871                     else
872                     {
873                         route_dist_squared_2 = abs((slope * _pos.unitx)
874                             - _pos.unity + (route_y1 - (slope * route_x1)));
875                         route_dist_squared_2 =
876                             route_dist_squared_2 * route_dist_squared_2
877                             / ((slope * slope) + 1);
878                     }
879                 }
880
881                 /* Check if our distance from the route is large. */
882                 if(MIN(route_dist_squared_1, route_dist_squared_2)
883                         > (2000 * 2000))
884                 {
885                     /* Prevent announcments from occurring. */
886                     announce_thres_unsquared = INT_MAX;
887
888                     if(_autoroute_data.enabled && !_autoroute_data.in_progress)
889                     {
890                         MACRO_BANNER_SHOW_INFO(_window,
891                                 _("Recalculating directions..."));
892                         _autoroute_data.in_progress = TRUE;
893                         show_directions = FALSE;
894                         g_idle_add((GSourceFunc)auto_route_dl_idle, NULL);
895                     }
896                     else
897                     {
898                         /* Reset the route to try and find the nearest point.*/
899                         path_reset_route();
900                     }
901                 }
902             }
903
904             /* Keep the display on. */
905             moving = TRUE;
906         }
907
908         if(_initial_distance_waypoint
909                && (_next_way != _initial_distance_waypoint
910                ||  _next_way_dist_squared > (_initial_distance_from_waypoint
911                                            * _initial_distance_from_waypoint)))
912         {
913             /* We've moved on to the next waypoint, or we're really far from
914              * the current waypoint. */
915             if(_waypoint_banner)
916             {
917                 gtk_widget_destroy(_waypoint_banner);
918                 _waypoint_banner = NULL;
919             }
920             _initial_distance_from_waypoint = -1.f;
921             _initial_distance_waypoint = NULL;
922         }
923
924         /* Check if we should announce upcoming waypoints. */
925         if(_enable_announce
926                 && (_initial_distance_waypoint || _next_way_dist_squared
927                     < (announce_thres_unsquared * announce_thres_unsquared)))
928         {
929             if(show_directions)
930             {
931                 if(!_initial_distance_waypoint)
932                 {
933                     /* First time we're close enough to this waypoint. */
934                     if(_enable_voice
935                             /* And that we haven't already announced it. */
936                             && strcmp(_next_way->desc, _last_spoken_phrase))
937                     {
938                         g_free(_last_spoken_phrase);
939                         _last_spoken_phrase = g_strdup(_next_way->desc);
940                         if(!fork())
941                         {
942                             /* We are the fork child.  Synthesize the voice. */
943                             hildon_play_system_sound(
944                                 "/usr/share/sounds/ui-information_note.wav");
945                             sleep(1);
946 #               define _voice_synth_path "/usr/bin/flite"
947                             printf("%s %s\n", _voice_synth_path,
948                                     _last_spoken_phrase);
949                             execl(_voice_synth_path, _voice_synth_path,
950                                     "-t", _last_spoken_phrase, (char *)NULL);
951                             exit(0);
952                         }
953                     }
954                     _initial_distance_from_waypoint
955                         = sqrtf(_next_way_dist_squared);
956                     _initial_distance_waypoint = _next_way;
957                     if(_next_wpt && _next_wpt->unity != 0)
958                     {
959                         /* Create a banner for us the show progress. */
960                         _waypoint_banner = hildon_banner_show_progress(
961                                 _window, NULL, _next_way->desc);
962                     }
963                     else
964                     {
965                         /* This is the last point in a segment, i.e.
966                          * "Arrive at ..." - just announce. */
967                         MACRO_BANNER_SHOW_INFO(_window, _next_way->desc);
968                     }
969                 }
970                 else if(_waypoint_banner);
971                 {
972                     /* We're already close to this waypoint. */
973                     gdouble fraction = 1.f - (sqrtf(_next_way_dist_squared)
974                             / _initial_distance_from_waypoint);
975                     BOUND(fraction, 0.f, 1.f);
976                     hildon_banner_set_fraction(
977                             HILDON_BANNER(_waypoint_banner), fraction);
978                 }
979             }
980             approaching_waypoint = TRUE;
981         }
982         else if(_next_way_dist_squared > 2 * (_initial_distance_from_waypoint
983                                             * _initial_distance_from_waypoint))
984         {
985             /* We're too far away now - destroy the banner. */
986         }
987
988         UNBLANK_SCREEN(moving, approaching_waypoint);
989     }
990
991     /* Maybe update the track database. */
992     {
993         static time_t last_track_db_update = 0;
994         if(!time || (time - last_track_db_update > 60
995                 && _track.tail - _track.head + 1 > _track_index_last_saved))
996         {
997             path_update_track_in_db();
998             last_track_db_update = time;
999         }
1000     }
1001
1002     vprintf("%s(): return\n", __PRETTY_FUNCTION__);
1003     return ret;
1004 }
1005
1006 void
1007 track_clear()
1008 {
1009     GtkWidget *confirm;
1010
1011     confirm = hildon_note_new_confirmation(GTK_WINDOW(_window),
1012                             _("Really clear the track?"));
1013
1014     if(GTK_RESPONSE_OK == gtk_dialog_run(GTK_DIALOG(confirm))) {
1015         MACRO_PATH_FREE(_track);
1016         MACRO_PATH_INIT(_track);
1017         path_save_track_to_db();
1018         map_force_redraw();
1019     }
1020
1021     gtk_widget_destroy(confirm);
1022 }
1023
1024 void
1025 track_insert_break(gboolean temporary)
1026 {
1027     printf("%s()\n", __PRETTY_FUNCTION__);
1028
1029     if(_track.tail->unity)
1030     {
1031         gint x1, y1;
1032         unit2screen(_track.tail->unitx, _track.tail->unity, x1, y1);
1033
1034         MACRO_PATH_INCREMENT_TAIL(_track);
1035         *_track.tail = _point_null;
1036
1037         /* To mark a "waypoint" in a track, we'll add a (0, 0) point and then
1038          * another instance of the most recent track point. */
1039         if(temporary)
1040         {
1041             MACRO_PATH_INCREMENT_TAIL(_track);
1042             *_track.tail = _track.tail[-2];
1043         }
1044
1045         /** Instead of calling map_render_paths(), we'll just add the waypoint
1046          * ourselves. */
1047         /* Make sure this circle will be visible. */
1048         if((x1 < _view_width_pixels) && (y1 < _view_height_pixels))
1049             gdk_draw_arc(_map_pixmap, _gc[COLORABLE_TRACK_BREAK],
1050                     FALSE, /* FALSE: not filled. */
1051                     x1 - _draw_width,
1052                     y1 - _draw_width,
1053                     2 * _draw_width,
1054                     2 * _draw_width,
1055                     0, /* start at 0 degrees. */
1056                     360 * 64);
1057     }
1058     else if(!temporary)
1059     {
1060         MACRO_BANNER_SHOW_INFO(_window, _("Break already inserted."));
1061     }
1062
1063     vprintf("%s(): return\n", __PRETTY_FUNCTION__);
1064 }
1065
1066 /**
1067  * Cancel the current auto-route.
1068  */
1069 void
1070 cancel_autoroute()
1071 {
1072     printf("%s()\n", __PRETTY_FUNCTION__);
1073
1074     if(_autoroute_data.enabled)
1075     {
1076         _autoroute_data.enabled = FALSE;
1077         g_free(_autoroute_data.source_url);
1078         _autoroute_data.source_url = NULL;
1079         g_free(_autoroute_data.dest);
1080         _autoroute_data.dest = NULL;
1081         _autoroute_data.in_progress = FALSE;
1082     }
1083
1084     vprintf("%s(): return\n", __PRETTY_FUNCTION__);
1085 }
1086
1087 WayPoint *
1088 find_nearest_waypoint(gint unitx, gint unity)
1089 {
1090     WayPoint *wcurr;
1091     WayPoint *wnear;
1092     gint64 nearest_squared;
1093     Point pos = { unitx, unity, 0, INT_MIN };
1094     printf("%s()\n", __PRETTY_FUNCTION__);
1095
1096     wcurr = wnear = _route.whead;
1097     if(wcurr && wcurr <= _route.wtail)
1098     {
1099         nearest_squared = DISTANCE_SQUARED(pos, *(wcurr->point));
1100
1101         wnear = _route.whead;
1102         while(++wcurr <=  _route.wtail)
1103         {
1104             gint64 test_squared = DISTANCE_SQUARED(pos, *(wcurr->point));
1105             if(test_squared < nearest_squared)
1106             {
1107                 wnear = wcurr;
1108                 nearest_squared = test_squared;
1109             }
1110         }
1111
1112         /* Only use the waypoint if it is within a 6*_draw_width square drawn
1113          * around the position. This is consistent with select_poi(). */
1114         if(abs(unitx - wnear->point->unitx) < pixel2unit(3 * _draw_width)
1115             && abs(unity - wnear->point->unity) < pixel2unit(3 * _draw_width))
1116             return wnear;
1117     }
1118
1119     vprintf("%s(): return\n", __PRETTY_FUNCTION__);
1120     return NULL;
1121 }
1122
1123 static gboolean
1124 origin_type_selected(GtkWidget *toggle, RouteDownloadInfo *oti)
1125 {
1126     printf("%s()\n", __PRETTY_FUNCTION__);
1127
1128     if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(toggle)))
1129     {
1130         gtk_widget_set_sensitive(oti->txt_from, toggle == oti->rad_use_text);
1131         gtk_widget_set_sensitive(oti->chk_auto, toggle == oti->rad_use_gps);
1132     }
1133     vprintf("%s(): return TRUE\n", __PRETTY_FUNCTION__);
1134     return TRUE;
1135 }
1136
1137 static gboolean
1138 route_download_swap(GtkWidget *button, RouteDownloadInfo *oti)
1139 {
1140     gchar *old_origin;
1141     printf("%s()\n", __PRETTY_FUNCTION__);
1142
1143     /* Save the old origin. */
1144     old_origin = g_strdup(gtk_entry_get_text(GTK_ENTRY(oti->txt_from)));
1145
1146     /* Set the origin text field equal to the current destination. */
1147     gtk_entry_set_text(GTK_ENTRY(oti->txt_from),
1148             gtk_entry_get_text(GTK_ENTRY(oti->txt_to)));
1149
1150     /* Set the contents of the destination text field. */
1151     if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(oti->rad_use_gps)))
1152     {
1153         /* "Use GPS Location" is enabled - set Destination to GPS Location */
1154         gchar buffer[80];
1155         gchar strlat[32];
1156         gchar strlon[32];
1157         g_ascii_formatd(strlat, 32, "%.06f", _gps.lat);
1158         g_ascii_formatd(strlon, 32, "%.06f", _gps.lon);
1159         snprintf(buffer, sizeof(buffer), "%s, %s", strlat, strlon);
1160         gtk_entry_set_text(GTK_ENTRY(oti->txt_to), buffer);
1161     }
1162     else if(gtk_toggle_button_get_active(
1163                 GTK_TOGGLE_BUTTON(oti->rad_use_route)))
1164     {
1165         /* "Use End of Route" is enabled - set Destination to start of route */
1166         gchar buffer[80];
1167         gchar strlat[32];
1168         gchar strlon[32];
1169         Point *p;
1170         gdouble lat, lon;
1171
1172         /* Use first non-zero route point. */
1173         for(p = _route.head; !p->unity; p++) { }
1174
1175         unit2latlon(p->unitx, p->unity, lat, lon);
1176         g_ascii_formatd(strlat, 32, "%.06f", lat);
1177         g_ascii_formatd(strlon, 32, "%.06f", lon);
1178         snprintf(buffer, sizeof(buffer), "%s, %s", strlat, strlon);
1179         gtk_entry_set_text(GTK_ENTRY(oti->txt_to), buffer);
1180     }
1181     else if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(oti->rad_use_text)))
1182     {
1183         /* "Origin" is enabled - just use the text. */
1184         gtk_entry_set_text(GTK_ENTRY(oti->txt_to), old_origin);
1185     }
1186
1187     g_free(old_origin);
1188     gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(oti->rad_use_text), TRUE);
1189
1190     vprintf("%s(): return TRUE\n", __PRETTY_FUNCTION__);
1191     return TRUE;
1192 }
1193
1194 /**
1195  * Display a dialog box to the user asking them to download a route.  The
1196  * "From" and "To" textfields may be initialized using the first two
1197  * parameters.  The third parameter, if set to TRUE, will cause the "Use GPS
1198  * Location" checkbox to be enabled, which automatically sets the "From" to the
1199  * current GPS position (this overrides any value that may have been passed as
1200  * the "To" initializer).
1201  * None of the passed strings are freed - that is left to the caller, and it is
1202  * safe to free either string as soon as this function returns.
1203  */
1204 gboolean
1205 route_download(gchar *to)
1206 {
1207     static GtkWidget *dialog = NULL;
1208     static GtkWidget *table = NULL;
1209     static GtkWidget *label = NULL;
1210     static GtkWidget *txt_source_url = NULL;
1211     static GtkWidget *btn_swap = NULL;
1212     static RouteDownloadInfo oti;
1213     printf("%s()\n", __PRETTY_FUNCTION__);
1214
1215     conic_recommend_connected();
1216
1217     if(dialog == NULL)
1218     {
1219         GtkEntryCompletion *from_comp;
1220         GtkEntryCompletion *to_comp;
1221         dialog = gtk_dialog_new_with_buttons(_("Download Route"),
1222                 GTK_WINDOW(_window), GTK_DIALOG_MODAL,
1223                 GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,
1224                 GTK_STOCK_CANCEL, GTK_RESPONSE_REJECT,
1225                 NULL);
1226
1227         /* Enable the help button. */
1228 #ifndef LEGACY
1229         hildon_help_dialog_help_enable(
1230 #else
1231         ossohelp_dialog_help_enable(
1232 #endif
1233                 GTK_DIALOG(dialog), HELP_ID_DOWNROUTE, _osso);
1234
1235         gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox),
1236                 table = gtk_table_new(2, 5, FALSE), TRUE, TRUE, 0);
1237
1238         /* Source URL. */
1239         gtk_table_attach(GTK_TABLE(table),
1240                 label = gtk_label_new(_("Source URL")),
1241                 0, 1, 0, 1, GTK_FILL, 0, 2, 4);
1242         gtk_misc_set_alignment(GTK_MISC(label), 1.f, 0.5f);
1243         gtk_table_attach(GTK_TABLE(table),
1244                 txt_source_url = gtk_entry_new(),
1245                 1, 5, 0, 1, GTK_EXPAND | GTK_FILL, 0, 2, 4);
1246         gtk_entry_set_width_chars(GTK_ENTRY(txt_source_url), 25);
1247
1248         /* Use GPS Location. */
1249         gtk_table_attach(GTK_TABLE(table),
1250                 oti.rad_use_gps = gtk_radio_button_new_with_label(NULL,
1251                     _("Use GPS Location")),
1252                 0, 2, 1, 2, GTK_FILL, 0, 2, 4);
1253
1254         /* Use End of Route. */
1255         gtk_table_attach(GTK_TABLE(table),
1256                oti.rad_use_route = gtk_radio_button_new_with_label_from_widget(
1257                    GTK_RADIO_BUTTON(oti.rad_use_gps), _("Use End of Route")),
1258                0, 2, 2, 3, GTK_FILL, 0, 2, 4);
1259
1260         gtk_table_attach(GTK_TABLE(table),
1261                 gtk_vseparator_new(),
1262                 2, 3, 1, 3, GTK_FILL, GTK_FILL, 2,4);
1263
1264         /* Auto. */
1265         gtk_table_attach(GTK_TABLE(table),
1266                 oti.chk_auto = gtk_check_button_new_with_label(
1267                     _("Auto-Update")),
1268                 3, 5, 1, 2, GTK_FILL, 0, 2, 4);
1269
1270         /* Avoid Highways. */
1271         gtk_table_attach(GTK_TABLE(table),
1272                 oti.chk_avoid_highways = gtk_check_button_new_with_label(
1273                     _("Avoid Highways")),
1274                 3, 5, 2, 3, GTK_FILL, 0, 2, 4);
1275
1276
1277         /* Origin. */
1278         gtk_table_attach(GTK_TABLE(table),
1279                 oti.rad_use_text = gtk_radio_button_new_with_label_from_widget(
1280                     GTK_RADIO_BUTTON(oti.rad_use_gps), _("Origin")),
1281                 0, 1, 3, 4, GTK_FILL, 0, 2, 4);
1282         gtk_table_attach(GTK_TABLE(table),
1283                 oti.txt_from = gtk_entry_new(),
1284                 1, 4, 3, 4, GTK_EXPAND | GTK_FILL, 0, 2, 4);
1285         gtk_entry_set_width_chars(GTK_ENTRY(oti.txt_from), 25);
1286 #ifndef LEGACY
1287         g_object_set(G_OBJECT(oti.txt_from), "hildon-input-mode",
1288                                 HILDON_GTK_INPUT_MODE_FULL, NULL);
1289 #else
1290         g_object_set(G_OBJECT(oti.txt_from), HILDON_AUTOCAP, FALSE, NULL);
1291 #endif
1292
1293         /* Destination. */
1294         gtk_table_attach(GTK_TABLE(table),
1295                 label = gtk_label_new(_("Destination")),
1296                 0, 1, 4, 5, GTK_FILL, 0, 2, 4);
1297         gtk_misc_set_alignment(GTK_MISC(label), 1.f, 0.5f);
1298         gtk_table_attach(GTK_TABLE(table),
1299                 oti.txt_to = gtk_entry_new(),
1300                 1, 4, 4, 5, GTK_EXPAND | GTK_FILL, 0, 2, 4);
1301         gtk_entry_set_width_chars(GTK_ENTRY(oti.txt_to), 25);
1302 #ifndef LEGACY
1303         g_object_set(G_OBJECT(oti.txt_to), "hildon-input-mode",
1304                                 HILDON_GTK_INPUT_MODE_FULL, NULL);
1305 #else
1306         g_object_set(G_OBJECT(oti.txt_to), HILDON_AUTOCAP, FALSE, NULL);
1307 #endif
1308
1309         /* Swap button. */
1310         gtk_table_attach(GTK_TABLE(table),
1311                 btn_swap = gtk_button_new_with_label("Swap"),
1312                 4, 5, 3, 5, GTK_FILL, GTK_FILL, 2, 4);
1313
1314         /* Set up auto-completion. */
1315         from_comp = gtk_entry_completion_new();
1316         gtk_entry_completion_set_model(from_comp, GTK_TREE_MODEL(_loc_model));
1317         gtk_entry_completion_set_text_column(from_comp, 0);
1318         gtk_entry_set_completion(GTK_ENTRY(oti.txt_from), from_comp);
1319
1320         to_comp = gtk_entry_completion_new();
1321         gtk_entry_completion_set_model(to_comp, GTK_TREE_MODEL(_loc_model));
1322         gtk_entry_completion_set_text_column(to_comp, 0);
1323         gtk_entry_set_completion(GTK_ENTRY(oti.txt_to), to_comp);
1324
1325
1326         g_signal_connect(G_OBJECT(oti.rad_use_gps), "toggled",
1327                           G_CALLBACK(origin_type_selected), &oti);
1328         g_signal_connect(G_OBJECT(oti.rad_use_route), "toggled",
1329                           G_CALLBACK(origin_type_selected), &oti);
1330         g_signal_connect(G_OBJECT(oti.rad_use_text), "toggled",
1331                           G_CALLBACK(origin_type_selected), &oti);
1332         g_signal_connect(G_OBJECT(btn_swap), "clicked",
1333                           G_CALLBACK(route_download_swap), &oti);
1334
1335         gtk_widget_set_sensitive(oti.chk_auto, FALSE);
1336     }
1337
1338     /* Initialize fields. */
1339
1340     gtk_entry_set_text(GTK_ENTRY(txt_source_url), _route_dl_url);
1341     if(to)
1342         gtk_entry_set_text(GTK_ENTRY(oti.txt_to), to);
1343
1344     /* Use "End of Route" by default if they have a route. */
1345     if(_route.head != _route.tail)
1346     {
1347         /* There is no route, so make it the default. */
1348         gtk_widget_set_sensitive(oti.rad_use_route, TRUE);
1349         gtk_toggle_button_set_active(
1350                 GTK_TOGGLE_BUTTON(oti.rad_use_route), TRUE);
1351         gtk_widget_grab_focus(oti.rad_use_route);
1352     }
1353     /* Else use "GPS Location" if they have GPS enabled. */
1354     else
1355     {
1356         /* There is no route, so desensitize "Use End of Route." */
1357         gtk_widget_set_sensitive(oti.rad_use_route, FALSE);
1358         if(_enable_gps)
1359         {
1360             gtk_toggle_button_set_active(
1361                     GTK_TOGGLE_BUTTON(oti.rad_use_gps), TRUE);
1362             gtk_widget_grab_focus(oti.rad_use_gps);
1363         }
1364         /* Else use text. */
1365         else
1366         {
1367             gtk_toggle_button_set_active(
1368                     GTK_TOGGLE_BUTTON(oti.rad_use_text), TRUE);
1369             gtk_widget_grab_focus(oti.txt_from);
1370         }
1371     }
1372
1373     gtk_widget_show_all(dialog);
1374
1375     while(GTK_RESPONSE_ACCEPT == gtk_dialog_run(GTK_DIALOG(dialog)))
1376     {
1377         gchar buffer[BUFFER_SIZE];
1378         const gchar *source_url, *from, *to;
1379         gboolean avoid_highways;
1380
1381         source_url = gtk_entry_get_text(GTK_ENTRY(txt_source_url));
1382         if(!strlen(source_url))
1383         {
1384             popup_error(dialog, _("Please specify a source URL."));
1385             continue;
1386         }
1387         else
1388         {
1389             g_free(_route_dl_url);
1390             _route_dl_url = g_strdup(source_url);
1391         }
1392
1393         if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(oti.rad_use_gps)))
1394         {
1395             gchar strlat[32];
1396             gchar strlon[32];
1397             g_ascii_formatd(strlat, 32, "%.06f", _gps.lat);
1398             g_ascii_formatd(strlon, 32, "%.06f", _gps.lon);
1399             snprintf(buffer, sizeof(buffer), "%s, %s", strlat, strlon);
1400             from = buffer;
1401         }
1402         else if(gtk_toggle_button_get_active(
1403                     GTK_TOGGLE_BUTTON(oti.rad_use_route)))
1404         {
1405             gchar strlat[32];
1406             gchar strlon[32];
1407             Point *p;
1408             gdouble lat, lon;
1409
1410             /* Use last non-zero route point. */
1411             for(p = _route.tail; !p->unity; p--) { }
1412
1413             unit2latlon(p->unitx, p->unity, lat, lon);
1414             g_ascii_formatd(strlat, 32, "%.06f", lat);
1415             g_ascii_formatd(strlon, 32, "%.06f", lon);
1416             snprintf(buffer, sizeof(buffer), "%s, %s", strlat, strlon);
1417             from = buffer;
1418         }
1419         else
1420         {
1421             from = gtk_entry_get_text(GTK_ENTRY(oti.txt_from));
1422         }
1423
1424         if(!strlen(from))
1425         {
1426             popup_error(dialog, _("Please specify a start location."));
1427             continue;
1428         }
1429
1430         to = gtk_entry_get_text(GTK_ENTRY(oti.txt_to));
1431         if(!strlen(to))
1432         {
1433             popup_error(dialog, _("Please specify an end location."));
1434             continue;
1435         }
1436
1437         avoid_highways = gtk_toggle_button_get_active(
1438                 GTK_TOGGLE_BUTTON(oti.chk_avoid_highways));
1439         if(route_download_and_setup(dialog, source_url, from, to,
1440                 gtk_toggle_button_get_active(
1441                     GTK_TOGGLE_BUTTON(oti.chk_avoid_highways)),
1442                 (gtk_toggle_button_get_active(
1443                     GTK_TOGGLE_BUTTON(oti.rad_use_gps)) ? 0 : 1)))
1444         {
1445             GtkTreeIter iter;
1446
1447             /* Cancel any autoroute that might be occurring. */
1448             cancel_autoroute();
1449
1450             if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(oti.chk_auto)))
1451             {
1452                 _autoroute_data.source_url = g_strdup(source_url);
1453                 _autoroute_data.dest = g_strdup(to);
1454                 _autoroute_data.avoid_highways = avoid_highways;
1455                 _autoroute_data.enabled = TRUE;
1456             }
1457
1458             /* Save Origin in Route Locations list if not from GPS. */
1459             if(gtk_toggle_button_get_active(
1460                         GTK_TOGGLE_BUTTON(oti.rad_use_text))
1461                 && !g_slist_find_custom(_loc_list, from,
1462                             (GCompareFunc)strcmp))
1463             {
1464                 _loc_list = g_slist_prepend(_loc_list, g_strdup(from));
1465                 gtk_list_store_insert_with_values(_loc_model, &iter,
1466                         INT_MAX, 0, from, -1);
1467             }
1468
1469             /* Save Destination in Route Locations list. */
1470             if(!g_slist_find_custom(_loc_list, to,
1471                         (GCompareFunc)strcmp))
1472             {
1473                 _loc_list = g_slist_prepend(_loc_list, g_strdup(to));
1474                 gtk_list_store_insert_with_values(_loc_model, &iter,
1475                         INT_MAX, 0, to, -1);
1476             }
1477
1478             /* Success! Get out of the while loop. */
1479             break;
1480         }
1481         /* else let them try again. */
1482     }
1483
1484     gtk_widget_hide(dialog); /* Destroying causes a crash (!?!?!??!) */
1485
1486     vprintf("%s(): return TRUE\n", __PRETTY_FUNCTION__);
1487     return TRUE;
1488 }
1489
1490 void
1491 route_add_way_dialog(gint unitx, gint unity)
1492 {
1493     gdouble lat, lon;
1494     gchar tmp1[LL_FMT_LEN], tmp2[LL_FMT_LEN], *p_latlon;
1495     static GtkWidget *dialog = NULL;
1496     static GtkWidget *table = NULL;
1497     static GtkWidget *label = NULL;
1498     static GtkWidget *txt_scroll = NULL;
1499     static GtkWidget *txt_desc = NULL;
1500     printf("%s()\n", __PRETTY_FUNCTION__);
1501
1502     if(dialog == NULL)
1503     {
1504         dialog = gtk_dialog_new_with_buttons(_("Add Waypoint"),
1505                 GTK_WINDOW(_window), GTK_DIALOG_MODAL,
1506                 GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,
1507                 GTK_STOCK_CANCEL, GTK_RESPONSE_REJECT,
1508                 NULL);
1509
1510         gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox),
1511                 table = gtk_table_new(2, 2, FALSE), TRUE, TRUE, 0);
1512
1513         gtk_table_attach(GTK_TABLE(table),
1514                 label = gtk_label_new(_("Lat, Lon:")),
1515                 0, 1, 0, 1, GTK_FILL, 0, 2, 4);
1516         gtk_misc_set_alignment(GTK_MISC(label), 1.f, 0.5f);
1517
1518         unit2latlon(unitx, unity, lat, lon);
1519         lat_format(lat, tmp1);
1520         lon_format(lon, tmp2);
1521         p_latlon = g_strdup_printf("%s, %s", tmp1, tmp2);
1522         gtk_table_attach(GTK_TABLE(table),
1523                 label = gtk_label_new(p_latlon),
1524                 1, 2, 0, 1, GTK_FILL, 0, 2, 4);
1525         gtk_misc_set_alignment(GTK_MISC(label), 0.0f, 0.5f);
1526         g_free(p_latlon);
1527
1528         gtk_table_attach(GTK_TABLE(table),
1529                 label = gtk_label_new(_("Description")),
1530                 0, 1, 1, 2, GTK_FILL, 0, 2, 4);
1531         gtk_misc_set_alignment(GTK_MISC(label), 1.f, 0.5f);
1532
1533         txt_scroll = gtk_scrolled_window_new(NULL, NULL);
1534         gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(txt_scroll),
1535                                        GTK_SHADOW_IN);
1536         gtk_table_attach(GTK_TABLE(table),
1537                 txt_scroll,
1538                 1, 2, 1, 2, GTK_EXPAND | GTK_FILL, 0, 2, 4);
1539
1540         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(txt_scroll),
1541                 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
1542
1543         txt_desc = gtk_text_view_new ();
1544         gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(txt_desc), GTK_WRAP_WORD);
1545
1546         gtk_container_add(GTK_CONTAINER(txt_scroll), txt_desc);
1547         gtk_widget_set_size_request(GTK_WIDGET(txt_scroll), 400, 60);
1548     }
1549
1550     gtk_text_buffer_set_text(
1551             gtk_text_view_get_buffer(GTK_TEXT_VIEW(txt_desc)), "", 0);
1552
1553     gtk_widget_show_all(dialog);
1554
1555     while(GTK_RESPONSE_ACCEPT == gtk_dialog_run(GTK_DIALOG(dialog)))
1556     {
1557         GtkTextBuffer *tbuf;
1558         GtkTextIter ti1, ti2;
1559         gchar *desc;
1560
1561         tbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(txt_desc));
1562         gtk_text_buffer_get_iter_at_offset(tbuf, &ti1, 0);
1563         gtk_text_buffer_get_end_iter(tbuf, &ti2);
1564         desc = gtk_text_buffer_get_text(tbuf, &ti1, &ti2, TRUE);
1565
1566         if(*desc)
1567         {
1568             /* There's a description.  Add a waypoint. */
1569             MACRO_PATH_INCREMENT_TAIL(_route);
1570             _route.tail->unitx = unitx;
1571             _route.tail->unity = unity;
1572             _route.tail->time = 0;
1573             _route.tail->altitude = 0;
1574
1575             MACRO_PATH_INCREMENT_WTAIL(_route);
1576             _route.wtail->point = _route.tail;
1577             _route.wtail->desc
1578                 = gtk_text_buffer_get_text(tbuf, &ti1, &ti2, TRUE);
1579         }
1580         else
1581         {
1582             GtkWidget *confirm;
1583
1584             g_free(desc);
1585
1586             confirm = hildon_note_new_confirmation(GTK_WINDOW(dialog),
1587                     _("Creating a \"waypoint\" with no description actually "
1588                         "adds a break point.  Is that what you want?"));
1589
1590             if(GTK_RESPONSE_OK == gtk_dialog_run(GTK_DIALOG(confirm)))
1591             {
1592                 /* There's no description.  Add a break by adding a (0, 0)
1593                  * point (if necessary), and then the ordinary route point. */
1594                 if(_route.tail->unity)
1595                 {
1596                     MACRO_PATH_INCREMENT_TAIL(_route);
1597                     *_route.tail = _point_null;
1598                 }
1599
1600                 MACRO_PATH_INCREMENT_TAIL(_route);
1601                 _route.tail->unitx = unitx;
1602                 _route.tail->unity = unity;
1603                 _route.tail->time = 0;
1604                 _route.tail->altitude = 0;
1605
1606
1607                 gtk_widget_destroy(confirm);
1608             }
1609             else
1610             {
1611                 gtk_widget_destroy(confirm);
1612                 continue;
1613             }
1614         }
1615
1616         route_find_nearest_point();
1617         map_render_paths();
1618         MACRO_QUEUE_DRAW_AREA();
1619         break;
1620     }
1621     gtk_widget_hide(dialog);
1622     vprintf("%s(): return\n", __PRETTY_FUNCTION__);
1623 }
1624
1625 WayPoint*
1626 path_get_next_way()
1627 {
1628     return _next_way;
1629 }
1630
1631 void
1632 path_init()
1633 {
1634     gchar *settings_dir;
1635     printf("%s()\n", __PRETTY_FUNCTION__);
1636
1637     /* Initialize settings_dir. */
1638     settings_dir = gnome_vfs_expand_initial_tilde(CONFIG_DIR_NAME);
1639     g_mkdir_with_parents(settings_dir, 0700);
1640
1641     /* Open path database. */
1642     {   
1643         gchar *path_db_file;
1644
1645         path_db_file = gnome_vfs_uri_make_full_from_relative(
1646                 settings_dir, CONFIG_PATH_DB_FILE);
1647
1648         if(!path_db_file || SQLITE_OK != sqlite3_open(path_db_file, &_path_db)
1649         /* Open worked. Now create tables, failing if they already exist. */
1650         || (sqlite3_exec(_path_db,
1651                     "create table route_path ("
1652                     "num integer primary key, "
1653                     "unitx integer, "
1654                     "unity integer, "
1655                     "time integer, "
1656                     "altitude integer)"
1657                     ";"
1658                     "create table route_way ("
1659                     "route_point primary key, "
1660                     "description text)"
1661                     ";"
1662                     "create table track_path ("
1663                     "num integer primary key, "
1664                     "unitx integer, "
1665                     "unity integer, "
1666                     "time integer, "
1667                     "altitude integer)"
1668                     ";"
1669                     "create table track_way ("
1670                     "track_point primary key, "
1671                     "description text)",
1672                     NULL, NULL, NULL), FALSE) /* !! Comma operator !! */
1673             /* Create prepared statements - failure here is bad! */
1674             || SQLITE_OK != sqlite3_prepare(_path_db,
1675                     "select unitx, unity, time, altitude, description "
1676                     "from route_path left join route_way on "
1677                     "route_path.num = route_way.route_point "
1678                     "order by route_path.num",
1679                     -1, &_route_stmt_select, NULL)
1680             || SQLITE_OK != sqlite3_prepare(_path_db,
1681                     "select unitx, unity, time, altitude, description "
1682                     "from track_path left join track_way on "
1683                     "track_path.num = track_way.track_point "
1684                     "order by track_path.num",
1685                     -1, &_track_stmt_select, NULL)
1686             || SQLITE_OK != sqlite3_prepare(_path_db,
1687                     "delete from route_path",
1688                     -1, &_route_stmt_delete_path, NULL)
1689             || SQLITE_OK != sqlite3_prepare(_path_db,
1690                     "delete from route_way",
1691                     -1, &_route_stmt_delete_way, NULL)
1692             || SQLITE_OK != sqlite3_prepare(_path_db,
1693                     "insert into route_path "
1694                     "(num, unitx, unity, time, altitude) "
1695                     "values (NULL, ?, ?, ?, ?)",
1696                     -1, &_route_stmt_insert_path, NULL)
1697             || SQLITE_OK != sqlite3_prepare(_path_db,
1698                     "insert into route_way (route_point, description) "
1699                     "values (?, ?)",
1700                     -1, &_route_stmt_insert_way, NULL)
1701             || SQLITE_OK != sqlite3_prepare(_path_db,
1702                     "delete from track_path",
1703                     -1, &_track_stmt_delete_path, NULL)
1704             || SQLITE_OK != sqlite3_prepare(_path_db,
1705                     "delete from track_way",
1706                     -1, &_track_stmt_delete_way, NULL)
1707             || SQLITE_OK != sqlite3_prepare(_path_db,
1708                     "insert into track_path "
1709                     "(num, unitx, unity, time, altitude) "
1710                     "values (NULL, ?, ?, ?, ?)",
1711                     -1, &_track_stmt_insert_path, NULL)
1712             || SQLITE_OK != sqlite3_prepare(_path_db,
1713                     "insert into track_way (track_point, description) "
1714                     "values (?, ?)",
1715                     -1, &_track_stmt_insert_way, NULL)
1716             || SQLITE_OK != sqlite3_prepare(_path_db, "begin transaction",
1717                     -1, &_path_stmt_trans_begin, NULL)
1718             || SQLITE_OK != sqlite3_prepare(_path_db, "commit transaction",
1719                     -1, &_path_stmt_trans_commit, NULL)
1720             || SQLITE_OK != sqlite3_prepare(_path_db, "rollback transaction",
1721                     -1, &_path_stmt_trans_rollback, NULL))
1722         {   
1723             gchar buffer[BUFFER_SIZE];
1724             snprintf(buffer, sizeof(buffer), "%s\n%s",
1725                     _("Failed to open path database. "
1726                         "Tracks and routes will not be saved."),
1727                     sqlite3_errmsg(_path_db));
1728             sqlite3_close(_path_db);
1729             _path_db = NULL;
1730             popup_error(_window, buffer);
1731         }
1732         else
1733         {   
1734             read_path_from_db(&_route, _route_stmt_select);
1735             read_path_from_db(&_track, _track_stmt_select);
1736             _track_index_last_saved = _track.tail - _track.head - 1;
1737         }
1738         g_free(path_db_file);
1739     }
1740
1741     g_free(settings_dir);
1742
1743     _last_spoken_phrase = g_strdup("");
1744
1745     vprintf("%s(): return\n", __PRETTY_FUNCTION__);
1746 }
1747
1748 void
1749 path_destroy()
1750 {
1751     printf("%s()\n", __PRETTY_FUNCTION__);
1752
1753     /* Save paths. */
1754     if(_track.tail->unity)
1755         track_insert_break(FALSE);
1756     path_update_track_in_db();
1757     path_save_route_to_db();
1758
1759     if(_path_db)
1760     {   
1761         sqlite3_close(_path_db);
1762         _path_db = NULL;
1763     }
1764
1765     MACRO_PATH_FREE(_track);
1766     MACRO_PATH_FREE(_route);
1767
1768     vprintf("%s(): return\n", __PRETTY_FUNCTION__);
1769 }