]> err.no Git - mapper/blob - src/map.c
Misc
[mapper] / src / map.c
1 #include <config.h>
2
3 #define _GNU_SOURCE
4
5 #include <unistd.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <strings.h>
9 #include <stddef.h>
10 #include <locale.h>
11 #include <math.h>
12 #include <errno.h>
13 #include <sys/wait.h>
14 #include <glib/gstdio.h>
15 #include <gtk/gtk.h>
16 #include <fcntl.h>
17 #include <libgnomevfs/gnome-vfs.h>
18 #include <gconf/gconf-client.h>
19 #include <libxml/parser.h>
20 #include <curl/multi.h>
21 #include <libintl.h>
22 #include <locale.h>
23 #include <sqlite3.h>
24
25 #include "hildon-mapper.h"
26
27 #include "utils.h"
28 #include "map.h"
29 #include "osm.h"
30 #include "db.h"
31 #include "osm-db.h"
32 #include "poi.h"
33 #include "route.h"
34 #include "track.h"
35 #include "gps.h"
36 #include "bt.h"
37 #include "mapper-types.h"
38 #include "ui-common.h"
39 #include "settings.h"
40 #include "latlon.h"
41 #include "gpx.h"
42 #include "map-download.h"
43
44 Point _min_center = { -1, -1 };
45 Point _max_center = { -1, -1 };
46 Point _focus = { -1, -1 };
47
48 /** The "base tile" is the upper-left tile in the pixmap. */
49 guint _base_tilex = -5;
50 guint _base_tiley = -5;
51
52 guint _zoom = 3;                /* zoom level, from 0 to MAX_ZOOM. */
53 Point _center = { -1, -1 };     /* current center location, X. */
54
55 CenterMode _center_mode = CENTER_LEAD;
56
57 static guint press[2] = { 0, 0 };
58 static guint release[2] = { 0, 0 };
59 static guint before[2] = { 0, 0 };
60 static guint _id = 0;
61
62 /** VARIABLES FOR ACCESSING THE LOCATION/BOUNDS OF THE CURRENT MARK. */
63 static gint _mark_x1;
64 static gint _mark_x2;
65 static gint _mark_y1;
66 static gint _mark_y2;
67 static gint _mark_minx;
68 static gint _mark_miny;
69 static gint _mark_width;
70 static gint _mark_height;
71
72 static gint zoom_timeout_sid=0;
73 static gint map_mode=0;
74
75 static osm_location map_loc = {NULL, NULL, NULL, FALSE, FALSE, 0, 0, 0.0, 0.0, 0 };
76
77 typedef struct _map_tile_rdata map_tile_rdata;
78 struct _map_tile_rdata {
79         guint tilex, tiley, zoom;
80         guint destx, desty;
81 };
82
83 void map_render_paths();
84 void map_force_redraw();
85 static void map_update_location(gint x, gint y, gboolean force);
86 void map_draw_position_icon(Position *pos);
87
88 gboolean 
89 map_cb_configure(GtkWidget * widget, GdkEventConfigure * event)
90 {
91 _screen_width_pixels = _map_widget->allocation.width;
92 _screen_height_pixels = _map_widget->allocation.height;
93 _screen_grids_halfwidth = pixel2grid(_screen_width_pixels) / 2;
94 _screen_grids_halfheight = pixel2grid(_screen_height_pixels) / 2;
95
96 /* Set _scale_rect. */
97 _scale_rect.x = (_screen_width_pixels - SCALE_WIDTH) / 2;
98 _scale_rect.width = SCALE_WIDTH;
99 pango_layout_set_text(_scale_layout, "0", -1);
100 pango_layout_get_pixel_size(_scale_layout, NULL, &_scale_rect.height);
101 _scale_rect.y = _screen_height_pixels - _scale_rect.height - 1;
102
103 MACRO_RECALC_FOCUS_BASE();
104 MACRO_RECALC_FOCUS_SIZE();
105
106 _min_center.unitx = pixel2unit(grid2pixel(_screen_grids_halfwidth));
107 _min_center.unity = pixel2unit(grid2pixel(_screen_grids_halfheight));
108 _max_center.unitx = WORLD_SIZE_UNITS - grid2unit(_screen_grids_halfwidth) - 1;
109 _max_center.unity = WORLD_SIZE_UNITS - grid2unit(_screen_grids_halfheight) - 1;
110
111 map_center_unit(_center.unitx, _center.unity);
112
113 return TRUE;
114 }
115
116 /**
117  * Draw the current mark (representing the current GPS location) onto
118  * _map_widget.  This method does not queue the draw area.
119  */
120 static void 
121 map_draw_mark()
122 {
123 gdk_draw_arc(_map_widget->window, _conn_state == RCVR_FIXED ? _gc[COLORABLE_MARK] : _gc[COLORABLE_MARK_OLD], FALSE,
124      _mark_x1 - _draw_width, _mark_y1 - _draw_width, 
125         2 * _draw_width, 2 * _draw_width, 0, 360 * 64);
126 gdk_draw_line(_map_widget->window,
127       _conn_state == RCVR_FIXED ? (_show_velvec ? _gc[COLORABLE_MARK_VELOCITY] : _gc[COLORABLE_MARK]) : _gc[COLORABLE_MARK_OLD],
128       _mark_x1, _mark_y1, _mark_x2, _mark_y2);
129 }
130
131 /**
132  * "Set" the mark, which translates the current GPS position into on-screen
133  * units in preparation for drawing the mark with map_draw_mark().
134  */
135 void 
136 map_set_mark(void)
137 {
138 _mark_x1 = unit2x(_pos.unitx);
139 _mark_y1 = unit2y(_pos.unity);
140 _mark_x2 = _mark_x1 + (_show_velvec ? _gps.vel_offsetx : 0);
141 _mark_y2 = _mark_y1 + (_show_velvec ? _gps.vel_offsety : 0);
142 _mark_minx = MIN(_mark_x1, _mark_x2) - (2 * _draw_width);
143 _mark_miny = MIN(_mark_y1, _mark_y2) - (2 * _draw_width);
144 _mark_width = abs(_mark_x1 - _mark_x2) + (4 * _draw_width);
145 _mark_height = abs(_mark_y1 - _mark_y2) + (4 * _draw_width);
146 }
147
148 /**
149  * Do an in-place scaling of a pixbuf's pixels at the given ratio from the
150  * given source location.  It would have been nice if gdk_pixbuf provided
151  * this method, but I guess it's not general-purpose enough.
152  */
153 static void
154 map_pixbuf_scale_inplace(GdkPixbuf * pixbuf, guint ratio_p2, guint src_x, guint src_y)
155 {
156         guint dest_x = 0, dest_y = 0, dest_dim = TILE_SIZE_PIXELS;
157         guint rowstride = gdk_pixbuf_get_rowstride(pixbuf);
158         guint n_channels = gdk_pixbuf_get_n_channels(pixbuf);
159         guchar *pixels = gdk_pixbuf_get_pixels(pixbuf);
160
161         /* Sweep through the entire dest area, copying as necessary, but
162          * DO NOT OVERWRITE THE SOURCE AREA.  We'll copy it afterward. */
163         do {
164                 guint src_dim = dest_dim >> ratio_p2;
165                 guint src_endx = src_x - dest_x + src_dim;
166                 gint x, y;
167
168                 for (y = dest_dim - 1; y >= 0; y--) {
169                         guint src_offset_y, dest_offset_y;
170
171                         src_offset_y = (src_y + (y >> ratio_p2)) * rowstride;
172                         dest_offset_y = (dest_y + y) * rowstride;
173                         x = dest_dim - 1;
174
175                         if ((unsigned)(dest_y + y - src_y) < src_dim && (unsigned)(dest_x + x - src_x) < src_dim)
176                                 x -= src_dim;
177
178                         for (; x >= 0; x--) {
179                                 guint src_offset, dest_offset, i;
180
181                                 src_offset = src_offset_y + (src_x + (x >> ratio_p2)) * n_channels;
182                                 dest_offset = dest_offset_y + (dest_x + x) * n_channels;
183
184                                 pixels[dest_offset] = pixels[src_offset];
185                                 for (i = n_channels - 1; i; i--)
186                                         pixels[dest_offset + i] = pixels[src_offset + i];
187
188                                 if ((unsigned)(dest_y + y - src_y) < src_dim && x == src_endx)
189                                         x -= src_dim;
190                         }
191                 }
192                 /* Reuse src_dim and src_endx to store new src_x and src_y. */
193                 src_dim = src_x + ((src_x - dest_x) >> ratio_p2);
194                 src_endx = src_y + ((src_y - dest_y) >> ratio_p2);
195                 dest_x = src_x;
196                 dest_y = src_y;
197                 src_x = src_dim;
198                 src_y = src_endx;
199         }
200         while ((dest_dim >>= ratio_p2) > 1);
201 }
202
203 /**
204  * Trim pixbufs that are bigger than tiles. (Those pixbufs result, when
205  * captions should be cut off.)
206  */
207 static GdkPixbuf *
208 pixbuf_trim(GdkPixbuf * pixbuf)
209 {
210 GdkPixbuf *mpixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, gdk_pixbuf_get_has_alpha(pixbuf),
211                    8, TILE_SIZE_PIXELS, TILE_SIZE_PIXELS);
212
213 gdk_pixbuf_copy_area(pixbuf,
214                      (gdk_pixbuf_get_width(pixbuf) - TILE_SIZE_PIXELS) / 2,
215                      (gdk_pixbuf_get_height(pixbuf) - TILE_SIZE_PIXELS) / 2, 
216                      TILE_SIZE_PIXELS,
217                      TILE_SIZE_PIXELS, mpixbuf, 0, 0);
218
219 g_object_unref(pixbuf);
220 return mpixbuf;
221 }
222
223 void
224 map_render_tile(guint tilex, guint tiley, guint destx, guint desty, gboolean fast_fail)
225 {
226 GdkPixbuf *pixbuf = NULL;
227 gchar buffer[BUFFER_SIZE];
228 GError *error = NULL;
229 gint zoff;
230
231 if (tilex < _world_size_tiles && tiley < _world_size_tiles) {
232         /* The tile is possible. */
233         for (zoff = (_curr_repo->double_size ? 1 : 0);
234              !pixbuf && (_zoom + zoff) <= MAX_ZOOM
235              && zoff <= TILE_SIZE_P2; zoff += 1) {
236                 snprintf(buffer, sizeof(buffer), "%s/%u/%u/%u.jpg",
237                          _curr_repo->cache_dir, _zoom + zoff,
238                          (tilex >> zoff), (tiley >> zoff));
239
240                 pixbuf = gdk_pixbuf_new_from_file(buffer, &error);
241                 if (error || !pixbuf) {
242                         /* Delete so we try again some other day. */
243                         g_unlink(buffer);       
244                         pixbuf = NULL;
245                         error = NULL;
246
247                         /* Download, if we should. */
248                         if (_auto_download && _curr_repo->type != REPOTYPE_NONE &&
249                             !((_zoom + zoff - (_curr_repo->double_size ? 1 : 0)) % _curr_repo->dl_zoom_steps)) {
250                                 if (!fast_fail)
251                                         map_initiate_download(tilex >> zoff,
252                                                               tiley >> zoff,
253                                                               _zoom + zoff,
254                                                               -INITIAL_DOWNLOAD_RETRIES);
255                                 fast_fail = TRUE;
256                         }
257                 } else {
258                         /* Check if we need to trim. */
259                         if (gdk_pixbuf_get_width(pixbuf) != TILE_SIZE_PIXELS || gdk_pixbuf_get_height(pixbuf) != TILE_SIZE_PIXELS)
260                                 pixbuf = pixbuf_trim(pixbuf);
261
262                         /* Check if we need to blit. */
263                         if (zoff) {
264                                 map_pixbuf_scale_inplace(pixbuf, zoff,
265                                                  (tilex - ((tilex >> zoff) << zoff)) << (TILE_SIZE_P2 - zoff),
266                                                  (tiley - ((tiley >> zoff) << zoff)) << (TILE_SIZE_P2 - zoff));
267                         }
268                 }
269         }
270 }
271
272 if (pixbuf) {
273         gdk_draw_pixbuf(_map_pixmap,
274                         _gc[COLORABLE_MARK],
275                         pixbuf, 0, 0, destx, desty,
276                         TILE_SIZE_PIXELS, TILE_SIZE_PIXELS,
277                         GDK_RGB_DITHER_NONE, 0, 0);
278         g_object_unref(pixbuf);
279 } else {
280         gdk_draw_rectangle(_map_pixmap, _map_widget->style->black_gc,
281                            TRUE, destx, desty, TILE_SIZE_PIXELS, TILE_SIZE_PIXELS);
282 }
283 }
284
285 gboolean 
286 map_render_tile_idle(map_tile_rdata *mtr)
287 {
288 map_render_tile(mtr->tilex, mtr->tiley, mtr->destx, mtr->desty, FALSE);
289 gtk_widget_queue_draw_area(_map_widget, mtr->destx, mtr->desty, TILE_SIZE_PIXELS, TILE_SIZE_PIXELS);
290
291 g_slice_free(map_tile_rdata, mtr);
292 return FALSE;
293 }
294
295 void
296 map_render_data(void)
297 {
298 if(_show_poi)
299         map_render_poi();
300 if(_show_tracks > 0)
301         map_render_paths();
302 if (_home.valid)
303         map_draw_position_icon(&_home);
304 }
305
306 /**
307  * Force a redraw of the entire _map_pixmap, including fetching the
308  * background maps from disk and redrawing the tracks on top of them.
309  */
310 void 
311 map_force_redraw()
312 {
313 guint new_x, new_y;
314
315 for (new_y = 0; new_y < BUF_HEIGHT_TILES; ++new_y)
316         for (new_x = 0; new_x < BUF_WIDTH_TILES; ++new_x) {
317                 map_render_tile(_base_tilex + new_x,
318                                 _base_tiley + new_y,
319                                 new_x * TILE_SIZE_PIXELS,
320                                 new_y * TILE_SIZE_PIXELS, FALSE);
321         }
322 map_render_data();
323 MACRO_QUEUE_DRAW_AREA();
324 }
325
326 /**
327  * Set the current zoom level.  If the given zoom level is the same as the
328  * current zoom level, or if the new zoom is invalid
329  * (not MIN_ZOOM <= new_zoom < MAX_ZOOM), then this method does nothing.
330  */
331 void 
332 map_set_zoom(guint new_zoom)
333 {
334 /* Note that, since new_zoom is a guint and MIN_ZOOM is 0, this if
335  * condition also checks for new_zoom >= MIN_ZOOM. */
336 if (new_zoom > (MAX_ZOOM - 1))
337         return;
338 if (new_zoom == _zoom)
339         return;
340
341 _zoom = new_zoom / _curr_repo->view_zoom_steps * _curr_repo->view_zoom_steps;
342 _world_size_tiles = unit2tile(WORLD_SIZE_UNITS);
343
344 /* If we're leading, update the center to reflect new zoom level. */
345 MACRO_RECALC_CENTER(_center.unitx, _center.unity);
346
347 /* Update center bounds to reflect new zoom level. */
348 _min_center.unitx = pixel2unit(grid2pixel(_screen_grids_halfwidth));
349 _min_center.unity = pixel2unit(grid2pixel(_screen_grids_halfheight));
350 _max_center.unitx = WORLD_SIZE_UNITS - grid2unit(_screen_grids_halfwidth) - 1;
351 _max_center.unity = WORLD_SIZE_UNITS - grid2unit(_screen_grids_halfheight) - 1;
352
353 BOUND(_center.unitx, _min_center.unitx, _max_center.unitx);
354 BOUND(_center.unity, _min_center.unity, _max_center.unity);
355
356 _base_tilex = grid2tile((gint) pixel2grid((gint) unit2pixel((gint) _center.unitx))
357                         - (gint) _screen_grids_halfwidth);
358 _base_tiley = grid2tile(pixel2grid(unit2pixel(_center.unity))
359                         - _screen_grids_halfheight);
360
361 /* New zoom level, so we can't reuse the old buffer's pixels. */
362 /* Update state variables. */
363 MACRO_RECALC_OFFSET();
364 MACRO_RECALC_FOCUS_BASE();
365 MACRO_RECALC_FOCUS_SIZE();
366
367 map_set_mark();
368 map_force_redraw();
369 }
370
371 /**
372  * Center the view on the given unitx/unity.
373  */
374 void 
375 map_center_unit(guint new_center_unitx, guint new_center_unity)
376 {
377 gint new_base_tilex, new_base_tiley;
378 guint new_x, new_y;
379 guint j, k, base_new_x, base_old_x, old_x, old_y, iox, ioy;
380
381 /* Assure that _center.unitx/y are bounded. */
382 BOUND(new_center_unitx, _min_center.unitx, _max_center.unitx);
383 BOUND(new_center_unity, _min_center.unity, _max_center.unity);
384
385 _center.unitx = new_center_unitx;
386 _center.unity = new_center_unity;
387
388 new_base_tilex = grid2tile((gint) pixel2grid((gint)unit2pixel((gint) _center.unitx))
389                            - (gint)_screen_grids_halfwidth);
390 new_base_tiley = grid2tile(pixel2grid(unit2pixel(_center.unity))
391                            - _screen_grids_halfheight);
392
393 /* Same zoom level, so it's likely that we can reuse some of the old
394  * buffer's pixels. */
395
396 if (new_base_tilex != _base_tilex || new_base_tiley != _base_tiley) {
397         /* If copying from old parts to new parts, we need to make sure we
398          * don't overwrite the old parts when copying, so set up new_x,
399          * new_y, old_x, old_y, iox, and ioy with that in mind. */
400         if (new_base_tiley < _base_tiley) {
401                 /* New is lower than old - start at bottom and go up. */
402                 new_y = BUF_HEIGHT_TILES - 1;
403                 ioy = -1;
404         } else {
405                 /* New is higher than old - start at top and go down. */
406                 new_y = 0;
407                 ioy = 1;
408         }
409         if (new_base_tilex < _base_tilex) {
410                 /* New is righter than old - start at right and go left. */
411                 base_new_x = BUF_WIDTH_TILES - 1;
412                 iox = -1;
413         } else {
414                 /* New is lefter than old - start at left and go right. */
415                 base_new_x = 0;
416                 iox = 1;
417         }
418
419         /* Iterate over the y tile values. */
420         old_y = new_y + new_base_tiley - _base_tiley;
421         base_old_x = base_new_x + new_base_tilex - _base_tilex;
422         _base_tilex = new_base_tilex;
423         _base_tiley = new_base_tiley;
424         for (j = 0; j < BUF_HEIGHT_TILES; ++j, new_y += ioy, old_y += ioy) {
425                 new_x = base_new_x;
426                 old_x = base_old_x;
427                 /* Iterate over the x tile values. */
428                 for (k = 0; k < BUF_WIDTH_TILES;
429                      ++k, new_x += iox, old_x += iox) {
430                         /* Can we get this grid block from the old buffer?. */
431                         if (old_x >= 0 && old_x < BUF_WIDTH_TILES
432                             && old_y >= 0 && old_y < BUF_HEIGHT_TILES) {
433                                 /* Copy from old buffer to new buffer. */
434                                 gdk_draw_drawable(_map_pixmap,
435                                                   _gc[COLORABLE_MARK],
436                                                   _map_pixmap,
437                                                   old_x * TILE_SIZE_PIXELS,
438                                                   old_y * TILE_SIZE_PIXELS,
439                                                   new_x * TILE_SIZE_PIXELS,
440                                                   new_y * TILE_SIZE_PIXELS,
441                                                   TILE_SIZE_PIXELS,
442                                                   TILE_SIZE_PIXELS);
443                         } else {
444                                 map_render_tile(new_base_tilex + new_x,
445                                                 new_base_tiley + new_y,
446                                                 new_x * TILE_SIZE_PIXELS,
447                                                 new_y * TILE_SIZE_PIXELS,
448                                                 FALSE);
449                         }
450                 }
451         }
452         map_render_data();
453 }
454
455 MACRO_RECALC_OFFSET();
456 MACRO_RECALC_FOCUS_BASE();
457
458 map_set_mark();
459 MACRO_QUEUE_DRAW_AREA();
460 }
461
462 /**
463  * Pan the view by the given number of units in the X and Y directions.
464  */
465 void 
466 map_pan(gint delta_unitx, gint delta_unity)
467 {
468 if (_center_mode > 0)
469         set_action_activate("autocenter_none", TRUE);
470
471 map_center_unit(_center.unitx + delta_unitx, _center.unity + delta_unity);
472 }
473
474 /**
475  * Initiate a move of the mark from the old location to the current
476  * location.  This function queues the draw area of the old mark (to force
477  * drawing of the background map), then updates the mark, then queus the
478  * draw area of the new mark.
479  */
480 void 
481 map_move_mark(void)
482 {
483 /* Just queue the old and new draw areas. */
484 gtk_widget_queue_draw_area(_map_widget,
485                    _mark_minx<0 ? 0 : _mark_minx,
486                    _mark_miny<0 ? 0 : _mark_miny, 
487                    _mark_width, _mark_height);
488 map_set_mark();
489 gtk_widget_queue_draw_area(_map_widget,
490                    _mark_minx<0 ? 0 : _mark_minx,
491                    _mark_miny<0 ? 0 : _mark_miny, 
492                    _mark_width, _mark_height);
493 }
494
495 gboolean
496 map_update_location_from_gps()
497 {
498 map_update_location(_pos.unitx, _pos.unity, FALSE);
499 return FALSE;
500 }
501
502 gboolean
503 map_update_location_from_center()
504 {
505 /* Force re-validation of place if user is clicking around */
506 map_loc.valid=FALSE;
507 map_update_location(_center.unitx, _center.unity, TRUE);
508 return FALSE;
509 }
510
511 /**
512  * Draw given pixbuf on map, centered on x,y
513  */
514 void
515 map_draw_pixbuf(guint unitx, guint unity, GdkPixbuf *p)
516 {
517 gint x,y;
518 x = unit2bufx(unitx);
519 y = unit2bufy(unity);
520
521 gdk_draw_pixbuf(_map_pixmap, _gc[COLORABLE_POI],
522         p, 0, 0,
523         x - gdk_pixbuf_get_width(p) / 2,
524         y - gdk_pixbuf_get_height(p) / 2,
525         -1, -1, GDK_RGB_DITHER_NONE, 0, 0);
526 }
527
528 /**
529  * Draw an icon on given Position.
530  * 
531  * XXX: don't hardcode as home.png !
532  */
533 void
534 map_draw_position_icon(Position *pos)
535 {
536 guint x,y;
537 GdkPixbuf *p;
538
539 latlon2unit(pos->lat, pos->lon, x, y);
540 p=gdk_pixbuf_new_from_file(DATADIR "/pixmaps/mapper/home.png", NULL);
541 if (p) {
542         map_draw_pixbuf(x,y,p);
543         g_object_unref(p);
544 }
545
546 }
547
548 /**
549  * Make sure the mark is up-to-date.  This function triggers a panning of
550  * the view if the mark is appropriately close to the edge of the view.
551  */
552 void
553 map_refresh_mark()
554 {
555 guint new_center_unitx;
556 guint new_center_unity;
557
558 MACRO_RECALC_CENTER(new_center_unitx, new_center_unity);
559
560 if ((new_center_unitx - _focus.unitx) < _focus_unitwidth
561     && (new_center_unity - _focus.unity) < _focus_unitheight)
562         /* We're not changing the view - just move the mark. */
563         map_move_mark();
564 else
565         map_center_unit(new_center_unitx, new_center_unity);
566
567 /* Draw speed info */
568 if (_speed_limit_on)
569         speed_limit();
570
571 if (_center_mode>0)
572         g_idle_add((GSourceFunc)map_update_location_from_gps, NULL);
573 }
574
575 /**
576  * Render a single track line to _map_pixmap.  If either point on the line
577  * is a break (defined as unity == 0), a circle is drawn at the other point.
578  * IT IS AN ERROR FOR BOTH POINTS TO INDICATE A BREAK.
579  */
580 void
581 map_render_segment(GdkGC * gc_norm, GdkGC * gc_alt,
582                    guint unitx1, guint unity1, guint unitx2, guint unity2)
583 {
584         vprintf("%s()\n", __PRETTY_FUNCTION__);
585
586         if (!unity1) {
587                 guint x2, y2;
588                 x2 = unit2bufx(unitx2);
589                 y2 = unit2bufy(unity2);
590                 /* Make sure this circle will be visible. */
591                 if ((x2 < BUF_WIDTH_PIXELS)
592                     && (y2 < BUF_HEIGHT_PIXELS))
593                         gdk_draw_arc(_map_pixmap, gc_alt, FALSE,        /* FALSE: not filled. */
594                                      x2 - _draw_width, y2 - _draw_width, 2 * _draw_width, 2 * _draw_width, 0,   /* start at 0 degrees. */
595                                      360 * 64);
596         } else if (!unity2) {
597                 guint x1, y1;
598                 x1 = unit2bufx(unitx1);
599                 y1 = unit2bufy(unity1);
600                 /* Make sure this circle will be visible. */
601                 if ((x1 < BUF_WIDTH_PIXELS)
602                     && ((unsigned)y1 < BUF_HEIGHT_PIXELS))
603                         gdk_draw_arc(_map_pixmap, gc_alt, FALSE,        /* FALSE: not filled. */
604                                      x1 - _draw_width, y1 - _draw_width, 2 * _draw_width, 2 * _draw_width, 0,   /* start at 0 degrees. */
605                                      360 * 64);
606         } else {
607                 gint x1, y1, x2, y2;
608                 x1 = unit2bufx(unitx1);
609                 y1 = unit2bufy(unity1);
610                 x2 = unit2bufx(unitx2);
611                 y2 = unit2bufy(unity2);
612                 /* Make sure this line could possibly be visible. */
613                 if (!((x1 > BUF_WIDTH_PIXELS && x2 > BUF_WIDTH_PIXELS)
614                       || (x1 < 0 && x2 < 0)
615                       || (y1 > BUF_HEIGHT_PIXELS && y2 > BUF_HEIGHT_PIXELS)
616                       || (y1 < 0 && y2 < 0)))
617                         gdk_draw_line(_map_pixmap, gc_norm, x1, y1, x2, y2);
618         }
619
620         vprintf("%s(): return\n", __PRETTY_FUNCTION__);
621 }
622
623 /**
624  * Render all track data onto the _map_pixmap.  Note that this does not
625  * clear the pixmap of previous track data (use map_force_redraw() for
626  * that), and also note that this method does not queue any redraws, so it
627  * is up to the caller to decide which part of the track really needs to be
628  * redrawn.
629  */
630 void 
631 map_render_path(Path * path, GdkGC ** gc)
632 {
633         Point *curr;
634         WayPoint *wcurr;
635         printf("%s()\n", __PRETTY_FUNCTION__);
636
637         /* gc is a pointer to the first GC to use (for plain points).  (gc + 1)
638          * is a pointer to the GC to use for waypoints, and (gc + 2) is a pointer
639          * to the GC to use for breaks. */
640
641         /* else there is a route to draw. */
642         for (curr = path->head, wcurr = path->whead; curr++ != path->tail;) {
643                 /* Draw the line from (curr - 1) to (curr). */
644                 map_render_segment(gc[0], gc[2],
645                                    curr[-1].unitx, curr[-1].unity, curr->unitx,
646                                    curr->unity);
647
648                 /* Now, check if curr is a waypoint. */
649                 if (wcurr && wcurr <= path->wtail && wcurr->point == curr) {
650                         guint x1 = unit2bufx(wcurr->point->unitx);
651                         guint y1 = unit2bufy(wcurr->point->unity);
652                         if ((x1 < BUF_WIDTH_PIXELS)
653                             && (y1 < BUF_HEIGHT_PIXELS)) {
654                                 gdk_draw_arc(_map_pixmap, gc[1], FALSE, /* FALSE: not filled. */
655                                              x1 - _draw_width, y1 - _draw_width, 2 * _draw_width, 2 * _draw_width, 0,   /* start at 0 degrees. */
656                                              360 * 64);
657                         }
658                         wcurr++;
659                 }
660         }
661
662         vprintf("%s(): return\n", __PRETTY_FUNCTION__);
663 }
664
665 void 
666 map_render_paths()
667 {
668         printf("%s()\n", __PRETTY_FUNCTION__);
669
670         if ((_show_tracks & ROUTES_MASK) && _route.head != _route.tail) {
671                 map_render_path(&_route, _gc + COLORABLE_ROUTE);
672
673                 /* Now, draw the next waypoint on top of all other waypoints. */
674                 if (_next_way) {
675                         guint x1 = unit2bufx(_next_way->point->unitx);
676                         guint y1 = unit2bufy(_next_way->point->unity);
677                         if ((x1 < BUF_WIDTH_PIXELS)
678                             && (y1 < BUF_HEIGHT_PIXELS)) {
679                                 /* Draw the next waypoint as a break. */
680                                 gdk_draw_arc(_map_pixmap, _gc[COLORABLE_ROUTE_BREAK], FALSE,    /* FALSE: not filled. */
681                                              x1 - _draw_width, y1 - _draw_width, 2 * _draw_width, 2 * _draw_width, 0,   /* start at 0 degrees. */
682                                              360 * 64);
683                         }
684                 }
685         }
686         if (_show_tracks & TRACKS_MASK)
687                 map_render_path(&_track, _gc + COLORABLE_TRACK);
688
689         vprintf("%s(): return\n", __PRETTY_FUNCTION__);
690 }
691
692 static 
693 gboolean map_follow_move(GtkWidget * widget, GdkEventMotion * event)
694 {
695         gint xx, yy;
696         GdkModifierType state;
697         guint unitx, unity;
698         guint cx, cy;
699
700         if (event->is_hint) {
701                 gdk_window_get_pointer(event->window, &xx, &yy, &state);
702                 state = event->state;
703         } else {
704                 xx = event->x;
705                 yy = event->y;
706                 state = event->state;
707         }
708
709         unitx = x2unit((gint) (xx - before[0]));
710         unity = y2unit((gint) (yy - before[1]));
711         cx = unit2x(_center.unitx);
712         cy = unit2y(_center.unity);
713
714         map_center_unit(x2unit((gint) (cx - (xx - before[0]))),
715                         y2unit((gint) (cy - (yy - before[1]))));
716
717         before[0] = xx;
718         before[1] = yy;
719         return FALSE;
720 }
721
722 gboolean 
723 map_key_zoom_timeout()
724 {
725         printf("%s()\n", __PRETTY_FUNCTION__);
726         if (_key_zoom_new < _zoom) {
727                 /* We're currently zooming in (_zoom is decreasing). */
728                 guint test = _key_zoom_new - _curr_repo->view_zoom_steps;
729                 if (test < MAX_ZOOM)
730                         _key_zoom_new = test;
731                 else
732                         return FALSE;
733         } else {
734                 /* We're currently zooming out (_zoom is increasing). */
735                 guint test = _key_zoom_new + _curr_repo->view_zoom_steps;
736                 if (test < MAX_ZOOM)
737                         _key_zoom_new = test;
738                 else
739                         return FALSE;
740         }
741
742         /* We can zoom more - tell them how much they're zooming. */
743         {
744                 gchar buffer[32];
745                 snprintf(buffer, sizeof(buffer), "%s %d", _("Zoom to Level"), _key_zoom_new);
746                 MACRO_BANNER_SHOW_INFO(_window, buffer);
747         }
748         vprintf("%s(): return\n", __PRETTY_FUNCTION__);
749         return TRUE;
750 }
751
752 void 
753 map_scale_draw(GdkEventExpose *event)
754 {
755         gdk_rectangle_intersect(&event->area, &_scale_rect, &event->area);
756
757         if (event->area.width && event->area.height) {
758                 gdk_draw_rectangle(_map_widget->window,
759                                    _map_widget->style->
760                                    bg_gc[GTK_WIDGET_STATE(_map_widget)],
761                                    TRUE, _scale_rect.x, _scale_rect.y,
762                                    _scale_rect.width,
763                                    _scale_rect.height);
764                 gdk_draw_rectangle(_map_widget->window,
765                                    _map_widget->style->
766                                    fg_gc[GTK_WIDGET_STATE(_map_widget)],
767                                    FALSE, _scale_rect.x, _scale_rect.y,
768                                    _scale_rect.width,
769                                    _scale_rect.height);
770
771                 /* Now calculate and draw the distance. */
772                 {
773                         gchar buffer[16];
774                         gdouble distance;
775                         gdouble lat1, lon1, lat2, lon2;
776                         gint width;
777
778                         unit2latlon(_center.unitx - pixel2unit(SCALE_WIDTH / 2 - 4),
779                                     _center.unity, lat1, lon1);
780                         unit2latlon(_center.unitx + pixel2unit(SCALE_WIDTH / 2 - 4),
781                                     _center.unity, lat2, lon2);
782                         distance = calculate_distance(lat1, lon1, lat2, lon2) * UNITS_CONVERT[_units];
783
784                         if (distance < 1.f)
785                                 snprintf(buffer, sizeof(buffer),
786                                          "%0.2f %s", distance,
787                                          UNITS_TEXT[_units]);
788                         else if (distance < 10.f)
789                                 snprintf(buffer, sizeof(buffer),
790                                          "%0.1f %s", distance,
791                                          UNITS_TEXT[_units]);
792                         else
793                                 snprintf(buffer, sizeof(buffer),
794                                          "%0.f %s", distance,
795                                          UNITS_TEXT[_units]);
796
797                         pango_layout_set_text(_scale_layout, buffer, -1);
798                         pango_layout_get_pixel_size(_scale_layout, &width, NULL);
799
800                         /* Draw the layout itself. */
801                         gdk_draw_layout(_map_widget->window,
802                                         _map_widget->style->
803                                         fg_gc[GTK_WIDGET_STATE
804                                               (_map_widget)],
805                                         _scale_rect.x +
806                                         (_scale_rect.width - width) / 2,
807                                         _scale_rect.y, _scale_layout);
808
809                         /* Draw little hashes on the ends. */
810                         gdk_draw_line(_map_widget->window,
811                                       _map_widget->style->
812                                       fg_gc[GTK_WIDGET_STATE
813                                             (_map_widget)],
814                                       _scale_rect.x + 4,
815                                       _scale_rect.y +
816                                       _scale_rect.height / 2 - 4,
817                                       _scale_rect.x + 4,
818                                       _scale_rect.y +
819                                       _scale_rect.height / 2 + 4);
820                         gdk_draw_line(_map_widget->window,
821                                       _map_widget->style->
822                                       fg_gc[GTK_WIDGET_STATE
823                                             (_map_widget)],
824                                       _scale_rect.x + 4,
825                                       _scale_rect.y +
826                                       _scale_rect.height / 2,
827                                       _scale_rect.x +
828                                       (_scale_rect.width - width) / 2 -
829                                       4,
830                                       _scale_rect.y +
831                                       _scale_rect.height / 2);
832                         gdk_draw_line(_map_widget->window,
833                                       _map_widget->style->
834                                       fg_gc[GTK_WIDGET_STATE
835                                             (_map_widget)],
836                                       _scale_rect.x +
837                                       _scale_rect.width - 4,
838                                       _scale_rect.y +
839                                       _scale_rect.height / 2 - 4,
840                                       _scale_rect.x +
841                                       _scale_rect.width - 4,
842                                       _scale_rect.y +
843                                       _scale_rect.height / 2 + 4);
844                         gdk_draw_line(_map_widget->window,
845                                       _map_widget->style->
846                                       fg_gc[GTK_WIDGET_STATE
847                                             (_map_widget)],
848                                       _scale_rect.x +
849                                       _scale_rect.width - 4,
850                                       _scale_rect.y +
851                                       _scale_rect.height / 2,
852                                       _scale_rect.x +
853                                       (_scale_rect.width + width) / 2 +
854                                       4,
855                                       _scale_rect.y +
856                                       _scale_rect.height / 2);
857                 }
858         }
859 }
860
861 gboolean 
862 map_cb_expose(GtkWidget * widget, GdkEventExpose * event)
863 {
864 g_printf("%s(%d, %d, %d, %d)\n", __PRETTY_FUNCTION__,
865        event->area.x, event->area.y,
866        event->area.width, event->area.height);
867
868 gdk_draw_drawable(GDK_DRAWABLE(_map_widget->window),
869                   _gc[COLORABLE_MARK],
870                   _map_pixmap,
871                   event->area.x + _offsetx, event->area.y + _offsety,
872                   event->area.x, event->area.y,
873                   event->area.width, event->area.height);
874 map_draw_mark();
875
876 /* Draw scale, if necessary. */
877 if (_show_scale)
878         map_scale_draw(event);
879
880 return TRUE;
881 }
882
883 int 
884 map_zoom(gint zdir)
885 {
886 gchar buffer[80];
887 gint nzoom;
888
889 nzoom = _zoom + zdir;
890
891 if ((nzoom > 0) && (nzoom < MAX_ZOOM - 1)) {
892         snprintf(buffer, sizeof(buffer), "%s %d", _("Zoom to Level"), nzoom);
893         MACRO_BANNER_SHOW_INFO(_window, buffer);
894         map_set_zoom(nzoom);
895 }
896
897 return nzoom;
898 }
899
900 static gboolean
901 map_autozoomer()
902 {
903 static gfloat z=5.0;
904 static gint last=5;
905 gint iz;
906
907 if (zoom_timeout_sid==0)
908         return FALSE;
909
910 z=(z+_gps.speed+1)/5;
911 if (z>5) z=5.0; else if (z<1) z=1.0;
912 iz=(gint)roundf(z);
913 #ifdef DEBUG
914 g_printf("Setting autozoom to: %f %d S:%f\n", z, iz, _gps.speed);
915 #endif
916 if (iz>last) 
917         iz=last+1; 
918 else if (iz<last) 
919         iz=last-1;
920 last=iz;
921 map_set_zoom(iz);
922
923 return TRUE;
924 }
925
926 void
927 map_set_autozoom(gboolean az)
928 {
929 if (az==TRUE) {
930         MACRO_BANNER_SHOW_INFO(_window, "Autozoom enabled");
931         zoom_timeout_sid=g_timeout_add(_gps.speed<5 ? 2000 : 5000, (GSourceFunc) map_autozoomer, NULL);
932         return;
933 } else {
934         if (zoom_timeout_sid) {
935                 g_source_remove(zoom_timeout_sid);
936                 zoom_timeout_sid=0;
937                 MACRO_BANNER_SHOW_INFO(_window, "Autozoom disabled");
938         }
939         return;
940 }
941
942 }
943
944 static void 
945 map_draw_route(gint x, gint y)
946 {
947 cmenu_route_add_way(x, y);
948 }
949
950 static void 
951 map_draw_track(gint x, gint y)
952 {
953 _pos.unitx = x2unit((gint) (x + 0.5));
954 _pos.unity = y2unit((gint) (y + 0.5));
955 unit2latlon(_pos.unitx, _pos.unity, _gps.lat, _gps.lon);
956 _gps.speed = 20.f;
957 integerize_data(&_gps, &_pos);
958 track_add(time(NULL), FALSE);
959 map_refresh_mark();
960 }
961
962 static void
963 map_set_place_information(osm_way *s, osm_place *mp, osm_place *sp)
964 {
965 gchar buffer[256];
966
967 if (!s && !mp && !sp) {
968         snprintf(buffer, sizeof(buffer), _("Unknown location"));
969 } else {
970         /* oh, fun */
971         snprintf(buffer, sizeof(buffer), "%s%s%s%s%s%s%s%s%s%s", 
972         s ? s->name ? s->name : _("unknown") : "?",
973         s ? s->ref ? ", " : "" : "",
974         s ? s->ref ? s->ref : "" : "",
975         s ? s->int_ref ? " (" : "" : "",
976         s ? s->int_ref ? s->int_ref : "" : "",
977         s ? s->int_ref ? ") " : "" : "",
978         (sp && sp->name) ? " in " : "",
979         (sp && sp->name) ? sp->name : "",
980         (mp && mp->name) ? " in " : "",
981         (mp && mp->name) ? mp->name : "");
982 }
983 gtk_label_set_label(GTK_LABEL(info_banner.location), buffer);
984 }
985
986 static void
987 map_update_destination(gdouble lat, gdouble lon)
988 {
989 if (_dest.valid) {
990         gchar buffer[32];
991         gdouble dt=calculate_distance(lat, lon, _dest.lat, _dest.lon);
992         gdouble dh=calculate_course(lat, lon, _dest.lat, _dest.lon);
993         snprintf(buffer, sizeof(buffer), "%.02f %s (%0.02f)", dt * UNITS_CONVERT[_units], UNITS_TEXT[_units], dh);
994         gtk_label_set_label(GTK_LABEL(info_banner.distance), buffer);
995 } else {
996         gtk_label_set_label(GTK_LABEL(info_banner.distance), "");
997 }
998 }
999
1000 static void 
1001 map_update_location(gint x, gint y, gboolean force)
1002 {
1003 gint ilat, ilon;
1004 gdouble lat,lon;
1005 static gboolean inp=FALSE;
1006
1007 /* We run the gtk mainloop in progress callback so we can be called again, we don't like that */
1008 if (inp==TRUE)
1009         return;
1010 inp=TRUE;
1011
1012 unit2latlon(x, y, lat, lon);
1013 ilat=lat2mp_int(lat);
1014 ilon=lon2mp_int(lon);
1015
1016 if (_gps.fix>1 && !force)
1017         osm_set_way_range_from_speed(_gps.speed);
1018 else
1019         osm_set_way_range(OSM_RANGE_WAY/4);
1020
1021 osm_progress_set_widget(_db, _progress_item);
1022 _map_location_known=osm_get_location_data(ilat, ilon, &map_loc);
1023 _map_location_dist=map_loc.street ? map_loc.street->dist : 900000.0;
1024 if (map_loc.valid)
1025         map_set_place_information(map_loc.street, map_loc.primary, map_loc.secondary);
1026 else
1027         map_set_place_information(NULL, NULL, NULL);
1028 osm_progress_set_widget(_db, NULL);
1029
1030 map_update_destination(lat, lon);
1031
1032 inp=FALSE;
1033 }
1034
1035 gboolean 
1036 map_cb_scroll_event(GtkWidget * widget, GdkEventScroll * event)
1037 {
1038 if (event->direction == GDK_SCROLL_UP) {
1039         map_center_unit(x2unit((gint) (event->x + 0.5)), y2unit((gint) (event->y + 0.5)));
1040         map_set_zoom(_zoom - 1);
1041 } else if (event->direction == GDK_SCROLL_DOWN) {
1042         map_center_unit(x2unit((gint) (event->x + 0.5)), y2unit((gint) (event->y + 0.5)));
1043         map_set_zoom(_zoom + 1);
1044 }
1045 return FALSE;
1046 }
1047
1048 gboolean 
1049 map_cb_button_press(GtkWidget * widget, GdkEventButton * event)
1050 {
1051         printf("%s()\n", __PRETTY_FUNCTION__);
1052
1053         _cmenu_position_x = event->x + 0.5;
1054         _cmenu_position_y = event->y + 0.5;
1055
1056         switch (event->button) {
1057         case 1:
1058                 if (event->type == GDK_2BUTTON_PRESS) {
1059                         map_set_zoom(_zoom - 1);
1060                         return FALSE;
1061                 }
1062                 if (event->type == GDK_3BUTTON_PRESS)
1063                         return FALSE;
1064                 break;
1065         case 2:
1066                 press[0] = event->x;
1067                 press[1] = event->y;
1068                 before[0] = press[0];
1069                 before[1] = press[1];
1070
1071                 _id = g_signal_connect(G_OBJECT(_map_widget),
1072                                      "motion_notify_event",
1073                                      G_CALLBACK(map_follow_move), NULL);
1074                 break;
1075         case 3:
1076 #ifndef WITH_HILDON
1077                 gtk_menu_popup(GTK_MENU(_menu_map), NULL, NULL, NULL, NULL,
1078                                event->button, gtk_get_current_event_time());
1079 #endif
1080                 break;
1081         }
1082
1083         /* Return FALSE to allow context menu to work. */
1084         vprintf("%s(): return FALSE\n", __PRETTY_FUNCTION__);
1085         return FALSE;
1086 }
1087
1088 gboolean 
1089 map_cb_button_release(GtkWidget * widget, GdkEventButton * event)
1090 {
1091 switch (event->button) {
1092         case 1:
1093                 if (_center_mode > 0)
1094                         set_action_activate("autocenter_none", TRUE);
1095
1096                 switch (map_mode) {
1097                 case MAP_MODE_DRAW_TRACK:
1098                         map_draw_track(event->x, event->y);
1099                 break;
1100                 case MAP_MODE_DRAW_ROUTE:
1101                         map_draw_route(event->x, event->y);
1102                 break;
1103                 case MAP_MODE_SET_ROUTE_FROM:
1104                 case MAP_MODE_SET_ROUTE_POINT:
1105                 case MAP_MODE_SET_ROUTE_TO:
1106                 break;
1107                 }
1108
1109 #if 0
1110                 ux = x2unit((gint) (event->x + 0.5));
1111                 uy = y2unit((gint) (event->y + 0.5));
1112                 map_update_location(ux, uy);
1113 #else
1114                 g_idle_add((GSourceFunc)map_update_location_from_center, NULL);
1115 #endif
1116
1117                 map_center_unit(x2unit((gint) (event->x + 0.5)),
1118                                 y2unit((gint) (event->y + 0.5)));
1119
1120                 break;
1121         case 2:
1122                 release[0] = event->x;
1123                 release[1] = event->y;
1124
1125                 g_signal_handler_disconnect(G_OBJECT(_map_widget), _id);
1126
1127                 press[0] = 0;
1128                 press[1] = 0;
1129                 release[0] = 0;
1130                 release[1] = 0;
1131                 before[0] = 0;
1132                 before[1] = 0;
1133                 break;
1134         case 3:
1135                 break;
1136 }
1137
1138 /* Return FALSE to avoid context menu (if it hasn't popped up already). */
1139 return FALSE;
1140 }