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