]> err.no Git - mapper/blob - src/map.c
Merge branch 'master' of ssh://git.tal.org/home/git/mapper
[mapper] / src / map.c
1 /*
2  * This file is part of mapper
3  *
4  * Copyright (C) 2007 Kaj-Michael Lang
5  * Copyright (C) 2006-2007 John Costigan.
6  *
7  * POI and GPS-Info code originally written by Cezary Jackiewicz.
8  *
9  * Default map data provided by http://www.openstreetmap.org/
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License along
22  * with this program; if not, write to the Free Software Foundation, Inc.,
23  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24  */
25
26 #include <config.h>
27
28 #include <unistd.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <strings.h>
32 #include <stddef.h>
33 #include <math.h>
34 #include <errno.h>
35 #include <sys/wait.h>
36 #include <glib/gstdio.h>
37 #include <gtk/gtk.h>
38 #include <fcntl.h>
39 #include <libintl.h>
40 #include <locale.h>
41
42 #include "hildon-mapper.h"
43
44 #include "utils.h"
45 #include "map.h"
46 #include "osm.h"
47 #include "db.h"
48 #include "osm-db.h"
49 #include "poi.h"
50 #include "route.h"
51 #include "track.h"
52 #include "gps.h"
53 #include "mapper-types.h"
54 #include "ui-common.h"
55 #include "settings.h"
56 #include "latlon.h"
57 #include "gpx.h"
58 #include "speak.h"
59 #include "map-poi.h"
60 #include "map-download.h"
61 #include "announcements.h"
62 #include "gtkcompass.h"
63 #include "dialogs.h"
64
65 #define DEBUG_MAP_TIME 1
66
67 /* Initial size */
68 #define BUF_WIDTH_TILES (4)
69 #define BUF_HEIGHT_TILES (3)
70 #define BUF_WIDTH_PIXELS (1024)
71 #define BUF_HEIGHT_PIXELS (768)
72
73 static guint buf_width_tiles=BUF_WIDTH_TILES;
74 static guint buf_height_tiles=BUF_HEIGHT_TILES;
75 static guint buf_width_pixels=BUF_WIDTH_PIXELS;
76 static guint buf_height_pixels=BUF_HEIGHT_PIXELS;
77
78 #ifdef WITH_GL
79 #include <GL/gl.h>
80 #include <gtk/gtkgl.h>
81 GdkGLConfig* map_gl_config=NULL;
82 #endif
83 gboolean map_gl=FALSE;
84
85 #ifdef WITH_CAIRO
86 cairo_t *ct_pixmap;
87 #endif
88
89 /** The backing pixmap of map_widget. */
90 static GdkPixmap *map_pixmap;
91
92 /** The "base tile" is the upper-left tile in the pixmap. */
93 guint _base_tilex = -5;
94 guint _base_tiley = -5;
95
96 static guint map_max_zoom=MAX_ZOOM;
97 guint _zoom = 3;                /* zoom level, from 0 to MAX_ZOOM. */
98
99 Point _min_center = { -1, -1 };
100 Point _max_center = { -1, -1 };
101 Point _focus = { -1, -1 };
102 /* current center location, X. */
103 Point _center = { -1, -1 };     
104
105 CenterMode _center_mode = CENTER_LEAD;
106
107 /* Drag */
108 static guint press[2] = { 0, 0 };
109 static guint release[2] = { 0, 0 };
110 static guint before[2] = { 0, 0 };
111 static guint map_drag_id = 0;
112 static gboolean map_dragged;
113
114 /** VARIABLES FOR ACCESSING THE LOCATION/BOUNDS OF THE CURRENT MARK. */
115 static gint mark_x1;
116 static gint mark_x2;
117 static gint mark_y1;
118 static gint mark_y2;
119 static gint mark_minx;
120 static gint mark_miny;
121 static gint mark_width;
122 static gint mark_height;
123
124 static GdkRectangle scale_rect;
125 static PangoContext *scale_context;
126 static PangoFontDescription *scale_font;
127 static PangoLayout *scale_layout;
128
129 static GdkGC *speed_gc1;
130 static GdkGC *speed_gc2;
131 static PangoContext *speed_context;
132 static PangoLayout *speed_layout;
133 static PangoFontDescription *speed_fontdesc;
134
135 static gint zoom_timeout_sid=0;
136 static gint map_mode=0;
137 static gboolean map_data_needs_refresh=FALSE;
138
139 osm_location map_loc = {NULL, NULL, NULL, FALSE, FALSE, 0, 0, 0.0, 0.0, 0 };
140
141 static GTimer *map_timer;
142
143 /* Tile max age, 1 week */
144 #define TILE_MAX_AGE (604800)
145
146 #define KM10KNOTS (5.39956803)
147
148 static void map_update_location(gdouble lat, gdouble lon, gboolean force);
149 static void map_speed_draw(void);
150 static gboolean map_cb_after_realize(GtkWidget *map_widget, gpointer data);
151 static gboolean map_cb_configure(GtkWidget *widget, GdkEventConfigure *event);
152 static gboolean map_cb_expose(GtkWidget * widget, GdkEventExpose * event);
153 static gboolean map_cb_button_press(GtkWidget * widget, GdkEventButton * event);
154 static gboolean map_cb_button_release(GtkWidget * widget, GdkEventButton * event);
155 static gboolean map_cb_scroll_event(GtkWidget * widget, GdkEventScroll * event); 
156
157 /******************************************************************************/
158
159 GtkWidget * 
160 map_new(void) 
161 {
162 GtkWidget *map_widget;
163
164 map_widget=gtk_drawing_area_new();
165 map_timer=g_timer_new();
166
167 g_debug("World size: %u", WORLD_SIZE_UNITS);
168
169 #ifdef WITH_GL
170 map_gl_config=gdk_gl_config_new_by_mode(GDK_GL_MODE_RGB | GDK_GL_MODE_DEPTH);
171 if (map_gl_config) {
172     g_print("OpenGL version: %s\n", glGetString (GL_VERSION));
173     g_print("OpenGL vendor: %s\n", glGetString (GL_VENDOR));
174     g_print("OpenGL renderer: %s\n", glGetString (GL_RENDERER));
175         gtk_widget_set_gl_capability(map_widget, map_gl_config, NULL, TRUE, GDK_GL_RGBA_TYPE);
176         map_gl=TRUE;
177 }
178 #endif
179
180 g_signal_connect_after(G_OBJECT(map_widget), "realize", G_CALLBACK(map_cb_after_realize), NULL);
181 g_signal_connect(G_OBJECT(map_widget), "configure_event", G_CALLBACK(map_cb_configure), NULL);
182
183 return map_widget;
184 }
185
186 static gboolean 
187 map_cb_after_realize(GtkWidget *map_widget, gpointer data)
188 {
189 GdkColor color;
190
191 g_debug("MAP: after_realize");
192
193 scale_context=gtk_widget_get_pango_context(map_widget);
194 scale_layout=pango_layout_new(scale_context);
195 scale_font=pango_font_description_new();
196 pango_font_description_set_size(scale_font, 12 * PANGO_SCALE);
197 pango_layout_set_font_description(scale_layout, scale_font);
198
199 /* Speed limit, over limit color */
200 speed_gc1=gdk_gc_new(map_widget->window);
201 color.red=0xffff;
202 color.green=0;
203 color.blue=0;
204 gdk_gc_set_rgb_fg_color(speed_gc1, &color);
205
206 /* Speed limit, under limit color */
207 speed_gc2=gdk_gc_new(map_widget->window);
208 color.red=0;
209 color.green=0x1000;
210 color.blue=0;
211 gdk_gc_set_rgb_fg_color(speed_gc2, &color);
212
213 speed_context=gtk_widget_get_pango_context(map_widget);
214 speed_layout=pango_layout_new(speed_context);
215 speed_fontdesc=pango_font_description_new();
216 pango_font_description_set_size(speed_fontdesc, 48 * PANGO_SCALE);
217 pango_layout_set_font_description(speed_layout, speed_fontdesc);
218 pango_layout_set_alignment(speed_layout, PANGO_ALIGN_CENTER);
219
220 /* Signals */
221 g_signal_connect(G_OBJECT(map_widget), "expose_event", G_CALLBACK(map_cb_expose), NULL);
222 g_signal_connect(G_OBJECT(map_widget), "button_press_event", G_CALLBACK(map_cb_button_press), NULL);
223 g_signal_connect(G_OBJECT(map_widget), "button_release_event",G_CALLBACK(map_cb_button_release), NULL);
224 g_signal_connect(G_OBJECT(map_widget), "scroll_event",  G_CALLBACK(map_cb_scroll_event), NULL);
225
226 gtk_widget_add_events(map_widget, GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK
227       | GDK_LEAVE_NOTIFY_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK);
228
229 map_poi_init(map_widget);
230
231 return TRUE;
232 }
233
234 static gboolean 
235 map_cb_configure(GtkWidget *widget, GdkEventConfigure *event)
236 {
237 guint tw, th;
238
239 tw=TILE_SIZE_PIXELS*((widget->allocation.width/TILE_SIZE_PIXELS)+2);
240 th=TILE_SIZE_PIXELS*((widget->allocation.height/TILE_SIZE_PIXELS)+2);
241
242 if (map_pixmap==NULL) {
243         map_pixmap=gdk_pixmap_new(widget->window, tw, th, -1);
244 } else {
245         if (tw>buf_width_pixels || th>buf_height_pixels) {
246                 g_object_unref(map_pixmap);
247                 map_pixmap=gdk_pixmap_new(widget->window, tw, th, -1);
248         } else if (tw<buf_width_pixels-(TILE_SIZE_PIXELS*2) || th<buf_height_pixels-(TILE_SIZE_PIXELS*2)) {
249                 g_object_unref(map_pixmap);
250                 map_pixmap=gdk_pixmap_new(widget->window, tw, th, -1);
251         }
252 }
253 g_assert(map_pixmap);
254
255 buf_width_pixels=tw;
256 buf_height_pixels=th;
257 buf_width_tiles=buf_width_pixels/TILE_SIZE_PIXELS;
258 buf_height_tiles=buf_height_pixels/TILE_SIZE_PIXELS;
259
260 _screen_width_pixels = widget->allocation.width;
261 _screen_height_pixels = widget->allocation.height;
262 _screen_grids_halfwidth = pixel2grid(_screen_width_pixels) / 2;
263 _screen_grids_halfheight = pixel2grid(_screen_height_pixels) / 2;
264
265 /* Set scale_rect. */
266 scale_rect.x = (_screen_width_pixels - SCALE_WIDTH) / 2;
267 scale_rect.width = SCALE_WIDTH;
268
269 MACRO_RECALC_FOCUS_BASE(_center_ratio);
270 MACRO_RECALC_FOCUS_SIZE(_center_ratio);
271
272 _min_center.unitx = pixel2unit(grid2pixel(_screen_grids_halfwidth));
273 _min_center.unity = pixel2unit(grid2pixel(_screen_grids_halfheight));
274 _max_center.unitx = WORLD_SIZE_UNITS - grid2unit(_screen_grids_halfwidth) - 1;
275 _max_center.unity = WORLD_SIZE_UNITS - grid2unit(_screen_grids_halfheight) - 1;
276
277 map_force_redraw();
278 return TRUE;
279 }
280
281 /**
282  * Draw the current mark (representing the current GPS location) onto
283  * _map_widget.  This method does not queue the draw area.
284  */
285 static void 
286 map_draw_mark(Gps *gps)
287 {
288 gdk_draw_arc(_map_widget->window, gps->io.conn == RCVR_FIXED ? _gc[COLORABLE_MARK] : _gc[COLORABLE_MARK_OLD], FALSE,
289      mark_x1 - _draw_width, mark_y1 - _draw_width, 2 * _draw_width, 2 * _draw_width, 0, 360 * 64);
290 gdk_draw_line(_map_widget->window, gps->io.conn == RCVR_FIXED ? (_show_velvec ? _gc[COLORABLE_MARK_VELOCITY] : _gc[COLORABLE_MARK]) : _gc[COLORABLE_MARK_OLD],
291       mark_x1, mark_y1, mark_x2, mark_y2);
292 }
293
294 /**
295  * "Set" the mark, which translates the current GPS position into on-screen
296  * units in preparation for drawing the mark with map_draw_mark().
297  */
298 void 
299 map_set_mark(GpsData *gps)
300 {
301 mark_x1 = unit2x(gps->unitx);
302 mark_y1 = unit2y(gps->unity);
303 mark_x2 = mark_x1 + (_show_velvec ? gps->vel_offsetx : 0);
304 mark_y2 = mark_y1 + (_show_velvec ? gps->vel_offsety : 0);
305 mark_minx = MIN(mark_x1, mark_x2) - (2 * _draw_width);
306 mark_miny = MIN(mark_y1, mark_y2) - (2 * _draw_width);
307 mark_width = abs(mark_x1 - mark_x2) + (4 * _draw_width);
308 mark_height = abs(mark_y1 - mark_y2) + (4 * _draw_width);
309 }
310
311 /**
312  * Do an in-place scaling of a pixbuf's pixels at the given ratio from the
313  * given source location.  It would have been nice if gdk_pixbuf provided
314  * this method, but I guess it's not general-purpose enough.
315  */
316 static void
317 map_pixbuf_scale_inplace(GdkPixbuf * pixbuf, guint ratio_p2, guint src_x, guint src_y)
318 {
319 guint dest_x = 0, dest_y = 0, dest_dim = TILE_SIZE_PIXELS;
320 guint rowstride = gdk_pixbuf_get_rowstride(pixbuf);
321 guint n_channels = gdk_pixbuf_get_n_channels(pixbuf);
322 guchar *pixels = gdk_pixbuf_get_pixels(pixbuf);
323
324 /* Sweep through the entire dest area, copying as necessary, but
325  * DO NOT OVERWRITE THE SOURCE AREA.  We'll copy it afterward. */
326 do {
327         guint src_dim = dest_dim >> ratio_p2;
328         guint src_endx = src_x - dest_x + src_dim;
329         gint x, y;
330
331         for (y = dest_dim - 1; y >= 0; y--) {
332                 guint src_offset_y, dest_offset_y;
333
334                 src_offset_y = (src_y + (y >> ratio_p2)) * rowstride;
335                 dest_offset_y = (dest_y + y) * rowstride;
336                 x = dest_dim - 1;
337
338                 if ((unsigned)(dest_y + y - src_y) < src_dim && (unsigned)(dest_x + x - src_x) < src_dim)
339                         x -= src_dim;
340
341                 for (; x >= 0; x--) {
342                         guint src_offset, dest_offset, i;
343
344                         src_offset = src_offset_y + (src_x + (x >> ratio_p2)) * n_channels;
345                         dest_offset = dest_offset_y + (dest_x + x) * n_channels;
346
347                         pixels[dest_offset] = pixels[src_offset];
348                         for (i = n_channels - 1; i; i--)
349                                 pixels[dest_offset + i] = pixels[src_offset + i];
350
351                         if ((unsigned)(dest_y + y - src_y) < src_dim && x == src_endx)
352                                 x -= src_dim;
353                 }
354         }
355
356         /* Reuse src_dim and src_endx to store new src_x and src_y. */
357         src_dim = src_x + ((src_x - dest_x) >> ratio_p2);
358         src_endx = src_y + ((src_y - dest_y) >> ratio_p2);
359         dest_x = src_x;
360         dest_y = src_y;
361         src_x = src_dim;
362         src_y = src_endx;
363 }
364 while ((dest_dim >>= ratio_p2) > 1);
365 }
366
367 /**
368  * Trim pixbufs that are bigger than tiles. (Those pixbufs result, when
369  * captions should be cut off.)
370  */
371 static GdkPixbuf *
372 pixbuf_trim(GdkPixbuf * pixbuf)
373 {
374 GdkPixbuf *mpixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, gdk_pixbuf_get_has_alpha(pixbuf),
375                    8, TILE_SIZE_PIXELS, TILE_SIZE_PIXELS);
376
377 gdk_pixbuf_copy_area(pixbuf,
378                      (gdk_pixbuf_get_width(pixbuf) - TILE_SIZE_PIXELS) / 2,
379                      (gdk_pixbuf_get_height(pixbuf) - TILE_SIZE_PIXELS) / 2, 
380                      TILE_SIZE_PIXELS,
381                      TILE_SIZE_PIXELS, mpixbuf, 0, 0);
382
383 g_object_unref(pixbuf);
384 return mpixbuf;
385 }
386
387 GdkPixmap *
388 map_pixmap_get(void)
389 {
390 return map_pixmap;
391 }
392
393
394 static GdkPixbuf *
395 map_tile_load(guint tilex, guint tiley, gint zoff, gboolean download)
396 {
397 GdkPixbuf *pixbuf;
398 GError *error = NULL;
399 gchar buffer[BUFFER_SIZE];
400 struct stat tstat;
401 gint se;
402
403 g_snprintf(buffer, sizeof(buffer), "%s/%u/%u/%u.jpg", _curr_repo->cache_dir, _zoom + zoff, (tilex >> zoff), (tiley >> zoff));
404
405 pixbuf=gdk_pixbuf_new_from_file(buffer, &error);
406 if (error || !pixbuf) {
407         g_unlink(buffer);
408
409         if (_auto_download && _curr_repo->type != REPOTYPE_NONE && !((_zoom + zoff - (_curr_repo->double_size ? 1 : 0)) % _curr_repo->dl_zoom_steps)) {
410                 if (download)
411                         map_initiate_download(tilex >> zoff, tiley >> zoff, _zoom + zoff, -INITIAL_DOWNLOAD_RETRIES);
412         }
413
414         return NULL;
415 }
416
417 /* Check tile age, if file date is ower a week old, redownload if autodownload enabled */
418 se=stat(buffer, &tstat);
419 if (se==0) {
420         time_t t;
421         t=time(NULL);
422         if (t-tstat.st_mtime>TILE_MAX_AGE) {
423                 if (_auto_download && _curr_repo->type != REPOTYPE_NONE && !((_zoom + zoff - (_curr_repo->double_size ? 1 : 0)) % _curr_repo->dl_zoom_steps)) {
424                         if (download) {
425                                 g_debug("Tile: %s is old, re-downloading\n", buffer);
426                                 map_initiate_download(tilex >> zoff, tiley >> zoff, _zoom + zoff, -INITIAL_DOWNLOAD_RETRIES);
427                         }
428                 }
429         }
430 }
431
432 return pixbuf;
433 }
434
435 gboolean
436 map_render_tile(guint tilex, guint tiley, guint destx, guint desty, gboolean fast_fail)
437 {
438 GdkPixbuf *pixbuf=NULL;
439 gint zoff;
440
441 if (destx > buf_width_pixels || desty > buf_height_pixels)
442         return FALSE;
443
444 if (tilex > _world_size_tiles || tiley > _world_size_tiles)
445         return FALSE;
446
447 g_debug("MAP RT: %u %u (%u) %u %u (%u, %u)", tilex, tiley, _world_size_tiles, destx, desty, buf_width_tiles, buf_height_tiles);
448
449 /* The tile is possible. */
450 for (zoff = (_curr_repo->double_size ? 1 : 0); !pixbuf && (_zoom + zoff) <= map_max_zoom && zoff <= TILE_SIZE_P2; zoff += 1) {
451         pixbuf=map_tile_load(tilex, tiley, zoff, !fast_fail);
452         if (!pixbuf) {
453                 if (!fast_fail)
454                         fast_fail=TRUE;
455         } else {
456                 /* Check if we need to trim. */
457                 if (gdk_pixbuf_get_width(pixbuf) != TILE_SIZE_PIXELS || gdk_pixbuf_get_height(pixbuf) != TILE_SIZE_PIXELS)
458                         pixbuf = pixbuf_trim(pixbuf);
459
460                 /* Check if we need to blit. */
461                 if (zoff) {
462                         map_pixbuf_scale_inplace(pixbuf, zoff,
463                                          (tilex - ((tilex >> zoff) << zoff)) << (TILE_SIZE_P2 - zoff),
464                                          (tiley - ((tiley >> zoff) << zoff)) << (TILE_SIZE_P2 - zoff));
465                 }
466         }
467 }
468
469 if (pixbuf) {
470         gdk_draw_pixbuf(map_pixmap, _gc[COLORABLE_MARK], pixbuf, 0, 0, destx, desty, TILE_SIZE_PIXELS, TILE_SIZE_PIXELS, GDK_RGB_DITHER_NONE, 0, 0);
471         g_object_unref(pixbuf);
472         return TRUE;
473 }
474 gdk_draw_rectangle(map_pixmap, _map_widget->style->black_gc, TRUE, destx, desty, TILE_SIZE_PIXELS, TILE_SIZE_PIXELS);
475 return TRUE;
476 }
477
478 void
479 map_render_data(void)
480 {
481 /* Don't update if dragging, too much lag */
482 if (map_drag_id>0)
483         return;
484
485 if (_home.valid)
486         map_draw_position_icon(&_home);
487
488 if(_show_poi)
489         map_render_all_pois(buf_width_pixels, buf_height_pixels);
490
491 if(_show_tracks>0)
492         map_render_paths();
493 }
494
495 /**
496  * Force a redraw of the entire map_pixmap, including fetching the
497  * background maps from disk and redrawing the tracks on top of them.
498  */
499 void 
500 map_force_redraw(void)
501 {
502 guint new_x, new_y;
503 #ifdef DEBUG
504 gulong tms;
505
506 g_timer_start(map_timer);
507 #endif
508 for (new_y = 0; new_y < buf_height_tiles; ++new_y)
509         for (new_x = 0; new_x < buf_width_tiles; ++new_x) {
510                 map_render_tile(_base_tilex + new_x, _base_tiley + new_y,
511                                 new_x * TILE_SIZE_PIXELS, new_y * TILE_SIZE_PIXELS, FALSE);
512         }
513 #ifdef DEBUG
514 g_timer_stop(map_timer);
515 g_debug("Full redraw: %f sec\n", g_timer_elapsed(map_timer, &tms));
516 #endif
517
518 map_render_data();
519 MACRO_QUEUE_DRAW_AREA();
520 }
521
522 guint
523 map_get_zoom(void)
524 {
525 return _zoom;
526 }
527
528 /**
529  * Set the current zoom level.  If the given zoom level is the same as the
530  * current zoom level, or if the new zoom is invalid
531  * (not MIN_ZOOM <= new_zoom < MAX_ZOOM), then this method does nothing.
532  */
533 gboolean 
534 map_set_zoom(guint new_zoom)
535 {
536 /* Note that, since new_zoom is a guint and MIN_ZOOM is 0, this if
537  * condition also checks for new_zoom >= MIN_ZOOM. */
538 if (new_zoom > (map_max_zoom - 1))
539         return FALSE;
540 if (new_zoom == _zoom)
541         return FALSE;
542
543 _zoom = new_zoom / _curr_repo->view_zoom_steps * _curr_repo->view_zoom_steps;
544 _world_size_tiles = unit2tile(WORLD_SIZE_UNITS);
545
546 /* If we're leading, update the center to reflect new zoom level. */
547 MACRO_RECALC_CENTER(_gps->data, _center.unitx, _center.unity);
548
549 /* Update center bounds to reflect new zoom level. */
550 _min_center.unitx = pixel2unit(grid2pixel(_screen_grids_halfwidth));
551 _min_center.unity = pixel2unit(grid2pixel(_screen_grids_halfheight));
552 _max_center.unitx = WORLD_SIZE_UNITS - grid2unit(_screen_grids_halfwidth) - 1;
553 _max_center.unity = WORLD_SIZE_UNITS - grid2unit(_screen_grids_halfheight) - 1;
554
555 BOUND(_center.unitx, _min_center.unitx, _max_center.unitx);
556 BOUND(_center.unity, _min_center.unity, _max_center.unity);
557
558 _base_tilex = grid2tile((gint) pixel2grid((gint) unit2pixel((gint) _center.unitx)) - (gint) _screen_grids_halfwidth);
559 _base_tiley = grid2tile(pixel2grid(unit2pixel(_center.unity)) - _screen_grids_halfheight);
560
561 /* New zoom level, so we can't reuse the old buffer's pixels. */
562 /* Update state variables. */
563 MACRO_RECALC_OFFSET();
564 MACRO_RECALC_FOCUS_BASE(_center_ratio);
565 MACRO_RECALC_FOCUS_SIZE(_center_ratio);
566
567 map_set_mark(&_gps->data);
568 map_force_redraw();
569 return TRUE;
570 }
571
572 /**
573  * Center the view on the given unitx/unity.
574  */
575 void 
576 map_center_unit(guint new_center_unitx, guint new_center_unity)
577 {
578 gint new_base_tilex, new_base_tiley;
579 guint new_x, new_y;
580 guint j, k, base_new_x, base_old_x, old_x, old_y, iox, ioy;
581
582 /* Assure that _center.unitx/y are bounded. */
583 BOUND(new_center_unitx, _min_center.unitx, _max_center.unitx);
584 BOUND(new_center_unity, _min_center.unity, _max_center.unity);
585
586 _center.unitx = new_center_unitx;
587 _center.unity = new_center_unity;
588
589 new_base_tilex = grid2tile((gint) pixel2grid((gint)unit2pixel((gint) _center.unitx)) - (gint)_screen_grids_halfwidth);
590 new_base_tiley = grid2tile(pixel2grid(unit2pixel(_center.unity)) - _screen_grids_halfheight);
591
592 /* Same zoom level, so it's likely that we can reuse some of the old
593  * buffer's pixels. */
594
595 if (new_base_tilex != _base_tilex || new_base_tiley != _base_tiley) {
596         /* If copying from old parts to new parts, we need to make sure we
597          * don't overwrite the old parts when copying, so set up new_x,
598          * new_y, old_x, old_y, iox, and ioy with that in mind. */
599         if (new_base_tiley < _base_tiley) {
600                 /* New is lower than old - start at bottom and go up. */
601                 new_y = buf_height_tiles - 1;
602                 ioy = -1;
603         } else {
604                 /* New is higher than old - start at top and go down. */
605                 new_y = 0;
606                 ioy = 1;
607         }
608         if (new_base_tilex < _base_tilex) {
609                 /* New is righter than old - start at right and go left. */
610                 base_new_x = buf_width_tiles - 1;
611                 iox = -1;
612         } else {
613                 /* New is lefter than old - start at left and go right. */
614                 base_new_x = 0;
615                 iox = 1;
616         }
617
618         /* Iterate over the y tile values. */
619         old_y = new_y + new_base_tiley - _base_tiley;
620         base_old_x = base_new_x + new_base_tilex - _base_tilex;
621         _base_tilex = new_base_tilex;
622         _base_tiley = new_base_tiley;
623
624         for (j = 0; j < buf_height_tiles; ++j, new_y += ioy, old_y += ioy) {
625                 new_x = base_new_x;
626                 old_x = base_old_x;
627                 /* Iterate over the x tile values. */
628                 for (k = 0; k < buf_width_tiles; ++k, new_x += iox, old_x += iox) {
629                         /* Can we get this grid block from the old buffer?. */
630                         if (old_x >= 0 && old_x < buf_width_tiles && old_y >= 0 && old_y < buf_height_tiles) {
631                                 /* Copy from old buffer to new buffer. */
632                                 gdk_draw_drawable(map_pixmap,
633                                                   _gc[COLORABLE_MARK],
634                                                   map_pixmap,
635                                                   old_x * TILE_SIZE_PIXELS,
636                                                   old_y * TILE_SIZE_PIXELS,
637                                                   new_x * TILE_SIZE_PIXELS,
638                                                   new_y * TILE_SIZE_PIXELS,
639                                                   TILE_SIZE_PIXELS,
640                                                   TILE_SIZE_PIXELS);
641                         } else {
642                                 map_render_tile(new_base_tilex + new_x,
643                                                 new_base_tiley + new_y,
644                                                 new_x * TILE_SIZE_PIXELS,
645                                                 new_y * TILE_SIZE_PIXELS,
646                                                 map_drag_id!=0 ? TRUE : FALSE);
647                         }
648                 }
649         }
650         map_render_data();
651 }
652
653 MACRO_RECALC_OFFSET();
654 MACRO_RECALC_FOCUS_BASE(_center_ratio);
655
656 map_set_mark(&_gps->data);
657 MACRO_QUEUE_DRAW_AREA();
658 }
659
660 /**
661  * Pan the view by the given number of units in the X and Y directions.
662  */
663 void 
664 map_pan(gint delta_unitx, gint delta_unity)
665 {
666 if (_center_mode > 0)
667         set_action_activate("autocenter_none", TRUE);
668
669 map_center_unit(_center.unitx + delta_unitx, _center.unity + delta_unity);
670 }
671
672 /**
673  * Helper to center map on given lat/lon
674  */
675 void
676 map_center_latlon(gdouble lat, gdouble lon)
677 {
678 guint unitx, unity;
679
680 latlon2unit(lat, lon, unitx, unity);
681 map_center_unit(unitx, unity);
682 }
683
684 /**
685  * Helper to goto given point and update location
686  * 
687  */
688 gboolean
689 map_goto_position(Position *pos)
690 {
691 if (pos->valid==FALSE)
692         return FALSE;
693
694 _center_mode=CENTER_MANUAL;
695 map_center_latlon(pos->lat, pos->lon);
696 map_set_autozoom(FALSE, 0);
697 g_idle_add_full(G_PRIORITY_HIGH_IDLE,(GSourceFunc)map_update_location_from_center, NULL, NULL);
698 return TRUE;
699 }
700
701 /**
702  * Initiate a move of the mark from the old location to the current
703  * location.  This function queues the draw area of the old mark (to force
704  * drawing of the background map), then updates the mark, then queus the
705  * draw area of the new mark.
706  */
707 void 
708 map_move_mark(void)
709 {
710 /* Just queue the old and new draw areas. */
711 gtk_widget_queue_draw_area(_map_widget,
712                    mark_minx<0 ? 0 : mark_minx,
713                    mark_miny<0 ? 0 : mark_miny, 
714                    mark_width, mark_height);
715 map_set_mark(&_gps->data);
716 gtk_widget_queue_draw_area(_map_widget,
717                    mark_minx<0 ? 0 : mark_minx,
718                    mark_miny<0 ? 0 : mark_miny, 
719                    mark_width, mark_height);
720 }
721
722 gboolean
723 map_update_location_from_gps(Gps *gps)
724 {
725 g_assert(gps);
726 map_update_location(gps->data.lat, gps->data.lon, FALSE);
727 return FALSE;
728 }
729
730 gboolean
731 map_update_location_from_center(void)
732 {
733 gdouble lat, lon;
734 /* Force re-validation of place if user is clicking around */
735 map_loc.valid=FALSE;
736 /* XXX: hmm, not the right place for this */
737 #if 0
738 if (_gps->fix==FIX_NOFIX) {
739         _gps->data.unitx=_center.unitx;
740         _gps->data.unity=_center.unity;
741         unit2latlon(_gps->data.unitx, _gps->data.unity, _gps->data.lat, _gps->data.lon);
742 }
743 #endif
744 unit2latlon(_center.unitx, _center.unity, lat, lon);
745 map_update_location(lat, lon, TRUE);
746 return FALSE;
747 }
748
749 /**
750  * Draw given pixbuf on map, centered on x,y
751  */
752 void
753 map_draw_pixbuf(guint unitx, guint unity, GdkPixbuf *p)
754 {
755 gint x,y;
756 x = unit2bufx(unitx);
757 y = unit2bufy(unity);
758
759 if ((x > buf_width_pixels) || (y > buf_height_pixels))
760         return;
761
762 gdk_draw_pixbuf(map_pixmap, _gc[COLORABLE_POI],
763         p, 0, 0,
764         x - gdk_pixbuf_get_width(p) / 2,
765         y - gdk_pixbuf_get_height(p) / 2,
766         -1, -1, GDK_RGB_DITHER_NONE, 0, 0);
767 }
768
769 /**
770  * Draw an icon on given Position.
771  * 
772  * XXX: don't hardcode as home.png !
773  */
774 void
775 map_draw_position_icon(Position *pos)
776 {
777 guint x,y, x1,y1;
778 GdkPixbuf *p;
779
780 latlon2unit(pos->lat, pos->lon, x, y);
781 x1=unit2bufx(x);
782 y1=unit2bufy(y);
783
784 if ((x1 > buf_width_pixels) || (y1 > buf_height_pixels))
785         return;
786
787 p=gdk_pixbuf_new_from_file(DATADIR "/pixmaps/mapper/home.png", NULL);
788 if (p) {
789         map_draw_pixbuf(x,y,p);
790         g_object_unref(p);
791 }
792
793 }
794
795 /**
796  * Make sure the mark is up-to-date.  This function triggers a panning of
797  * the view if the mark is appropriately close to the edge of the view.
798  */
799 void
800 map_refresh_mark(void)
801 {
802 guint new_center_unitx;
803 guint new_center_unity;
804
805 MACRO_RECALC_CENTER(_gps->data, new_center_unitx, new_center_unity);
806
807 if ((new_center_unitx - _focus.unitx) < _focus_unitwidth && (new_center_unity - _focus.unity) < _focus_unitheight)
808         /* We're not changing the view - just move the mark. */
809         map_move_mark();
810 else
811         map_center_unit(new_center_unitx, new_center_unity);
812
813 /* Draw speed info */
814 if (_speed_on)
815         map_speed_draw();
816
817 if (_center_mode>0)
818         g_idle_add_full(G_PRIORITY_HIGH_IDLE,(GSourceFunc)map_update_location_from_gps, _gps, NULL);
819 }
820
821 /**
822  * Render a single track line to map_pixmap.  If either point on the line
823  * is a break (defined as unity == 0), a circle is drawn at the other point.
824  * IT IS AN ERROR FOR BOTH POINTS TO INDICATE A BREAK.
825  */
826 void
827 map_render_segment(GdkGC *gc_norm, GdkGC *gc_alt, guint unitx1, guint unity1, guint unitx2, guint unity2)
828 {
829 if (!unity1) {
830         guint x2, y2;
831
832         x2 = unit2bufx(unitx2);
833         y2 = unit2bufy(unity2);
834         /* Make sure this circle will be visible. */
835         if ((x2 < buf_width_pixels) && (y2 < buf_height_pixels))
836                 gdk_draw_arc(map_pixmap, gc_alt, FALSE, /* FALSE: not filled. */
837                      x2 - _draw_width, y2 - _draw_width, 2 * _draw_width, 2 * _draw_width, 0,   /* start at 0 degrees. */
838                      360 * 64);
839 } else if (!unity2) {
840         guint x1, y1;
841
842         x1 = unit2bufx(unitx1);
843         y1 = unit2bufy(unity1);
844         /* Make sure this circle will be visible. */
845         if ((x1 < buf_width_pixels) && ((unsigned)y1 < buf_height_pixels))
846                 gdk_draw_arc(map_pixmap, gc_alt, FALSE, /* FALSE: not filled. */
847                      x1 - _draw_width, y1 - _draw_width, 2 * _draw_width, 2 * _draw_width, 0,   /* start at 0 degrees. */
848                      360 * 64);
849 } else {
850         gint x1, y1, x2, y2;
851
852         x1 = unit2bufx(unitx1);
853         y1 = unit2bufy(unity1);
854         x2 = unit2bufx(unitx2);
855         y2 = unit2bufy(unity2);
856         /* Make sure this line could possibly be visible. */
857         if (!((x1 > buf_width_pixels && x2 > buf_width_pixels)
858               || (x1 < 0 && x2 < 0)
859               || (y1 > buf_height_pixels && y2 > buf_height_pixels)
860               || (y1 < 0 && y2 < 0)))
861                 gdk_draw_line(map_pixmap, gc_norm, x1, y1, x2, y2);
862         }
863 }
864
865 void
866 map_render_waypoint(guint x1, guint y1, GdkGC *gc)
867 {
868 if ((x1 > buf_width_pixels) || (y1 > buf_height_pixels))
869         return;
870 gdk_draw_arc(map_pixmap, gc, FALSE, x1 - _draw_width, y1 - _draw_width, 2 * _draw_width, 2 * _draw_width, 0, 360 * 64);
871 }
872
873 /**
874  * Render all track data onto the map_pixmap.  Note that this does not
875  * clear the pixmap of previous track data (use map_force_redraw() for
876  * that), and also note that this method does not queue any redraws, so it
877  * is up to the caller to decide which part of the track really needs to be
878  * redrawn.
879  */
880 void 
881 map_render_path(Path * path, GdkGC ** gc)
882 {
883 Point *curr;
884 WayPoint *wcurr;
885
886 /* gc is a pointer to the first GC to use (for plain points).  (gc + 1)
887  * is a pointer to the GC to use for waypoints, and (gc + 2) is a pointer
888  * to the GC to use for breaks. */
889
890 /* else there is a route to draw. */
891 for (curr = path->head, wcurr = path->whead; curr++ != path->tail;) {
892         /* Draw the line from (curr - 1) to (curr). */
893         map_render_segment(gc[0], gc[2], curr[-1].unitx, curr[-1].unity, curr->unitx, curr->unity);
894
895         /* Now, check if curr is a waypoint. */
896         if (wcurr && wcurr <= path->wtail && wcurr->point == curr) {
897                 guint x1 = unit2bufx(wcurr->point->unitx);
898                 guint y1 = unit2bufy(wcurr->point->unity);
899
900                 map_render_waypoint(x1, y1, _gc[COLORABLE_TRACK_BREAK]);
901                 wcurr++;
902         }
903 }
904 }
905
906 void 
907 map_render_paths(void)
908 {
909 if ((_show_tracks & ROUTES_MASK) && _route->head != _route->tail) {
910         map_render_path(_route, _gc + COLORABLE_ROUTE);
911
912         /* Now, draw the next waypoint on top of all other waypoints. */
913         if (_next_way) {
914                 guint x1 = unit2bufx(_next_way->point->unitx);
915                 guint y1 = unit2bufy(_next_way->point->unity);
916
917                 if ((x1 < buf_width_pixels) && (y1 < buf_height_pixels)) {
918                         /* Draw the next waypoint as a break. */
919                         gdk_draw_arc(map_pixmap, _gc[COLORABLE_ROUTE_BREAK], FALSE,     /* FALSE: not filled. */
920                              x1 - _draw_width, y1 - _draw_width, 4 * _draw_width, 4 * _draw_width, 0,   /* start at 0 degrees. */
921                              360 * 64);
922                 }
923         }
924 }
925 if (_show_tracks & TRACKS_MASK)
926         map_render_path(_track, _gc + COLORABLE_TRACK);
927 }
928
929 /**
930  * 
931  *
932  */
933 static gboolean 
934 map_follow_move_cb(GtkWidget *widget, GdkEventMotion *event, gpointer data)
935 {
936 GdkModifierType state;
937 gint xx, yy;
938 guint unitx, unity, nunitx, nunity;
939 guint cx, cy;
940
941 if (!(event->state & GDK_BUTTON1_MASK)) {
942         map_drag_id=0;
943         return TRUE;
944 }
945
946 if (event->is_hint) {
947         gdk_window_get_pointer(event->window, &xx, &yy, &state);
948         state = event->state;
949 } else {
950         xx = event->x;
951         yy = event->y;
952         state = event->state;
953 }
954
955 unitx = x2unit((gint) (xx - before[0]));
956 unity = y2unit((gint) (yy - before[1]));
957 cx = unit2x(_center.unitx);
958 cy = unit2y(_center.unity);
959
960 nunitx=x2unit((gint) (cx - (xx - before[0])));
961 nunity=y2unit((gint) (cy - (yy - before[1])));
962
963 map_center_unit(nunitx, nunity);
964
965 map_dragged=TRUE;
966 g_debug("MAP PAN: %d %d %d %d (%d, %d)", cx, cy, xx, yy, nunitx, nunity);
967 before[0] = xx;
968 before[1] = yy;
969 return FALSE;
970 }
971
972 gboolean 
973 map_key_zoom_timeout(void)
974 {
975 if (_key_zoom_new < _zoom) {
976         /* We're currently zooming in (_zoom is decreasing). */
977         guint test = _key_zoom_new - _curr_repo->view_zoom_steps;
978         if (test < map_max_zoom)
979                 _key_zoom_new = test;
980         else
981                 return FALSE;
982 } else {
983         /* We're currently zooming out (_zoom is increasing). */
984         guint test = _key_zoom_new + _curr_repo->view_zoom_steps;
985         if (test < map_max_zoom)
986                 _key_zoom_new = test;
987         else
988                 return FALSE;
989 }
990
991 return TRUE;
992 }
993
994 static void
995 map_information_text(guint x, guint y, GdkGC *gc, gchar *msg)
996 {
997 guint width, height;
998
999 pango_layout_set_text(speed_layout, msg, -1);
1000 pango_layout_get_pixel_size(speed_layout, &width, &height);
1001 gtk_widget_queue_draw_area(_map_widget, x - 5, y - 5, width * 3 + 15, height + 5);
1002 gdk_window_process_all_updates();
1003 gdk_draw_layout(_map_widget->window, gc, x, y, speed_layout);
1004 }
1005
1006 static void
1007 map_speed_draw(void)
1008 {
1009 GdkGC *gc;
1010 gfloat cur_speed;
1011 gchar *buffer;
1012
1013 cur_speed = _gps->data.speed * UNITS_CONVERT[_units];
1014 gc=(cur_speed > _speed_limit) ? speed_gc1 : speed_gc2;
1015 buffer = g_strdup_printf("%0.0f", cur_speed);
1016 map_information_text(10, 10, gc, buffer);
1017 g_free(buffer);
1018 }
1019
1020 static void 
1021 map_scale_draw(GdkEventExpose *event)
1022 {
1023 gchar buffer[16];
1024 gdouble distance;
1025 gdouble lat1, lon1, lat2, lon2;
1026 gint width;
1027
1028 pango_layout_set_text(scale_layout, "0", -1);
1029 pango_layout_get_pixel_size(scale_layout, NULL, &scale_rect.height);
1030 scale_rect.y = _screen_height_pixels - scale_rect.height - 1;
1031
1032 gdk_rectangle_intersect(&event->area, &scale_rect, &event->area);
1033
1034 if (event->area.width && event->area.height) {
1035         gdk_draw_rectangle(_map_widget->window,
1036                            _map_widget->style->bg_gc[GTK_WIDGET_STATE(_map_widget)],
1037                            TRUE, scale_rect.x, scale_rect.y,
1038                            scale_rect.width,
1039                            scale_rect.height);
1040         gdk_draw_rectangle(_map_widget->window,
1041                            _map_widget->style->fg_gc[GTK_WIDGET_STATE(_map_widget)],
1042                            FALSE, scale_rect.x, scale_rect.y,
1043                            scale_rect.width,
1044                            scale_rect.height);
1045
1046         /* Now calculate and draw the distance. */
1047         unit2latlon(_center.unitx - pixel2unit(SCALE_WIDTH / 2 - 4), _center.unity, lat1, lon1);
1048         unit2latlon(_center.unitx + pixel2unit(SCALE_WIDTH / 2 - 4), _center.unity, lat2, lon2);
1049         distance=calculate_distance(lat1, lon1, lat2, lon2) * UNITS_CONVERT[_units];
1050
1051         if (distance < 1.f)
1052                 g_snprintf(buffer, sizeof(buffer), "%0.2f %s", distance, UNITS_TEXT[_units]);
1053         else if (distance < 10.f)
1054                 g_snprintf(buffer, sizeof(buffer), "%0.1f %s", distance, UNITS_TEXT[_units]);
1055         else
1056                 g_snprintf(buffer, sizeof(buffer), "%0.f %s", distance, UNITS_TEXT[_units]);
1057
1058         pango_layout_set_text(scale_layout, buffer, -1);
1059         pango_layout_get_pixel_size(scale_layout, &width, NULL);
1060
1061         /* Draw the layout itself. */
1062         gdk_draw_layout(_map_widget->window,
1063                         _map_widget->style->fg_gc[GTK_WIDGET_STATE(_map_widget)],
1064                         scale_rect.x + (scale_rect.width - width) / 2,
1065                         scale_rect.y, scale_layout);
1066
1067         /* Draw little hashes on the ends. */
1068         gdk_draw_line(_map_widget->window,
1069                       _map_widget->style->fg_gc[GTK_WIDGET_STATE(_map_widget)],
1070                       scale_rect.x + 4,
1071                       scale_rect.y + scale_rect.height / 2 - 4,
1072                       scale_rect.x + 4,
1073                       scale_rect.y + scale_rect.height / 2 + 4);
1074         gdk_draw_line(_map_widget->window,
1075                       _map_widget->style->fg_gc[GTK_WIDGET_STATE(_map_widget)],
1076                       scale_rect.x + 4,
1077                       scale_rect.y + scale_rect.height / 2,
1078                       scale_rect.x + (scale_rect.width - width) / 2 - 4,
1079                       scale_rect.y + scale_rect.height / 2);
1080         gdk_draw_line(_map_widget->window,
1081                       _map_widget->style->fg_gc[GTK_WIDGET_STATE(_map_widget)],
1082                       scale_rect.x + scale_rect.width - 4,
1083                       scale_rect.y + scale_rect.height / 2 - 4,
1084                       scale_rect.x + scale_rect.width - 4,
1085                       scale_rect.y + scale_rect.height / 2 + 4);
1086         gdk_draw_line(_map_widget->window,
1087                       _map_widget->style->fg_gc[GTK_WIDGET_STATE(_map_widget)],
1088                       scale_rect.x + scale_rect.width - 4,
1089                       scale_rect.y + scale_rect.height / 2,
1090                       scale_rect.x + (scale_rect.width + width) / 2 + 4,
1091                       scale_rect.y + scale_rect.height / 2);
1092         }
1093 }
1094
1095 static gboolean 
1096 map_cb_expose(GtkWidget * widget, GdkEventExpose * event)
1097 {
1098 gdk_draw_drawable(GDK_DRAWABLE(_map_widget->window),
1099                 _gc[COLORABLE_MARK],
1100                 map_pixmap,
1101                 event->area.x + _offsetx, event->area.y + _offsety,
1102                 event->area.x, event->area.y,
1103                 event->area.width, event->area.height);
1104 map_draw_mark(_gps);
1105
1106 /* Draw scale, if necessary. */
1107 if (_show_scale)
1108         map_scale_draw(event);
1109
1110 #if 0
1111 if (_speed_on)
1112         map_speed_draw();
1113 #endif
1114
1115 return TRUE;
1116 }
1117
1118 int 
1119 map_zoom(gint zdir)
1120 {
1121 gint nzoom;
1122
1123 nzoom=_zoom+zdir;
1124 if ((nzoom >= 0) && (nzoom < map_max_zoom - 1)) {
1125         map_set_zoom(nzoom);
1126 }
1127 return nzoom;
1128 }
1129
1130 gboolean
1131 map_zoom_in(void)
1132 {
1133 map_zoom(-1);
1134 return FALSE;
1135 }
1136
1137 gboolean
1138 map_zoom_out(void)
1139 {
1140 map_zoom(1);
1141 return FALSE;
1142 }
1143
1144 static gboolean
1145 map_autozoomer(void)
1146 {
1147 static gfloat z=5.0;
1148 static gint last=5;
1149 gint b=0;
1150 gint iz;
1151
1152 if (zoom_timeout_sid==0)
1153         return FALSE;
1154
1155 /* If location is known, use road type and speed for zoom setting */
1156 if (map_loc.valid && map_loc.street) {
1157         switch (map_loc.street->type) {
1158         case WAY_MOTORWAY:
1159         case WAY_TRUNK:
1160                 b=2;
1161         break;
1162         case WAY_PRIMARY:
1163         case WAY_SECONDARY:
1164                 b=1;
1165         break;
1166         default:
1167                 b=0;
1168         break;
1169         }
1170 }
1171
1172 z=(z+_gps->data.speed+1)/5;
1173 z+=b;
1174 if (z>5) z=5.0; else if (z<1) z=1.0;
1175 iz=(gint)roundf(z);
1176 g_debug("Setting autozoom to: %f %d S:%f\n", z, iz, _gps->data.speed);
1177 if (iz>last) 
1178         iz=last+1; 
1179 else if (iz<last) 
1180         iz=last-1;
1181 last=iz;
1182 map_set_zoom(iz);
1183
1184 return TRUE;
1185 }
1186
1187 void
1188 map_set_autozoom(gboolean az, gfloat speed)
1189 {
1190 if (az==TRUE) {
1191         zoom_timeout_sid=g_timeout_add(speed<5 ? 2000 : 5000, (GSourceFunc) map_autozoomer, NULL);
1192         MACRO_BANNER_SHOW_INFO(_window, "Autozoom enabled");
1193         return;
1194 } else {
1195         if (zoom_timeout_sid) {
1196                 g_source_remove(zoom_timeout_sid);
1197                 zoom_timeout_sid=0;
1198                 MACRO_BANNER_SHOW_INFO(_window, "Autozoom disabled");
1199         }
1200         return;
1201 }
1202
1203 }
1204
1205 static void 
1206 map_draw_route(gint x, gint y)
1207 {
1208 cmenu_route_add_way(x, y);
1209 }
1210
1211 static void 
1212 map_draw_track(gint x, gint y)
1213 {
1214 _gps->data.unitx=x2unit((gint) (x + 0.5));
1215 _gps->data.unity=y2unit((gint) (y + 0.5));
1216 unit2latlon(_gps->data.unitx, _gps->data.unity, _gps->data.lat, _gps->data.lon);
1217 _gps->data.speed=20.f;
1218 gps_data_integerize(&_gps->data);
1219 _gps->data.time=time(NULL);
1220 track_add(&_gps->data);
1221 map_refresh_mark();
1222 }
1223
1224 static void
1225 map_set_place_information(osm_way *s, osm_place *mp, osm_place *sp)
1226 {
1227 gchar buffer[256];
1228
1229 if (!s && !mp && !sp) {
1230         g_snprintf(buffer, sizeof(buffer), _("Unknown location"));
1231 } else {
1232         /* oh, fun */
1233         g_snprintf(buffer, sizeof(buffer), "%s%s%s%s%s%s%s%s%s%s", 
1234         s ? s->name ? s->name : "" : "",
1235         s ? s->ref ? ", " : "" : "",
1236         s ? s->ref ? s->ref : "" : "",
1237         s ? s->int_ref ? " (" : "" : "",
1238         s ? s->int_ref ? s->int_ref : "" : "",
1239         s ? s->int_ref ? ") " : "" : "",
1240         (sp && sp->name) ? " in " : "",
1241         (sp && sp->name) ? sp->name : "",
1242         (mp && mp->name) ? " in " : "",
1243         (mp && mp->name) ? mp->name : "");
1244 }
1245 gtk_label_set_label(GTK_LABEL(info_banner.location), buffer);
1246 }
1247
1248 static void
1249 map_update_destination(gdouble lat, gdouble lon)
1250 {
1251 gdouble dh=0.0;
1252 gdouble dt, cdist;
1253 static gdouble prev_dt=99999.0;
1254 static gboolean dest_reached=FALSE;
1255 gchar buffer[64];
1256
1257 if (_dest.valid) {
1258         dt=calculate_distance(lat, lon, _dest.lat, _dest.lon);
1259         dh=calculate_course(lat, lon, _dest.lat, _dest.lon);
1260         cdist=dt*UNITS_CONVERT[_units];
1261
1262         g_snprintf(buffer, sizeof(buffer), "%.02f %s (%0.02f)", cdist, UNITS_TEXT[_units], dh<0 ? 360+dh : dh);
1263         gtk_label_set_label(GTK_LABEL(info_banner.distance), buffer);
1264
1265         if (dt<0.005 && dest_reached==FALSE) {
1266                 if (_center_mode>0)
1267                         announce_destination_reached();
1268                 dest_reached=TRUE;
1269         } else if (dt<prev_dt-KM10KNOTS) {
1270                 if (_center_mode>0 && _announce_destination==TRUE)
1271                         announce_distance_to_destination(cdist, UNITS_TEXT[_units], KM10KNOTS);
1272                 prev_dt=dt;
1273         } else if (dt>prev_dt+KM10KNOTS/4) {
1274                 prev_dt=dt;
1275         }
1276         if (dt>0.05) {
1277                 dest_reached=FALSE;
1278         }
1279         g_debug("%f (Prev:%f)\n", prev_dt, dt);
1280 } else {
1281         dest_reached=FALSE;
1282         prev_dt=99999.0;
1283         gtk_label_set_label(GTK_LABEL(info_banner.distance), "");
1284 }
1285
1286 gtk_compass_set_dest_heading(_gps_compass, _dest.valid, (gfloat)dh);
1287 gtk_compass_set_dest_heading(_tab_compass, _dest.valid, (gfloat)dh);
1288
1289 if (_next_way && _next_way->point) {
1290         gdouble wp_lat, wp_lon;
1291         gfloat wc;
1292
1293         unit2latlon(_next_way->point->unitx,_next_way->point->unity, wp_lat, wp_lon);
1294         wc=calculate_course(lat, lon, wp_lat, wp_lon);
1295         gtk_compass_set_way_heading(_gps_compass, TRUE, wc);
1296         gtk_compass_set_way_heading(_tab_compass, TRUE, wc);
1297 } else {
1298         gtk_compass_set_way_heading(_gps_compass, FALSE, 0);
1299         gtk_compass_set_way_heading(_tab_compass, FALSE, 0);
1300 }
1301
1302 }
1303
1304 /**
1305  * Query the OSM database for where we are.
1306  * 
1307  * XXX: This is the wrong place for this function.
1308  */
1309 static void 
1310 map_update_location(gdouble lat, gdouble lon, gboolean force)
1311 {
1312 gint ilat, ilon;
1313 static gboolean inp=FALSE;
1314
1315 /* We run the gtk mainloop in progress callback so we can be called again, we don't like that */
1316 if (inp==TRUE) {
1317         g_debug("LOC: Query in progress");
1318         return;
1319 }
1320 inp=TRUE;
1321
1322 ilat=lat2mp_int(lat);
1323 ilon=lon2mp_int(lon);
1324
1325 if (_gps->data.fix>1 && !force)
1326         osm_set_way_range_from_speed(_gps->data.speed);
1327 else
1328         osm_set_way_range(2800);
1329
1330 /* XXX: Don't pulse progress if we don't need to check location ! */
1331 osm_progress_set_widget(_db, _progress_item);
1332 osm_get_location_data(ilat, ilon, _gps->data.heading, &map_loc);
1333 if (map_loc.valid)
1334         map_set_place_information(map_loc.street, map_loc.primary, map_loc.secondary);
1335 else
1336         map_set_place_information(NULL, NULL, NULL);
1337 osm_progress_set_widget(_db, NULL);
1338
1339 map_update_destination(lat, lon);
1340
1341 inp=FALSE;
1342 }
1343
1344 /**
1345  * Mouse scroller zoom in/out callback
1346  */
1347 static gboolean
1348 map_cb_scroll_event(GtkWidget * widget, GdkEventScroll * event)
1349 {
1350 if (event->direction == GDK_SCROLL_UP) {
1351         map_center_unit(x2unit((gint) (event->x + 0.5)), y2unit((gint) (event->y + 0.5)));
1352         map_set_zoom(_zoom - 1);
1353 } else if (event->direction == GDK_SCROLL_DOWN) {
1354         map_center_unit(x2unit((gint) (event->x + 0.5)), y2unit((gint) (event->y + 0.5)));
1355         map_set_zoom(_zoom + 1);
1356 }
1357 return FALSE;
1358 }
1359
1360 /** 
1361  * Start map drag operation
1362  */
1363 static void
1364 map_drag_start(gint x,gint y)
1365 {
1366 press[0] = x;
1367 press[1] = y;
1368 before[0] = press[0];
1369 before[1] = press[1];
1370 _center_mode=CENTER_MANUAL;
1371 if (map_drag_id!=0)
1372         g_signal_handler_disconnect(G_OBJECT(_map_widget), map_drag_id);
1373 map_dragged=FALSE;
1374 map_drag_id=g_signal_connect(G_OBJECT(_map_widget), "motion_notify_event", G_CALLBACK(map_follow_move_cb), NULL);
1375 }
1376
1377 /**
1378  * Stop map drag operation
1379  */
1380 static void
1381 map_drag_stop(gint x, gint y)
1382 {
1383 if (map_drag_id==0)
1384         return;
1385
1386 g_signal_handler_disconnect(G_OBJECT(_map_widget), map_drag_id);
1387
1388 release[0]=x;
1389 release[1]=y;
1390 press[0]=0;
1391 press[1]=0;
1392 release[0]=0;
1393 release[1]=0;
1394 before[0]=0;
1395 before[1]=0;
1396 map_drag_id=0;
1397 if (map_dragged==TRUE)
1398         map_force_redraw();
1399 }
1400
1401 /* Workaround hildon content menu problem */
1402 static gboolean
1403 map_cb_show_poi_info_dialog(gpointer data)
1404 {
1405 guint poi_id=GPOINTER_TO_INT(data);
1406 if (poi_info_dialog(_window, poi_id)==FALSE)
1407         g_printerr("Huh? Failed to display info dialog\n");
1408 return FALSE;
1409 }
1410
1411 static gboolean 
1412 map_cb_button_press(GtkWidget * widget, GdkEventButton * event)
1413 {
1414 _cmenu_position_x = event->x + 0.5;
1415 _cmenu_position_y = event->y + 0.5;
1416
1417 switch (event->button) {
1418 case 1:
1419         if (event->type==GDK_2BUTTON_PRESS) {
1420                 map_center_unit(x2unit((gint) (event->x + 0.5)), y2unit((gint) (event->y + 0.5)));
1421 #ifdef MAP_ZOOM_ON_DOUBLE_CLICK
1422                 map_set_zoom(_zoom-1);
1423 #endif
1424                 map_data_needs_refresh=TRUE;
1425                 map_drag_stop(event->x, event->y);
1426                 return FALSE;
1427         }
1428         if (event->type==GDK_3BUTTON_PRESS) {
1429                 map_drag_stop(event->x, event->y);
1430                 return FALSE;
1431         }
1432
1433         map_drag_start(event->x, event->y);
1434         return FALSE;
1435 break;
1436 case 2:
1437         map_set_zoom(_zoom - 1);
1438 break;
1439 case 3:
1440 #ifndef WITH_HILDON
1441         gtk_menu_popup(GTK_MENU(_menu_map), NULL, NULL, NULL, NULL, event->button, gtk_get_current_event_time());
1442 #endif
1443 break;
1444 }
1445 /* Return FALSE to allow context menu to work. */
1446 return FALSE;
1447 }
1448
1449 static gboolean 
1450 map_cb_button_release(GtkWidget *widget, GdkEventButton *event)
1451 {
1452 gdouble lat, lon;
1453 guint poi_id;
1454 gint ux, uy;
1455
1456 switch (event->button) {
1457 case 1:
1458         if (_center_mode>0)
1459                 set_action_activate("autocenter_none", TRUE);
1460
1461         switch (map_mode) {
1462         case MAP_MODE_DRAW_TRACK:
1463                 map_draw_track(event->x, event->y);
1464         break;
1465         case MAP_MODE_DRAW_ROUTE:
1466                 map_draw_route(event->x, event->y);
1467         break;
1468         case MAP_MODE_SET_ROUTE_FROM:
1469         case MAP_MODE_SET_ROUTE_POINT:
1470         case MAP_MODE_SET_ROUTE_TO:
1471         break;
1472         default:
1473                 ux=x2unit(_cmenu_position_x);
1474                 uy=y2unit(_cmenu_position_y);
1475
1476                 unit2latlon(ux, uy, lat, lon);
1477                 if (map_poi_find_at_latlon(lat, lon, &poi_id)==TRUE) {
1478                         g_debug("POI: %d", poi_id);
1479                         g_idle_add_full(G_PRIORITY_HIGH_IDLE,(GSourceFunc)map_cb_show_poi_info_dialog, GINT_TO_POINTER(poi_id), NULL);
1480                 }
1481                 if (map_data_needs_refresh==TRUE) {
1482                         map_data_needs_refresh=FALSE;
1483                         map_render_data();
1484                         g_idle_add_full(G_PRIORITY_HIGH_IDLE,(GSourceFunc)map_update_location_from_center, NULL, NULL);
1485                 }
1486                 map_drag_stop(event->x, event->y);
1487         break;
1488         }
1489 break;
1490 case 2:
1491         /* */
1492 break;
1493 case 3:
1494 break;
1495 }
1496
1497 /* Return FALSE to avoid context menu (if it hasn't popped up already). */
1498 return FALSE;
1499 }
1500
1501 gboolean 
1502 map_dialog_goto_latlon(void)
1503 {
1504 GtkWidget *dialog;
1505 GtkWidget *table;
1506 GtkWidget *label;
1507 GtkWidget *txt_lat;
1508 GtkWidget *txt_lon;
1509
1510 dialog = gtk_dialog_new_with_buttons(_("Go to Lat/Lon"),
1511                      GTK_WINDOW(_window),
1512                      GTK_DIALOG_MODAL, GTK_STOCK_OK,
1513                      GTK_RESPONSE_ACCEPT,
1514                      GTK_STOCK_CANCEL,
1515                      GTK_RESPONSE_REJECT, NULL);
1516
1517 gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), table = gtk_table_new(2, 3, FALSE), TRUE, TRUE, 0);
1518
1519 gtk_table_attach(GTK_TABLE(table), label = gtk_label_new(_("Latitude")),0, 1, 0, 1, GTK_FILL, 0, 2, 4);
1520 gtk_misc_set_alignment(GTK_MISC(label), 1.f, 0.5f);
1521
1522 gtk_table_attach(GTK_TABLE(table), txt_lat = gtk_entry_new(), 1, 2, 0, 1, GTK_FILL, 0, 2, 4);
1523 gtk_misc_set_alignment(GTK_MISC(label), 0.0f, 0.5f);
1524
1525 gtk_table_attach(GTK_TABLE(table), label = gtk_label_new(_("Longitude")), 0, 1, 1, 2, GTK_FILL, 0, 2, 4);
1526 gtk_misc_set_alignment(GTK_MISC(label), 1.f, 0.5f);
1527
1528 gtk_table_attach(GTK_TABLE(table), txt_lon = gtk_entry_new(), 1, 2, 1, 2, GTK_FILL, 0, 2, 4);
1529 gtk_misc_set_alignment(GTK_MISC(label), 0.0f, 0.5f);
1530
1531 #if defined (WITH_DEVICE_770) && !defined(WITH_HILDON_NEW)
1532 g_object_set(G_OBJECT(txt_lat), HILDON_INPUT_MODE_HINT, HILDON_INPUT_MODE_HINT_NUMERICSPECIAL, NULL);
1533 g_object_set(G_OBJECT(txt_lon), HILDON_INPUT_MODE_HINT, HILDON_INPUT_MODE_HINT_NUMERICSPECIAL, NULL);
1534 #endif
1535
1536 /* Initialize with the current center position. */
1537 {
1538         gchar buffer[32];
1539         gdouble lat, lon;
1540         unit2latlon(_center.unitx, _center.unity, lat, lon);
1541         g_snprintf(buffer, sizeof(buffer), "%.06f", lat);
1542         gtk_label_set_text(GTK_LABEL(txt_lat), buffer);
1543         g_snprintf(buffer, sizeof(buffer), "%.06f", lon);
1544         gtk_label_set_text(GTK_LABEL(txt_lon), buffer);
1545 }
1546
1547 gtk_widget_show_all(dialog);
1548
1549 while (GTK_RESPONSE_ACCEPT == gtk_dialog_run(GTK_DIALOG(dialog))) {
1550         const gchar *text;
1551         gchar *error_check;
1552         gdouble lat, lon;
1553         guint unitx, unity;
1554
1555         text = gtk_entry_get_text(GTK_ENTRY(txt_lat));
1556         lat = strtof(text, &error_check);
1557         if (text == error_check || lat < -90.f || lat > 90.f) {
1558                 popup_error(dialog, _("Invalid Latitude"));
1559                 continue;
1560         }
1561
1562         text = gtk_entry_get_text(GTK_ENTRY(txt_lon));
1563         lon = strtof(text, &error_check);
1564         if (text == error_check || lon < -180.f || lon > 180.f) {
1565                 popup_error(dialog, _("Invalid Longitude"));
1566                 continue;
1567         }
1568
1569         latlon2unit(lat, lon, unitx, unity);
1570         if (_center_mode > 0)
1571                 set_action_activate("autocenter_none", TRUE);
1572
1573         map_center_unit(unitx, unity);
1574         break;
1575 }
1576 gtk_widget_destroy(dialog);
1577 return TRUE;
1578 }
1579