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