]> git.street.me.uk Git - andy/viking.git/blob - src/vikwindow.c
Add Nominatim search engine
[andy/viking.git] / src / vikwindow.c
1 /*
2  * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
3  *
4  * Copyright (C) 2003-2005, Evan Battaglia <gtoevan@gmx.net>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif
25
26 #include "viking.h"
27 #include "background.h"
28 #include "acquire.h"
29 #include "datasources.h"
30 #include "vikgoto.h"
31 #include "dems.h"
32 #include "mapcache.h"
33 #include "print.h"
34 #include "preferences.h"
35 #include "icons/icons.h"
36 #include "vikexttools.h"
37
38 #ifdef HAVE_STDLIB_H
39 #include <stdlib.h>
40 #endif
41 #ifdef HAVE_MATH_H
42 #include <math.h>
43 #endif
44 #ifdef HAVE_STRING_H
45 #include <string.h>
46 #endif
47 #include <ctype.h>
48 #include <glib.h>
49 #include <glib/gstdio.h>
50 #include <glib/gprintf.h>
51 #include <glib/gi18n.h>
52
53 #define VIKING_WINDOW_WIDTH      1000
54 #define VIKING_WINDOW_HEIGHT     800
55 #define DRAW_IMAGE_DEFAULT_WIDTH 1280
56 #define DRAW_IMAGE_DEFAULT_HEIGHT 1024
57 #define DRAW_IMAGE_DEFAULT_SAVE_AS_PNG TRUE
58
59 static void window_finalize ( GObject *gob );
60 static GObjectClass *parent_class;
61
62 static void window_init ( VikWindow *vw );
63 static void window_class_init ( VikWindowClass *klass );
64 static void window_set_filename ( VikWindow *vw, const gchar *filename );
65
66 static void draw_update ( VikWindow *vw );
67
68 static void newwindow_cb ( GtkAction *a, VikWindow *vw );
69
70 /* Drawing & stuff */
71
72 static gboolean delete_event( VikWindow *vw );
73
74 static gboolean key_press_event( VikWindow *vw, GdkEventKey *event, gpointer data );
75
76 static void window_configure_event ( VikWindow *vw );
77 static void draw_sync ( VikWindow *vw );
78 static void draw_redraw ( VikWindow *vw );
79 static void draw_scroll  ( VikWindow *vw, GdkEventScroll *event );
80 static void draw_click  ( VikWindow *vw, GdkEventButton *event );
81 static void draw_release ( VikWindow *vw, GdkEventButton *event );
82 static void draw_mouse_motion ( VikWindow *vw, GdkEventMotion *event );
83 static void draw_zoom_cb ( GtkAction *a, VikWindow *vw );
84 static void draw_goto_cb ( GtkAction *a, VikWindow *vw );
85
86 static void draw_status ();
87
88 /* End Drawing Functions */
89
90 static void menu_addlayer_cb ( GtkAction *a, VikWindow *vw );
91 static void menu_properties_cb ( GtkAction *a, VikWindow *vw );
92 static void menu_delete_layer_cb ( GtkAction *a, VikWindow *vw );
93
94 /* tool management */
95 typedef struct {
96   VikToolInterface ti;
97   gpointer state;
98   gint layer_type;
99 } toolbox_tool_t;
100 #define TOOL_LAYER_TYPE_NONE -1
101
102 typedef struct {
103   int                   active_tool;
104   int                   n_tools;
105   toolbox_tool_t        *tools;
106   VikWindow *vw;
107 } toolbox_tools_t;
108
109 static void menu_tool_cb ( GtkAction *old, GtkAction *a, VikWindow *vw );
110 static toolbox_tools_t* toolbox_create(VikWindow *vw);
111 static void toolbox_add_tool(toolbox_tools_t *vt, VikToolInterface *vti, gint layer_type );
112 static int toolbox_get_tool(toolbox_tools_t *vt, const gchar *tool_name);
113 static void toolbox_activate(toolbox_tools_t *vt, const gchar *tool_name);
114 static const GdkCursor *toolbox_get_cursor(toolbox_tools_t *vt, const gchar *tool_name);
115 static void toolbox_click (toolbox_tools_t *vt, GdkEventButton *event);
116 static void toolbox_move (toolbox_tools_t *vt, GdkEventMotion *event);
117 static void toolbox_release (toolbox_tools_t *vt, GdkEventButton *event);
118
119
120 /* ui creation */
121 static void window_create_ui( VikWindow *window );
122 static void register_vik_icons (GtkIconFactory *icon_factory);
123
124 /* i/o */
125 static void load_file ( GtkAction *a, VikWindow *vw );
126 static gboolean save_file_as ( GtkAction *a, VikWindow *vw );
127 static gboolean save_file ( GtkAction *a, VikWindow *vw );
128 static gboolean save_file_and_exit ( GtkAction *a, VikWindow *vw );
129 static gboolean window_save ( VikWindow *vw );
130
131 struct _VikWindow {
132   GtkWindow gtkwindow;
133   VikViewport *viking_vvp;
134   VikLayersPanel *viking_vlp;
135   VikStatusbar *viking_vs;
136
137   GtkToolbar *toolbar;
138
139   GtkItemFactory *item_factory;
140
141   /* tool management state */
142   guint current_tool;
143   toolbox_tools_t *vt;
144   guint16 tool_layer_id;
145   guint16 tool_tool_id;
146
147   GtkActionGroup *action_group;
148
149   gint pan_x, pan_y;
150
151   guint draw_image_width, draw_image_height;
152   gboolean draw_image_save_as_png;
153
154   gchar *filename;
155   gboolean modified;
156
157   GtkWidget *open_dia, *save_dia;
158   GtkWidget *save_img_dia, *save_img_dir_dia;
159
160   gboolean only_updating_coord_mode_ui; /* hack for a bug in GTK */
161   GtkUIManager *uim;
162
163   /* half-drawn update */
164   VikLayer *trigger;
165   VikCoord trigger_center;
166 };
167
168 enum {
169  TOOL_PAN = 0,
170  TOOL_ZOOM,
171  TOOL_RULER,
172  TOOL_LAYER,
173  NUMBER_OF_TOOLS
174 };
175
176 enum {
177   VW_NEWWINDOW_SIGNAL,
178   VW_OPENWINDOW_SIGNAL,
179   VW_LAST_SIGNAL
180 };
181
182 static guint window_signals[VW_LAST_SIGNAL] = { 0 };
183
184 static gchar *tool_names[NUMBER_OF_TOOLS] = { N_("Pan"), N_("Zoom"), N_("Ruler") };
185
186 GType vik_window_get_type (void)
187 {
188   static GType vw_type = 0;
189
190   if (!vw_type)
191   {
192     static const GTypeInfo vw_info = 
193     {
194       sizeof (VikWindowClass),
195       NULL, /* base_init */
196       NULL, /* base_finalize */
197       (GClassInitFunc) window_class_init, /* class_init */
198       NULL, /* class_finalize */
199       NULL, /* class_data */
200       sizeof (VikWindow),
201       0,
202       (GInstanceInitFunc) window_init,
203     };
204     vw_type = g_type_register_static ( GTK_TYPE_WINDOW, "VikWindow", &vw_info, 0 );
205   }
206
207   return vw_type;
208 }
209
210 VikViewport * vik_window_viewport(VikWindow *vw)
211 {
212   return(vw->viking_vvp);
213 }
214
215 void vik_window_selected_layer(VikWindow *vw, VikLayer *vl)
216 {
217   int i, j, tool_count;
218   VikLayerInterface *layer_interface;
219
220   if (!vw->action_group) return;
221
222   for (i=0; i<VIK_LAYER_NUM_TYPES; i++) {
223     GtkAction *action;
224     layer_interface = vik_layer_get_interface(i);
225     tool_count = layer_interface->tools_count;
226
227     for (j = 0; j < tool_count; j++) {
228       action = gtk_action_group_get_action(vw->action_group,
229             layer_interface->tools[j].name);
230       g_object_set(action, "sensitive", i == vl->type, NULL);
231     }
232   }
233 }
234
235 static void window_finalize ( GObject *gob )
236 {
237   VikWindow *vw = VIK_WINDOW(gob);
238   g_return_if_fail ( vw != NULL );
239
240   a_background_remove_status ( vw->viking_vs );
241
242   G_OBJECT_CLASS(parent_class)->finalize(gob);
243 }
244
245
246 static void window_class_init ( VikWindowClass *klass )
247 {
248   /* destructor */
249   GObjectClass *object_class;
250
251   window_signals[VW_NEWWINDOW_SIGNAL] = g_signal_new ( "newwindow", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (VikWindowClass, newwindow), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
252   window_signals[VW_OPENWINDOW_SIGNAL] = g_signal_new ( "openwindow", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (VikWindowClass, openwindow), NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1, G_TYPE_POINTER);
253
254   object_class = G_OBJECT_CLASS (klass);
255
256   object_class->finalize = window_finalize;
257
258   parent_class = g_type_class_peek_parent (klass);
259
260 }
261
262 static void window_init ( VikWindow *vw )
263 {
264   GtkWidget *main_vbox;
265   GtkWidget *hpaned;
266
267   vw->action_group = NULL;
268
269   vw->viking_vvp = vik_viewport_new();
270   vw->viking_vlp = vik_layers_panel_new();
271   vik_layers_panel_set_viewport ( vw->viking_vlp, vw->viking_vvp );
272   vw->viking_vs = vik_statusbar_new();
273
274   vw->vt = toolbox_create(vw);
275   window_create_ui(vw);
276   window_set_filename (vw, NULL);
277   
278   toolbox_activate(vw->vt, "Pan");
279
280   vw->filename = NULL;
281   vw->item_factory = NULL;
282
283   vw->modified = FALSE;
284   vw->only_updating_coord_mode_ui = FALSE;
285   
286   vw->pan_x = vw->pan_y = -1;
287   vw->draw_image_width = DRAW_IMAGE_DEFAULT_WIDTH;
288   vw->draw_image_height = DRAW_IMAGE_DEFAULT_HEIGHT;
289   vw->draw_image_save_as_png = DRAW_IMAGE_DEFAULT_SAVE_AS_PNG;
290
291   main_vbox = gtk_vbox_new(FALSE, 1);
292   gtk_container_add (GTK_CONTAINER (vw), main_vbox);
293
294   gtk_box_pack_start (GTK_BOX(main_vbox), gtk_ui_manager_get_widget (vw->uim, "/MainMenu"), FALSE, TRUE, 0);
295   gtk_box_pack_start (GTK_BOX(main_vbox), gtk_ui_manager_get_widget (vw->uim, "/MainToolbar"), FALSE, TRUE, 0);
296   gtk_toolbar_set_icon_size(GTK_TOOLBAR(gtk_ui_manager_get_widget (vw->uim, "/MainToolbar")), GTK_ICON_SIZE_SMALL_TOOLBAR);
297   gtk_toolbar_set_style (GTK_TOOLBAR(gtk_ui_manager_get_widget (vw->uim, "/MainToolbar")), GTK_TOOLBAR_ICONS);
298
299   vik_ext_tools_add_menu_items ( vw, vw->uim );
300
301   g_signal_connect (G_OBJECT (vw), "delete_event", G_CALLBACK (delete_event), NULL);
302
303   g_signal_connect_swapped (G_OBJECT(vw->viking_vvp), "expose_event", G_CALLBACK(draw_sync), vw);
304   g_signal_connect_swapped (G_OBJECT(vw->viking_vvp), "configure_event", G_CALLBACK(window_configure_event), vw);
305   gtk_widget_add_events ( GTK_WIDGET(vw->viking_vvp), GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_KEY_PRESS_MASK );
306   g_signal_connect_swapped (G_OBJECT(vw->viking_vvp), "scroll_event", G_CALLBACK(draw_scroll), vw);
307   g_signal_connect_swapped (G_OBJECT(vw->viking_vvp), "button_press_event", G_CALLBACK(draw_click), vw);
308   g_signal_connect_swapped (G_OBJECT(vw->viking_vvp), "button_release_event", G_CALLBACK(draw_release), vw);
309   g_signal_connect_swapped (G_OBJECT(vw->viking_vvp), "motion_notify_event", G_CALLBACK(draw_mouse_motion), vw);
310   g_signal_connect_swapped (G_OBJECT(vw->viking_vlp), "update", G_CALLBACK(draw_update), vw);
311
312   g_signal_connect_swapped (G_OBJECT (vw->viking_vvp), "key_press_event", G_CALLBACK (key_press_event), vw);
313
314   gtk_window_set_default_size ( GTK_WINDOW(vw), VIKING_WINDOW_WIDTH, VIKING_WINDOW_HEIGHT);
315
316   hpaned = gtk_hpaned_new ();
317   gtk_paned_pack1 ( GTK_PANED(hpaned), GTK_WIDGET (vw->viking_vlp), FALSE, FALSE );
318   gtk_paned_pack2 ( GTK_PANED(hpaned), GTK_WIDGET (vw->viking_vvp), TRUE, TRUE );
319
320   /* This packs the button into the window (a gtk container). */
321   gtk_box_pack_start (GTK_BOX(main_vbox), hpaned, TRUE, TRUE, 0);
322
323   gtk_box_pack_end (GTK_BOX(main_vbox), GTK_WIDGET(vw->viking_vs), FALSE, TRUE, 0);
324
325   a_background_add_status(vw->viking_vs);
326
327   vw->open_dia = NULL;
328   vw->save_dia = NULL;
329   vw->save_img_dia = NULL;
330   vw->save_img_dir_dia = NULL;
331 }
332
333 VikWindow *vik_window_new ()
334 {
335   return VIK_WINDOW ( g_object_new ( VIK_WINDOW_TYPE, NULL ) );
336 }
337
338 static gboolean key_press_event( VikWindow *vw, GdkEventKey *event, gpointer data )
339 {
340   VikLayer *vl = vik_layers_panel_get_selected ( vw->viking_vlp );
341   if (vl && vw->vt->active_tool != -1 && vw->vt->tools[vw->vt->active_tool].ti.key_press ) {
342     gint ltype = vw->vt->tools[vw->vt->active_tool].layer_type;
343     if ( vl && ltype == vl->type )
344       return vw->vt->tools[vw->vt->active_tool].ti.key_press(vl, event, vw->vt->tools[vw->vt->active_tool].state);
345   }
346   return FALSE; /* don't handle the keypress */
347 }
348
349 static gboolean delete_event( VikWindow *vw )
350 {
351 #ifdef VIKING_PROMPT_IF_MODIFIED
352   if ( vw->modified )
353 #else
354   if (0)
355 #endif
356   {
357     GtkDialog *dia;
358     dia = GTK_DIALOG ( gtk_message_dialog_new ( GTK_WINDOW(vw), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE,
359       _("Do you want to save the changes you made to the document \"%s\"?\n"
360         "\n"
361         "Your changes will be lost if you don't save them."),
362       vw->filename ? a_file_basename ( vw->filename ) : _("Untitled") ) );
363     gtk_dialog_add_buttons ( dia, _("Don't Save"), GTK_RESPONSE_NO, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_SAVE, GTK_RESPONSE_YES, NULL );
364     switch ( gtk_dialog_run ( dia ) )
365     {
366       case GTK_RESPONSE_NO: gtk_widget_destroy ( GTK_WIDGET(dia) ); return FALSE;
367       case GTK_RESPONSE_CANCEL: gtk_widget_destroy ( GTK_WIDGET(dia) ); return TRUE;
368       default: gtk_widget_destroy ( GTK_WIDGET(dia) ); return ! save_file(NULL, vw);
369     }
370   }
371   return FALSE;
372 }
373
374 /* Drawing stuff */
375 static void newwindow_cb ( GtkAction *a, VikWindow *vw )
376 {
377   g_signal_emit ( G_OBJECT(vw), window_signals[VW_NEWWINDOW_SIGNAL], 0 );
378 }
379
380 static void draw_update ( VikWindow *vw )
381 {
382   draw_redraw (vw);
383   draw_sync (vw);
384 }
385
386 static void draw_sync ( VikWindow *vw )
387 {
388   vik_viewport_sync(vw->viking_vvp);
389   draw_status ( vw );
390   /* other things may be necc here later. */
391 }
392
393 static void draw_status ( VikWindow *vw )
394 {
395   static gchar zoom_level[22];
396   g_snprintf ( zoom_level, 22, "%.3f/%.3f %s", vik_viewport_get_xmpp (vw->viking_vvp), vik_viewport_get_ympp(vw->viking_vvp), vik_viewport_get_coord_mode(vw->viking_vvp) == VIK_COORD_UTM ? _("mpp") : _("pixelfact") );
397   if ( vw->current_tool == TOOL_LAYER )
398     vik_statusbar_set_message ( vw->viking_vs, 0, vik_layer_get_interface(vw->tool_layer_id)->tools[vw->tool_tool_id].name );
399   else
400     vik_statusbar_set_message ( vw->viking_vs, 0, _(tool_names[vw->current_tool]) );
401
402   vik_statusbar_set_message ( vw->viking_vs, 2, zoom_level );
403 }
404
405 void vik_window_set_redraw_trigger(VikLayer *vl)
406 {
407   VikWindow *vw = VIK_WINDOW(VIK_GTK_WINDOW_FROM_LAYER(vl));
408   if (NULL != vw)
409     vw->trigger = vl;
410 }
411
412 static void window_configure_event ( VikWindow *vw )
413 {
414   static int first = 1;
415   draw_redraw ( vw );
416   if (first) {
417     // This is a hack to set the cursor corresponding to the first tool
418     // FIXME find the correct way to initialize both tool and its cursor
419     const GdkCursor *cursor = NULL;
420     first = 0;
421     cursor = toolbox_get_cursor(vw->vt, "Pan");
422     /* We set cursor, even if it is NULL: it resets to default */
423     gdk_window_set_cursor ( GTK_WIDGET(vw->viking_vvp)->window, cursor );
424   }
425 }
426
427 static void draw_redraw ( VikWindow *vw )
428 {
429   VikCoord old_center = vw->trigger_center;
430   vw->trigger_center = *(vik_viewport_get_center(vw->viking_vvp));
431   VikLayer *new_trigger = vw->trigger;
432   vw->trigger = NULL;
433   VikLayer *old_trigger = VIK_LAYER(vik_viewport_get_trigger(vw->viking_vvp));
434
435   if ( ! new_trigger )
436     ; /* do nothing -- have to redraw everything. */
437   else if ( (old_trigger != new_trigger) || !vik_coord_equals(&old_center, &vw->trigger_center) )
438     vik_viewport_set_trigger ( vw->viking_vvp, new_trigger ); /* todo: set to half_drawn mode if new trigger is above old */
439   else
440     vik_viewport_set_half_drawn ( vw->viking_vvp, TRUE );
441
442   /* actually draw */
443   vik_viewport_clear ( vw->viking_vvp);
444   vik_layers_panel_draw_all ( vw->viking_vlp );
445   vik_viewport_draw_scale ( vw->viking_vvp );
446   vik_viewport_draw_centermark ( vw->viking_vvp );
447
448   vik_viewport_set_half_drawn ( vw->viking_vvp, FALSE ); /* just in case. */
449 }
450
451 gboolean draw_buf_done = TRUE;
452
453 static gboolean draw_buf(gpointer data)
454 {
455   gpointer *pass_along = data;
456   gdk_threads_enter();
457   gdk_draw_drawable (pass_along[0], pass_along[1],
458                      pass_along[2], 0, 0, 0, 0, -1, -1);
459   draw_buf_done = TRUE;
460   gdk_threads_leave();
461   return FALSE;
462 }
463
464
465 /* Mouse event handlers ************************************************************************/
466
467 static void vik_window_pan_click (VikWindow *vw, GdkEventButton *event)
468 {
469   /* set panning origin */
470   vw->pan_x = (gint) event->x;
471   vw->pan_y = (gint) event->y;
472 }
473
474 static void draw_click (VikWindow *vw, GdkEventButton *event)
475 {
476   gtk_widget_grab_focus ( GTK_WIDGET(vw->viking_vvp) );
477
478   /* middle button pressed.  we reserve all middle button and scroll events
479    * for panning and zooming; tools only get left/right/movement 
480    */
481   if ( event->button == 2) {
482     vik_window_pan_click ( vw, event );
483   } 
484   else {
485     toolbox_click(vw->vt, event);
486   }
487 }
488
489 static void vik_window_pan_move (VikWindow *vw, GdkEventMotion *event)
490 {
491   if ( vw->pan_x != -1 ) {
492     vik_viewport_pan_sync ( vw->viking_vvp, event->x - vw->pan_x, event->y - vw->pan_y );
493   }
494 }
495
496 static void draw_mouse_motion (VikWindow *vw, GdkEventMotion *event)
497 {
498   static VikCoord coord;
499   static struct UTM utm;
500   static struct LatLon ll;
501   #define BUFFER_SIZE 50
502   static char pointer_buf[BUFFER_SIZE];
503   gchar *lat = NULL, *lon = NULL;
504   gint16 alt;
505   gdouble zoom;
506   VikDemInterpol interpol_method;
507
508   /* This is a hack, but work far the best, at least for single pointer systems.
509    * See http://bugzilla.gnome.org/show_bug.cgi?id=587714 for more. */
510   gint x, y;
511   gdk_window_get_pointer (event->window, &x, &y, NULL);
512   event->x = x;
513   event->y = y;
514
515   toolbox_move(vw->vt, event);
516
517   vik_viewport_screen_to_coord ( vw->viking_vvp, event->x, event->y, &coord );
518   vik_coord_to_utm ( &coord, &utm );
519   a_coords_utm_to_latlon ( &utm, &ll );
520   a_coords_latlon_to_string ( &ll, &lat, &lon );
521   /* Change interpolate method according to scale */
522   zoom = vik_viewport_get_zoom(vw->viking_vvp);
523   if (zoom > 2.0)
524     interpol_method = VIK_DEM_INTERPOL_NONE;
525   else if (zoom >= 1.0)
526     interpol_method = VIK_DEM_INTERPOL_SIMPLE;
527   else
528     interpol_method = VIK_DEM_INTERPOL_BEST;
529   if ((alt = a_dems_get_elev_by_coord(&coord, interpol_method)) != VIK_DEM_INVALID_ELEVATION)
530     g_snprintf ( pointer_buf, BUFFER_SIZE, _("%s %s %dm"), lat, lon, alt );
531   else
532     g_snprintf ( pointer_buf, BUFFER_SIZE, _("%s %s"), lat, lon );
533   g_free (lat);
534   lat = NULL;
535   g_free (lon);
536   lon = NULL;
537   vik_statusbar_set_message ( vw->viking_vs, 4, pointer_buf );
538
539   vik_window_pan_move ( vw, event );
540
541   /* This is recommended by the GTK+ documentation, but does not work properly.
542    * Use deprecated way until GTK+ gets a solution for correct motion hint handling:
543    * http://bugzilla.gnome.org/show_bug.cgi?id=587714
544   */
545   /* gdk_event_request_motions ( event ); */
546 }
547
548 static void vik_window_pan_release ( VikWindow *vw, GdkEventButton *event )
549 {
550   if ( ABS(vw->pan_x - event->x) <= 1 && ABS(vw->pan_y - event->y) <= 1 )
551     vik_viewport_set_center_screen ( vw->viking_vvp, vw->pan_x, vw->pan_y );
552   else
553      vik_viewport_set_center_screen ( vw->viking_vvp, vik_viewport_get_width(vw->viking_vvp)/2 - event->x + vw->pan_x,
554                                       vik_viewport_get_height(vw->viking_vvp)/2 - event->y + vw->pan_y );
555   draw_update ( vw );
556   vw->pan_x = vw->pan_y = -1;
557 }
558
559 static void draw_release ( VikWindow *vw, GdkEventButton *event )
560 {
561   gtk_widget_grab_focus ( GTK_WIDGET(vw->viking_vvp) );
562
563   if ( event->button == 2 ) {  /* move / pan */
564     vik_window_pan_release(vw, event);
565   }
566   else {
567     toolbox_release(vw->vt, event);
568   }
569 }
570
571 static void draw_scroll (VikWindow *vw, GdkEventScroll *event)
572 {
573   guint modifiers = event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK);
574   if ( modifiers == GDK_CONTROL_MASK ) {
575     /* control == pan up & down */
576     if ( event->direction == GDK_SCROLL_UP )
577       vik_viewport_set_center_screen ( vw->viking_vvp, vik_viewport_get_width(vw->viking_vvp)/2, vik_viewport_get_height(vw->viking_vvp)/3 );
578     else
579       vik_viewport_set_center_screen ( vw->viking_vvp, vik_viewport_get_width(vw->viking_vvp)/2, vik_viewport_get_height(vw->viking_vvp)*2/3 );
580   } else if ( modifiers == GDK_SHIFT_MASK ) {
581     /* shift == pan left & right */
582     if ( event->direction == GDK_SCROLL_UP )
583       vik_viewport_set_center_screen ( vw->viking_vvp, vik_viewport_get_width(vw->viking_vvp)/3, vik_viewport_get_height(vw->viking_vvp)/2 );
584     else
585       vik_viewport_set_center_screen ( vw->viking_vvp, vik_viewport_get_width(vw->viking_vvp)*2/3, vik_viewport_get_height(vw->viking_vvp)/2 );
586   } else if ( modifiers == (GDK_CONTROL_MASK | GDK_SHIFT_MASK) ) {
587     /* control+shift == make sure mouse is still over the same point on the map when we zoom */
588     VikCoord coord;
589     gint x, y;
590     gint center_x = vik_viewport_get_width ( vw->viking_vvp ) / 2;
591     gint center_y = vik_viewport_get_height ( vw->viking_vvp ) / 2;
592     vik_viewport_screen_to_coord ( vw->viking_vvp, event->x, event->y, &coord );
593     if ( event->direction == GDK_SCROLL_UP )
594       vik_viewport_zoom_in (vw->viking_vvp);
595     else
596       vik_viewport_zoom_out(vw->viking_vvp);
597     vik_viewport_coord_to_screen ( vw->viking_vvp, &coord, &x, &y );
598     vik_viewport_set_center_screen ( vw->viking_vvp, center_x + (x - event->x),
599                                      center_y + (y - event->y) );
600   } else {
601     if ( event->direction == GDK_SCROLL_UP )
602       vik_viewport_zoom_in (vw->viking_vvp);
603     else
604       vik_viewport_zoom_out (vw->viking_vvp);
605   }
606
607   draw_update(vw);
608 }
609
610
611
612 /********************************************************************************
613  ** Ruler tool code
614  ********************************************************************************/
615 static void draw_ruler(VikViewport *vvp, GdkDrawable *d, GdkGC *gc, gint x1, gint y1, gint x2, gint y2, gdouble distance)
616 {
617   PangoFontDescription *pfd;
618   PangoLayout *pl;
619   gchar str[128];
620   GdkGC *labgc = vik_viewport_new_gc ( vvp, "#cccccc", 1);
621   GdkGC *thickgc = gdk_gc_new(d);
622   
623   gdouble len = sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
624   gdouble dx = (x2-x1)/len*10; 
625   gdouble dy = (y2-y1)/len*10;
626   gdouble c = cos(15.0 * M_PI/180.0);
627   gdouble s = sin(15.0 * M_PI/180.0);
628   gdouble angle;
629   gdouble baseangle = 0;
630   gint i;
631
632   /* draw line with arrow ends */
633   {
634     gint tmp_x1=x1, tmp_y1=y1, tmp_x2=x2, tmp_y2=y2;
635     a_viewport_clip_line(&tmp_x1, &tmp_y1, &tmp_x2, &tmp_y2);
636     gdk_draw_line(d, gc, tmp_x1, tmp_y1, tmp_x2, tmp_y2);
637   }
638
639   a_viewport_clip_line(&x1, &y1, &x2, &y2);
640   gdk_draw_line(d, gc, x1, y1, x2, y2);
641
642   gdk_draw_line(d, gc, x1 - dy, y1 + dx, x1 + dy, y1 - dx);
643   gdk_draw_line(d, gc, x2 - dy, y2 + dx, x2 + dy, y2 - dx);
644   gdk_draw_line(d, gc, x2, y2, x2 - (dx * c + dy * s), y2 - (dy * c - dx * s));
645   gdk_draw_line(d, gc, x2, y2, x2 - (dx * c - dy * s), y2 - (dy * c + dx * s));
646   gdk_draw_line(d, gc, x1, y1, x1 + (dx * c + dy * s), y1 + (dy * c - dx * s));
647   gdk_draw_line(d, gc, x1, y1, x1 + (dx * c - dy * s), y1 + (dy * c + dx * s));
648
649   /* draw compass */
650 #define CR 80
651 #define CW 4
652   angle = atan2(dy, dx) + M_PI_2;
653
654   if ( vik_viewport_get_drawmode ( vvp ) == VIK_VIEWPORT_DRAWMODE_UTM) {
655     VikCoord test;
656     struct LatLon ll;
657     struct UTM u;
658     gint tx, ty;
659
660     vik_viewport_screen_to_coord ( vvp, x1, y1, &test );
661     vik_coord_to_latlon ( &test, &ll );
662     ll.lat += vik_viewport_get_ympp ( vvp ) * vik_viewport_get_height ( vvp ) / 11000.0; // about 11km per degree latitude
663     a_coords_latlon_to_utm ( &ll, &u );
664     vik_coord_load_from_utm ( &test, VIK_VIEWPORT_DRAWMODE_UTM, &u );
665     vik_viewport_coord_to_screen ( vvp, &test, &tx, &ty );
666
667     baseangle = M_PI - atan2(tx-x1, ty-y1);
668     angle -= baseangle;
669   }
670
671   if (angle<0) 
672     angle+=2*M_PI;
673   if (angle>2*M_PI)
674     angle-=2*M_PI;
675
676   {
677     GdkColor color;
678     gdk_gc_copy(thickgc, gc);
679     gdk_gc_set_line_attributes(thickgc, CW, GDK_LINE_SOLID, GDK_CAP_BUTT, GDK_JOIN_MITER);
680     gdk_color_parse("#2255cc", &color);
681     gdk_gc_set_rgb_fg_color(thickgc, &color);
682   }
683   gdk_draw_arc (d, thickgc, FALSE, x1-CR+CW/2, y1-CR+CW/2, 2*CR-CW, 2*CR-CW, (90 - baseangle*180/M_PI)*64, -angle*180/M_PI*64);
684
685
686   gdk_gc_copy(thickgc, gc);
687   gdk_gc_set_line_attributes(thickgc, 2, GDK_LINE_SOLID, GDK_CAP_BUTT, GDK_JOIN_MITER);
688   for (i=0; i<180; i++) {
689     c = cos(i*M_PI/90.0 + baseangle);
690     s = sin(i*M_PI/90.0 + baseangle);
691
692     if (i%5) {
693       gdk_draw_line (d, gc, x1 + CR*c, y1 + CR*s, x1 + (CR+CW)*c, y1 + (CR+CW)*s);
694     } else {
695       gdouble ticksize = 2*CW;
696       gdk_draw_line (d, thickgc, x1 + (CR-CW)*c, y1 + (CR-CW)*s, x1 + (CR+ticksize)*c, y1 + (CR+ticksize)*s);
697     }
698   }
699
700   gdk_draw_arc (d, gc, FALSE, x1-CR, y1-CR, 2*CR, 2*CR, 0, 64*360);
701   gdk_draw_arc (d, gc, FALSE, x1-CR-CW, y1-CR-CW, 2*(CR+CW), 2*(CR+CW), 0, 64*360);
702   gdk_draw_arc (d, gc, FALSE, x1-CR+CW, y1-CR+CW, 2*(CR-CW), 2*(CR-CW), 0, 64*360);
703   c = (CR+CW*2)*cos(baseangle);
704   s = (CR+CW*2)*sin(baseangle);
705   gdk_draw_line (d, gc, x1-c, y1-s, x1+c, y1+s);
706   gdk_draw_line (d, gc, x1+s, y1-c, x1-s, y1+c);
707
708   /* draw labels */
709 #define LABEL(x, y, w, h) { \
710     gdk_draw_rectangle(d, labgc, TRUE, (x)-2, (y)-1, (w)+4, (h)+1); \
711     gdk_draw_rectangle(d, gc, FALSE, (x)-2, (y)-1, (w)+4, (h)+1); \
712     gdk_draw_layout(d, gc, (x), (y), pl); } 
713   {
714     gint wd, hd, xd, yd;
715     gint wb, hb, xb, yb;
716
717     pl = gtk_widget_create_pango_layout (GTK_WIDGET(vvp), NULL);
718
719     pfd = pango_font_description_from_string ("Sans 8"); // FIXME: settable option? global variable?
720     pango_layout_set_font_description (pl, pfd);
721     pango_font_description_free (pfd);
722
723     pango_layout_set_text(pl, "N", -1);
724     gdk_draw_layout(d, gc, x1-5, y1-CR-3*CW-8, pl);
725
726     /* draw label with distance */
727     if (distance >= 1000 && distance < 100000) {
728       g_sprintf(str, "%3.2f km", distance/1000.0);
729     } else if (distance < 1000) {
730       g_sprintf(str, "%d m", (int)distance);
731     } else {
732       g_sprintf(str, "%d km", (int)distance/1000);
733     }
734     pango_layout_set_text(pl, str, -1);
735
736     pango_layout_get_pixel_size ( pl, &wd, &hd );
737     if (dy>0) {
738       xd = (x1+x2)/2 + dy;
739       yd = (y1+y2)/2 - hd/2 - dx;
740     } else {
741       xd = (x1+x2)/2 - dy;
742       yd = (y1+y2)/2 - hd/2 + dx;
743     }
744
745     if ( xd < -5 || yd < -5 || xd > vik_viewport_get_width(vvp)+5 || yd > vik_viewport_get_height(vvp)+5 ) {
746       xd = x2 + 10;
747       yd = y2 - 5;
748     }
749
750     LABEL(xd, yd, wd, hd);
751
752     /* draw label with bearing */
753     g_sprintf(str, "%3.1f°", angle*180.0/M_PI);
754     pango_layout_set_text(pl, str, -1);
755     pango_layout_get_pixel_size ( pl, &wb, &hb );
756     xb = x1 + CR*cos(angle-M_PI_2);
757     yb = y1 + CR*sin(angle-M_PI_2);
758
759     if ( xb < -5 || yb < -5 || xb > vik_viewport_get_width(vvp)+5 || yb > vik_viewport_get_height(vvp)+5 ) {
760       xb = x2 + 10;
761       yb = y2 + 10;
762     }
763
764     {
765       GdkRectangle r1 = {xd-2, yd-1, wd+4, hd+1}, r2 = {xb-2, yb-1, wb+4, hb+1};
766       if (gdk_rectangle_intersect(&r1, &r2, &r2)) {
767         xb = xd + wd + 5;
768       }
769     }
770     LABEL(xb, yb, wb, hb);
771   }
772 #undef LABEL
773
774   g_object_unref ( G_OBJECT ( pl ) );
775   g_object_unref ( G_OBJECT ( labgc ) );
776   g_object_unref ( G_OBJECT ( thickgc ) );
777 }
778
779 typedef struct {
780   VikWindow *vw;
781   VikViewport *vvp;
782   gboolean has_oldcoord;
783   VikCoord oldcoord;
784 } ruler_tool_state_t;
785
786 static gpointer ruler_create (VikWindow *vw, VikViewport *vvp) 
787 {
788   ruler_tool_state_t *s = g_new(ruler_tool_state_t, 1);
789   s->vw = vw;
790   s->vvp = vvp;
791   s->has_oldcoord = FALSE;
792   return s;
793 }
794
795 static void ruler_destroy (ruler_tool_state_t *s)
796 {
797   g_free(s);
798 }
799
800 static VikLayerToolFuncStatus ruler_click (VikLayer *vl, GdkEventButton *event, ruler_tool_state_t *s)
801 {
802   struct LatLon ll;
803   VikCoord coord;
804   gchar *temp;
805   if ( event->button == 1 ) {
806     gchar *lat=NULL, *lon=NULL;
807     vik_viewport_screen_to_coord ( s->vvp, (gint) event->x, (gint) event->y, &coord );
808     vik_coord_to_latlon ( &coord, &ll );
809     a_coords_latlon_to_string ( &ll, &lat, &lon );
810     if ( s->has_oldcoord ) {
811       temp = g_strdup_printf ( "%s %s DIFF %f meters", lat, lon, vik_coord_diff( &coord, &(s->oldcoord) ) );
812       s->has_oldcoord = FALSE;
813     }
814     else {
815       temp = g_strdup_printf ( "%s %s", lat, lon );
816       s->has_oldcoord = TRUE;
817     }
818
819     vik_statusbar_set_message ( s->vw->viking_vs, 3, temp );
820     g_free ( temp );
821
822     s->oldcoord = coord;
823   }
824   else {
825     vik_viewport_set_center_screen ( s->vvp, (gint) event->x, (gint) event->y );
826     draw_update ( s->vw );
827   }
828   return VIK_LAYER_TOOL_ACK;
829 }
830
831 static VikLayerToolFuncStatus ruler_move (VikLayer *vl, GdkEventMotion *event, ruler_tool_state_t *s)
832 {
833   VikViewport *vvp = s->vvp;
834   VikWindow *vw = s->vw;
835
836   struct LatLon ll;
837   VikCoord coord;
838   gchar *temp;
839
840   if ( s->has_oldcoord ) {
841     int oldx, oldy, w1, h1, w2, h2;
842     static GdkPixmap *buf = NULL;
843     gchar *lat=NULL, *lon=NULL;
844     w1 = vik_viewport_get_width(vvp); 
845     h1 = vik_viewport_get_height(vvp);
846     if (!buf) {
847       buf = gdk_pixmap_new ( GTK_WIDGET(vvp)->window, w1, h1, -1 );
848     }
849     gdk_drawable_get_size(buf, &w2, &h2);
850     if (w1 != w2 || h1 != h2) {
851       g_object_unref ( G_OBJECT ( buf ) );
852       buf = gdk_pixmap_new ( GTK_WIDGET(vvp)->window, w1, h1, -1 );
853     }
854
855     vik_viewport_screen_to_coord ( vvp, (gint) event->x, (gint) event->y, &coord );
856     vik_coord_to_latlon ( &coord, &ll );
857     vik_viewport_coord_to_screen ( vvp, &s->oldcoord, &oldx, &oldy );
858
859     gdk_draw_drawable (buf, GTK_WIDGET(vvp)->style->black_gc, 
860                        vik_viewport_get_pixmap(vvp), 0, 0, 0, 0, -1, -1);
861     draw_ruler(vvp, buf, GTK_WIDGET(vvp)->style->black_gc, oldx, oldy, event->x, event->y, vik_coord_diff( &coord, &(s->oldcoord)) );
862     if (draw_buf_done) {
863       static gpointer pass_along[3];
864       pass_along[0] = GTK_WIDGET(vvp)->window;
865       pass_along[1] = GTK_WIDGET(vvp)->style->black_gc;
866       pass_along[2] = buf;
867       g_idle_add_full (G_PRIORITY_HIGH_IDLE + 10, draw_buf, pass_along, NULL);
868       draw_buf_done = FALSE;
869     }
870     a_coords_latlon_to_string(&ll, &lat, &lon);
871     temp = g_strdup_printf ( "%s %s DIFF %f meters", lat, lon, vik_coord_diff( &coord, &(s->oldcoord) ) );
872     vik_statusbar_set_message ( vw->viking_vs, 3, temp );
873     g_free ( temp );
874   }
875   return VIK_LAYER_TOOL_ACK;
876 }
877
878 static VikLayerToolFuncStatus ruler_release (VikLayer *vl, GdkEventButton *event, ruler_tool_state_t *s)
879 {
880   return VIK_LAYER_TOOL_ACK;
881 }
882
883 static void ruler_deactivate (VikLayer *vl, ruler_tool_state_t *s)
884 {
885   draw_update ( s->vw );
886 }
887
888 static VikToolInterface ruler_tool = 
889   { "Ruler", 
890     (VikToolConstructorFunc) ruler_create,
891     (VikToolDestructorFunc) ruler_destroy,
892     (VikToolActivationFunc) NULL,
893     (VikToolActivationFunc) ruler_deactivate, 
894     (VikToolMouseFunc) ruler_click, 
895     (VikToolMouseMoveFunc) ruler_move, 
896     (VikToolMouseFunc) ruler_release,
897     NULL,
898     GDK_CURSOR_IS_PIXMAP,
899     &cursor_ruler_pixbuf };
900 /*** end ruler code ********************************************************/
901
902
903
904 /********************************************************************************
905  ** Zoom tool code
906  ********************************************************************************/
907 static gpointer zoomtool_create (VikWindow *vw, VikViewport *vvp)
908 {
909   return vw;
910 }
911
912 static VikLayerToolFuncStatus zoomtool_click (VikLayer *vl, GdkEventButton *event, VikWindow *vw)
913 {
914   vw->modified = TRUE;
915   vik_viewport_set_center_screen ( vw->viking_vvp, (gint) event->x, (gint) event->y );
916   if ( event->button == 1 )
917     vik_viewport_zoom_in (vw->viking_vvp);
918   else if ( event->button == 3 )
919     vik_viewport_zoom_out (vw->viking_vvp);
920   draw_update ( vw );
921   return VIK_LAYER_TOOL_ACK;
922 }
923
924 static VikLayerToolFuncStatus zoomtool_move (VikLayer *vl, GdkEventMotion *event, VikViewport *vvp)
925 {
926   return VIK_LAYER_TOOL_ACK;
927 }
928
929 static VikLayerToolFuncStatus zoomtool_release (VikLayer *vl, GdkEventButton *event, VikViewport *vvp)
930 {
931   return VIK_LAYER_TOOL_ACK;
932 }
933
934 static VikToolInterface zoom_tool = 
935   { "Zoom", 
936     (VikToolConstructorFunc) zoomtool_create,
937     (VikToolDestructorFunc) NULL,
938     (VikToolActivationFunc) NULL,
939     (VikToolActivationFunc) NULL,
940     (VikToolMouseFunc) zoomtool_click, 
941     (VikToolMouseMoveFunc) zoomtool_move,
942     (VikToolMouseFunc) zoomtool_release,
943     NULL,
944     GDK_CURSOR_IS_PIXMAP,
945     &cursor_zoom_pixbuf };
946 /*** end zoom code ********************************************************/
947
948 /********************************************************************************
949  ** Pan tool code
950  ********************************************************************************/
951 static gpointer pantool_create (VikWindow *vw, VikViewport *vvp)
952 {
953   return vw;
954 }
955
956 static VikLayerToolFuncStatus pantool_click (VikLayer *vl, GdkEventButton *event, VikWindow *vw)
957 {
958   vw->modified = TRUE;
959   if ( event->button == 1 )
960     vik_window_pan_click ( vw, event );
961   draw_update ( vw );
962   return VIK_LAYER_TOOL_ACK;
963 }
964
965 static VikLayerToolFuncStatus pantool_move (VikLayer *vl, GdkEventMotion *event, VikWindow *vw)
966 {
967   vik_window_pan_move ( vw, event );
968   return VIK_LAYER_TOOL_ACK;
969 }
970
971 static VikLayerToolFuncStatus pantool_release (VikLayer *vl, GdkEventButton *event, VikWindow *vw)
972 {
973   if ( event->button == 1 )
974     vik_window_pan_release ( vw, event );
975   return VIK_LAYER_TOOL_ACK;
976 }
977
978 static VikToolInterface pan_tool = 
979   { "Pan", 
980     (VikToolConstructorFunc) pantool_create,
981     (VikToolDestructorFunc) NULL,
982     (VikToolActivationFunc) NULL,
983     (VikToolActivationFunc) NULL,
984     (VikToolMouseFunc) pantool_click, 
985     (VikToolMouseMoveFunc) pantool_move,
986     (VikToolMouseFunc) pantool_release,
987     NULL,
988     GDK_FLEUR };
989 /*** end pan code ********************************************************/
990
991 static void draw_pan_cb ( GtkAction *a, VikWindow *vw )
992 {
993   if (!strcmp(gtk_action_get_name(a), "PanNorth")) {
994     vik_viewport_set_center_screen ( vw->viking_vvp, vik_viewport_get_width(vw->viking_vvp)/2, 0 );
995   } else if (!strcmp(gtk_action_get_name(a), "PanEast")) {
996     vik_viewport_set_center_screen ( vw->viking_vvp, vik_viewport_get_width(vw->viking_vvp), vik_viewport_get_height(vw->viking_vvp)/2 );
997   } else if (!strcmp(gtk_action_get_name(a), "PanSouth")) {
998     vik_viewport_set_center_screen ( vw->viking_vvp, vik_viewport_get_width(vw->viking_vvp)/2, vik_viewport_get_height(vw->viking_vvp) );
999   } else if (!strcmp(gtk_action_get_name(a), "PanWest")) {
1000     vik_viewport_set_center_screen ( vw->viking_vvp, 0, vik_viewport_get_height(vw->viking_vvp)/2 );
1001   }
1002   draw_update ( vw );
1003 }
1004
1005 static void full_screen_cb ( GtkAction *a, VikWindow *vw )
1006 {
1007   GtkWidget *check_box = gtk_ui_manager_get_widget ( vw->uim, "/ui/MainMenu/View/FullScreen" );
1008   g_assert(check_box);
1009   gboolean state = gtk_check_menu_item_get_active ( GTK_CHECK_MENU_ITEM(check_box));
1010   if ( state )
1011     gtk_window_fullscreen ( GTK_WINDOW(vw) );
1012   else
1013     gtk_window_unfullscreen ( GTK_WINDOW(vw) );
1014 }
1015
1016 static void draw_zoom_cb ( GtkAction *a, VikWindow *vw )
1017 {
1018   guint what = 128;
1019
1020   if (!strcmp(gtk_action_get_name(a), "ZoomIn")) {
1021     what = -3;
1022   } 
1023   else if (!strcmp(gtk_action_get_name(a), "ZoomOut")) {
1024     what = -4;
1025   }
1026   else if (!strcmp(gtk_action_get_name(a), "Zoom0.25")) {
1027     what = -2;
1028   }
1029   else if (!strcmp(gtk_action_get_name(a), "Zoom0.5")) {
1030     what = -1;
1031   }
1032   else {
1033     gchar *s = (gchar *)gtk_action_get_name(a);
1034     what = atoi(s+4);
1035   }
1036
1037   switch (what)
1038   {
1039     case -3: vik_viewport_zoom_in ( vw->viking_vvp ); break;
1040     case -4: vik_viewport_zoom_out ( vw->viking_vvp ); break;
1041     case -1: vik_viewport_set_zoom ( vw->viking_vvp, 0.5 ); break;
1042     case -2: vik_viewport_set_zoom ( vw->viking_vvp, 0.25 ); break;
1043     default: vik_viewport_set_zoom ( vw->viking_vvp, what );
1044   }
1045   draw_update ( vw );
1046 }
1047
1048 void draw_goto_cb ( GtkAction *a, VikWindow *vw )
1049 {
1050   VikCoord new_center;
1051
1052   if (!strcmp(gtk_action_get_name(a), "GotoLL")) {
1053     struct LatLon ll, llold;
1054     vik_coord_to_latlon ( vik_viewport_get_center ( vw->viking_vvp ), &llold );
1055     if ( a_dialog_goto_latlon ( GTK_WINDOW(vw), &ll, &llold ) )
1056       vik_coord_load_from_latlon ( &new_center, vik_viewport_get_coord_mode(vw->viking_vvp), &ll );
1057     else
1058       return;
1059   }
1060   else if (!strcmp(gtk_action_get_name(a), "GotoUTM")) {
1061     struct UTM utm, utmold;
1062     vik_coord_to_utm ( vik_viewport_get_center ( vw->viking_vvp ), &utmold );
1063     if ( a_dialog_goto_utm ( GTK_WINDOW(vw), &utm, &utmold ) )
1064       vik_coord_load_from_utm ( &new_center, vik_viewport_get_coord_mode(vw->viking_vvp), &utm );
1065     else
1066      return;
1067   }
1068   else {
1069     g_critical("Houston, we've had a problem.");
1070     return;
1071   }
1072
1073   vik_viewport_set_center_coord ( vw->viking_vvp, &new_center );
1074   draw_update ( vw );
1075 }
1076
1077 static void menu_addlayer_cb ( GtkAction *a, VikWindow *vw )
1078 {
1079   gint type;
1080   for ( type = 0; type < VIK_LAYER_NUM_TYPES; type++ ) {
1081     if (!strcmp(vik_layer_get_interface(type)->name, gtk_action_get_name(a))) {
1082       if ( vik_layers_panel_new_layer ( vw->viking_vlp, type ) ) {
1083         draw_update ( vw );
1084         vw->modified = TRUE;
1085       }
1086     }
1087   }
1088 }
1089
1090 static void menu_copy_layer_cb ( GtkAction *a, VikWindow *vw )
1091 {
1092   a_clipboard_copy_selected ( vw->viking_vlp );
1093 }
1094
1095 static void menu_cut_layer_cb ( GtkAction *a, VikWindow *vw )
1096 {
1097   a_clipboard_copy_selected ( vw->viking_vlp );
1098   menu_delete_layer_cb ( a, vw );
1099 }
1100
1101 static void menu_paste_layer_cb ( GtkAction *a, VikWindow *vw )
1102 {
1103   if ( a_clipboard_paste ( vw->viking_vlp ) )
1104   {
1105     draw_update ( vw );
1106     vw->modified = TRUE;
1107   }
1108 }
1109
1110 static void menu_properties_cb ( GtkAction *a, VikWindow *vw )
1111 {
1112   if ( ! vik_layers_panel_properties ( vw->viking_vlp ) )
1113     a_dialog_info_msg ( GTK_WINDOW(vw), _("You must select a layer to show its properties.") );
1114 }
1115
1116 static void help_about_cb ( GtkAction *a, VikWindow *vw )
1117 {
1118   a_dialog_about(GTK_WINDOW(vw));
1119 }
1120
1121 static void menu_delete_layer_cb ( GtkAction *a, VikWindow *vw )
1122 {
1123   if ( vik_layers_panel_get_selected ( vw->viking_vlp ) )
1124   {
1125     vik_layers_panel_delete_selected ( vw->viking_vlp );
1126     vw->modified = TRUE;
1127   }
1128   else
1129     a_dialog_info_msg ( GTK_WINDOW(vw), _("You must select a layer to delete.") );
1130 }
1131
1132 static void view_side_panel_cb ( GtkAction *a, VikWindow *vw )
1133 {
1134   GtkWidget *check_box = gtk_ui_manager_get_widget ( vw->uim, "/ui/MainMenu/View/ViewSidePanel" );
1135   g_assert(check_box);
1136   gboolean state = gtk_check_menu_item_get_active ( GTK_CHECK_MENU_ITEM(check_box));
1137   if ( state )
1138     gtk_widget_show(GTK_WIDGET(vw->viking_vlp));
1139   else
1140     gtk_widget_hide(GTK_WIDGET(vw->viking_vlp));
1141 }
1142
1143 /***************************************
1144  ** tool management routines
1145  **
1146  ***************************************/
1147
1148 static toolbox_tools_t* toolbox_create(VikWindow *vw)
1149 {
1150   toolbox_tools_t *vt = g_new(toolbox_tools_t, 1);
1151   vt->tools = NULL;
1152   vt->n_tools = 0;
1153   vt->active_tool = -1;
1154   vt->vw = vw;
1155   if (!vw->viking_vvp) {
1156     g_critical("no viewport found.");
1157     exit(1);
1158   }
1159   return vt;
1160 }
1161
1162 static void toolbox_add_tool(toolbox_tools_t *vt, VikToolInterface *vti, gint layer_type )
1163 {
1164   vt->tools = g_renew(toolbox_tool_t, vt->tools, vt->n_tools+1);
1165   vt->tools[vt->n_tools].ti = *vti;
1166   vt->tools[vt->n_tools].layer_type = layer_type;
1167   if (vti->create) {
1168     vt->tools[vt->n_tools].state = vti->create(vt->vw, vt->vw->viking_vvp);
1169   } 
1170   else {
1171     vt->tools[vt->n_tools].state = NULL;
1172   }
1173   vt->n_tools++;
1174 }
1175
1176 static int toolbox_get_tool(toolbox_tools_t *vt, const gchar *tool_name)
1177 {
1178   int i;
1179   for (i=0; i<vt->n_tools; i++) {
1180     if (!strcmp(tool_name, vt->tools[i].ti.name)) {
1181       break;
1182     }
1183   }
1184   return i;
1185 }
1186
1187 static void toolbox_activate(toolbox_tools_t *vt, const gchar *tool_name)
1188 {
1189   int tool = toolbox_get_tool(vt, tool_name);
1190   toolbox_tool_t *t = &vt->tools[tool];
1191   VikLayer *vl = vik_layers_panel_get_selected ( vt->vw->viking_vlp );
1192
1193   if (tool == vt->n_tools) {
1194     g_critical("trying to activate a non-existent tool...");
1195     exit(1);
1196   }
1197   /* is the tool already active? */
1198   if (vt->active_tool == tool) {
1199     return;
1200   }
1201
1202   if (vt->active_tool != -1) {
1203     if (vt->tools[vt->active_tool].ti.deactivate) {
1204       vt->tools[vt->active_tool].ti.deactivate(NULL, vt->tools[vt->active_tool].state);
1205     }
1206   }
1207   if (t->ti.activate) {
1208     t->ti.activate(vl, t->state);
1209   }
1210   vt->active_tool = tool;
1211 }
1212
1213 static const GdkCursor *toolbox_get_cursor(toolbox_tools_t *vt, const gchar *tool_name)
1214 {
1215   int tool = toolbox_get_tool(vt, tool_name);
1216   toolbox_tool_t *t = &vt->tools[tool];
1217   if (t->ti.cursor == NULL) {
1218     if (t->ti.cursor_type == GDK_CURSOR_IS_PIXMAP && t->ti.cursor_data != NULL) {
1219       GError *cursor_load_err = NULL;
1220       GdkPixbuf *cursor_pixbuf = gdk_pixbuf_from_pixdata (t->ti.cursor_data, FALSE, &cursor_load_err);
1221       /* TODO: settable offeset */
1222       t->ti.cursor = gdk_cursor_new_from_pixbuf ( gdk_display_get_default(), cursor_pixbuf, 3, 3 );
1223       g_object_unref ( G_OBJECT(cursor_pixbuf) );
1224     } else {
1225       t->ti.cursor = gdk_cursor_new ( t->ti.cursor_type );
1226     }
1227   }
1228   return t->ti.cursor;
1229 }
1230
1231 static void toolbox_click (toolbox_tools_t *vt, GdkEventButton *event)
1232 {
1233   VikLayer *vl = vik_layers_panel_get_selected ( vt->vw->viking_vlp );
1234   if (vt->active_tool != -1 && vt->tools[vt->active_tool].ti.click) {
1235     gint ltype = vt->tools[vt->active_tool].layer_type;
1236     if ( ltype == TOOL_LAYER_TYPE_NONE || (vl && ltype == vl->type) )
1237       vt->tools[vt->active_tool].ti.click(vl, event, vt->tools[vt->active_tool].state);
1238   }
1239 }
1240
1241 static void toolbox_move (toolbox_tools_t *vt, GdkEventMotion *event)
1242 {
1243   VikLayer *vl = vik_layers_panel_get_selected ( vt->vw->viking_vlp );
1244   if (vt->active_tool != -1 && vt->tools[vt->active_tool].ti.move) {
1245     gint ltype = vt->tools[vt->active_tool].layer_type;
1246     if ( ltype == TOOL_LAYER_TYPE_NONE || (vl && ltype == vl->type) )
1247       if ( VIK_LAYER_TOOL_ACK_GRAB_FOCUS == vt->tools[vt->active_tool].ti.move(vl, event, vt->tools[vt->active_tool].state) )
1248         gtk_widget_grab_focus ( GTK_WIDGET(vt->vw->viking_vvp) );
1249   }
1250 }
1251
1252 static void toolbox_release (toolbox_tools_t *vt, GdkEventButton *event)
1253 {
1254   VikLayer *vl = vik_layers_panel_get_selected ( vt->vw->viking_vlp );
1255   if (vt->active_tool != -1 && vt->tools[vt->active_tool].ti.release ) {
1256     gint ltype = vt->tools[vt->active_tool].layer_type;
1257     if ( ltype == TOOL_LAYER_TYPE_NONE || (vl && ltype == vl->type) )
1258       vt->tools[vt->active_tool].ti.release(vl, event, vt->tools[vt->active_tool].state);
1259   }
1260 }
1261 /** End tool management ************************************/
1262
1263 void vik_window_enable_layer_tool ( VikWindow *vw, gint layer_id, gint tool_id )
1264 {
1265   gtk_action_activate ( gtk_action_group_get_action ( vw->action_group, vik_layer_get_interface(layer_id)->tools[tool_id].name ) );
1266 }
1267
1268 /* this function gets called whenever a toolbar tool is clicked */
1269 static void menu_tool_cb ( GtkAction *old, GtkAction *a, VikWindow *vw )
1270 {
1271   /* White Magic, my friends ... White Magic... */
1272   int layer_id, tool_id;
1273   const GdkCursor *cursor = NULL;
1274
1275   toolbox_activate(vw->vt, gtk_action_get_name(a));
1276
1277   cursor = toolbox_get_cursor(vw->vt, gtk_action_get_name(a));
1278   /* We set cursor, even if it is NULL: it resets to default */
1279   gdk_window_set_cursor ( GTK_WIDGET(vw->viking_vvp)->window, cursor );
1280
1281   if (!strcmp(gtk_action_get_name(a), "Pan")) {
1282     vw->current_tool = TOOL_PAN;
1283   } 
1284   else if (!strcmp(gtk_action_get_name(a), "Zoom")) {
1285     vw->current_tool = TOOL_ZOOM;
1286   } 
1287   else if (!strcmp(gtk_action_get_name(a), "Ruler")) {
1288     vw->current_tool = TOOL_RULER;
1289   }
1290   else {
1291     /* TODO: only enable tools from active layer */
1292     for (layer_id=0; layer_id<VIK_LAYER_NUM_TYPES; layer_id++) {
1293       for ( tool_id = 0; tool_id < vik_layer_get_interface(layer_id)->tools_count; tool_id++ ) {
1294         if (!strcmp(vik_layer_get_interface(layer_id)->tools[tool_id].name, gtk_action_get_name(a))) {
1295            vw->current_tool = TOOL_LAYER;
1296            vw->tool_layer_id = layer_id;
1297            vw->tool_tool_id = tool_id;
1298         }
1299       }
1300     }
1301   }
1302   draw_status ( vw );
1303 }
1304
1305 static void window_set_filename ( VikWindow *vw, const gchar *filename )
1306 {
1307   gchar *title;
1308   const gchar *file;
1309   if ( vw->filename )
1310     g_free ( vw->filename );
1311   if ( filename == NULL )
1312   {
1313     vw->filename = NULL;
1314     file = _("Untitled");
1315   }
1316   else
1317   {
1318     vw->filename = g_strdup(filename);
1319     file = a_file_basename ( filename );
1320   }
1321   title = g_strdup_printf( "%s - Viking", file );
1322   gtk_window_set_title ( GTK_WINDOW(vw), title );
1323   g_free ( title );
1324 }
1325
1326 GtkWidget *vik_window_get_drawmode_button ( VikWindow *vw, VikViewportDrawMode mode )
1327 {
1328   GtkWidget *mode_button;
1329   gchar *buttonname;
1330   switch ( mode ) {
1331 #ifdef VIK_CONFIG_EXPEDIA
1332     case VIK_VIEWPORT_DRAWMODE_EXPEDIA: buttonname = "/ui/MainMenu/View/ModeExpedia"; break;
1333 #endif
1334     case VIK_VIEWPORT_DRAWMODE_MERCATOR: buttonname = "/ui/MainMenu/View/ModeMercator"; break;
1335     default: buttonname = "/ui/MainMenu/View/ModeUTM";
1336   }
1337   mode_button = gtk_ui_manager_get_widget ( vw->uim, buttonname );
1338   g_assert ( mode_button );
1339   return mode_button;
1340 }
1341
1342 static void on_activate_recent_item (GtkRecentChooser *chooser,
1343                                      VikWindow *self)
1344 {
1345   gchar *filename;
1346
1347   filename = gtk_recent_chooser_get_current_uri (chooser);
1348   if (filename != NULL)
1349   {
1350     GFile *file = g_file_new_for_uri ( filename );
1351     gchar *path = g_file_get_path ( file );
1352     g_object_unref ( file );
1353     if ( self->filename )
1354     {
1355       gchar *filenames[] = { path, NULL };
1356       g_signal_emit ( G_OBJECT(self), window_signals[VW_OPENWINDOW_SIGNAL], 0, filenames );
1357     }
1358     else
1359       vik_window_open_file ( self, filename, TRUE );
1360     g_free ( path );
1361   }
1362
1363   g_free (filename);
1364 }
1365
1366 static void setup_recent_files (VikWindow *self)
1367 {
1368   GtkRecentManager *manager;
1369   GtkRecentFilter *filter;
1370   GtkWidget *menu, *menu_item;
1371
1372   filter = gtk_recent_filter_new ();
1373   /* gtk_recent_filter_add_application (filter, g_get_application_name()); */
1374   gtk_recent_filter_add_group(filter, "viking");
1375
1376   manager = gtk_recent_manager_get_default ();
1377   menu = gtk_recent_chooser_menu_new_for_manager (manager);
1378   gtk_recent_chooser_set_sort_type (GTK_RECENT_CHOOSER (menu), GTK_RECENT_SORT_MRU);
1379   gtk_recent_chooser_add_filter (GTK_RECENT_CHOOSER (menu), filter);
1380
1381   menu_item = gtk_ui_manager_get_widget (self->uim, "/ui/MainMenu/File/OpenRecentFile");
1382   gtk_menu_item_set_submenu (GTK_MENU_ITEM (menu_item), menu);
1383
1384   g_signal_connect (G_OBJECT (menu), "item-activated",
1385                     G_CALLBACK (on_activate_recent_item), (gpointer) self);
1386 }
1387
1388 static void update_recently_used_document(const gchar *filename)
1389 {
1390   /* Update Recently Used Document framework */
1391   GtkRecentManager *manager = gtk_recent_manager_get_default();
1392   GtkRecentData *recent_data = g_slice_new (GtkRecentData);
1393   gchar *groups[] = {"viking", NULL};
1394   GFile *file = g_file_new_for_commandline_arg(filename);
1395   gchar *uri = g_file_get_uri(file);
1396   gchar *basename = g_path_get_basename(filename);
1397   g_object_unref(file);
1398   file = NULL;
1399
1400   recent_data->display_name   = basename;
1401   recent_data->description    = NULL;
1402   recent_data->mime_type      = "text/x-gps-data";
1403   recent_data->app_name       = (gchar *) g_get_application_name ();
1404   recent_data->app_exec       = g_strjoin (" ", g_get_prgname (), "%f", NULL);
1405   recent_data->groups         = groups;
1406   recent_data->is_private     = FALSE;
1407   if (!gtk_recent_manager_add_full (manager, uri, recent_data))
1408   {
1409     g_warning (_("Unable to add '%s' to the list of recently used documents"), uri);
1410   }
1411
1412   g_free (uri);
1413   g_free (basename);
1414   g_free (recent_data->app_exec);
1415   g_slice_free (GtkRecentData, recent_data);
1416 }
1417
1418 void vik_window_open_file ( VikWindow *vw, const gchar *filename, gboolean change_filename )
1419 {
1420   switch ( a_file_load ( vik_layers_panel_get_top_layer(vw->viking_vlp), vw->viking_vvp, filename ) )
1421   {
1422     case 0:
1423       a_dialog_error_msg ( GTK_WINDOW(vw), _("The file you requested could not be opened.") );
1424       break;
1425     case 1:
1426     {
1427       GtkWidget *mode_button;
1428       /* Update UI */
1429       if ( change_filename )
1430         window_set_filename ( vw, filename );
1431       mode_button = vik_window_get_drawmode_button ( vw, vik_viewport_get_drawmode ( vw->viking_vvp ) );
1432       vw->only_updating_coord_mode_ui = TRUE; /* if we don't set this, it will change the coord to UTM if we click Lat/Lon. I don't know why. */
1433       gtk_check_menu_item_set_active ( GTK_CHECK_MENU_ITEM(mode_button), TRUE );
1434       vw->only_updating_coord_mode_ui = FALSE;
1435
1436       vik_layers_panel_change_coord_mode ( vw->viking_vlp, vik_viewport_get_coord_mode ( vw->viking_vvp ) );
1437
1438       mode_button = gtk_ui_manager_get_widget ( vw->uim, "/ui/MainMenu/View/ShowScale" );
1439       g_assert ( mode_button );
1440       gtk_check_menu_item_set_active ( GTK_CHECK_MENU_ITEM(mode_button),vik_viewport_get_draw_scale(vw->viking_vvp) );
1441
1442       mode_button = gtk_ui_manager_get_widget ( vw->uim, "/ui/MainMenu/View/ShowCenterMark" );
1443       g_assert ( mode_button );
1444       gtk_check_menu_item_set_active ( GTK_CHECK_MENU_ITEM(mode_button),vik_viewport_get_draw_centermark(vw->viking_vvp) );
1445     }
1446     default:
1447       update_recently_used_document(filename);
1448       draw_update ( vw );
1449   }
1450 }
1451 static void load_file ( GtkAction *a, VikWindow *vw )
1452 {
1453   GSList *files = NULL;
1454   GSList *cur_file = NULL;
1455   gboolean newwindow;
1456   if (!strcmp(gtk_action_get_name(a), "Open")) {
1457     newwindow = TRUE;
1458   } 
1459   else if (!strcmp(gtk_action_get_name(a), "Append")) {
1460     newwindow = FALSE;
1461   } 
1462   else {
1463     g_critical("Houston, we've had a problem.");
1464     return;
1465   }
1466     
1467   if ( ! vw->open_dia )
1468   {
1469     vw->open_dia = gtk_file_chooser_dialog_new (_("Please select a GPS data file to open. "),
1470                                       GTK_WINDOW(vw),
1471                                       GTK_FILE_CHOOSER_ACTION_OPEN,
1472                                       GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
1473                                       GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
1474                                       NULL);
1475     gtk_file_chooser_set_select_multiple ( GTK_FILE_CHOOSER(vw->open_dia), TRUE );
1476     gtk_window_set_transient_for ( GTK_WINDOW(vw->open_dia), GTK_WINDOW(vw) );
1477     gtk_window_set_destroy_with_parent ( GTK_WINDOW(vw->open_dia), TRUE );
1478   }
1479   if ( gtk_dialog_run ( GTK_DIALOG(vw->open_dia) ) == GTK_RESPONSE_ACCEPT )
1480   {
1481     gtk_widget_hide ( vw->open_dia );
1482 #ifdef VIKING_PROMPT_IF_MODIFIED
1483     if ( (vw->modified || vw->filename) && newwindow )
1484 #else
1485     if ( vw->filename && newwindow )
1486 #endif
1487       g_signal_emit ( G_OBJECT(vw), window_signals[VW_OPENWINDOW_SIGNAL], 0, gtk_file_chooser_get_filenames (GTK_FILE_CHOOSER(vw->open_dia) ) );
1488     else {
1489       files = gtk_file_chooser_get_filenames (GTK_FILE_CHOOSER(vw->open_dia) );
1490       gboolean change_fn = newwindow && (g_slist_length(files)==1); /* only change fn if one file */
1491       
1492       cur_file = files;
1493       while ( cur_file ) {
1494         gchar *file_name = cur_file->data;
1495         vik_window_open_file ( vw, file_name, change_fn );
1496         g_free (file_name);
1497         cur_file = g_slist_next (cur_file);
1498       }
1499       g_slist_free (files);
1500     }
1501   }
1502   else
1503     gtk_widget_hide ( vw->open_dia );
1504 }
1505
1506 static gboolean save_file_as ( GtkAction *a, VikWindow *vw )
1507 {
1508   gboolean rv = FALSE;
1509   const gchar *fn;
1510   if ( ! vw->save_dia )
1511   {
1512     vw->save_dia = gtk_file_chooser_dialog_new (_("Save as Viking File."),
1513                                       GTK_WINDOW(vw),
1514                                       GTK_FILE_CHOOSER_ACTION_SAVE,
1515                                       GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
1516                                       GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
1517                                       NULL);
1518     gtk_window_set_transient_for ( GTK_WINDOW(vw->save_dia), GTK_WINDOW(vw) );
1519     gtk_window_set_destroy_with_parent ( GTK_WINDOW(vw->save_dia), TRUE );
1520   }
1521
1522   while ( gtk_dialog_run ( GTK_DIALOG(vw->save_dia) ) == GTK_RESPONSE_ACCEPT )
1523   {
1524     fn = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER(vw->save_dia) );
1525     if ( g_file_test ( fn, G_FILE_TEST_EXISTS ) == FALSE || a_dialog_overwrite ( GTK_WINDOW(vw->save_dia), _("The file \"%s\" exists, do you wish to overwrite it?"), a_file_basename ( fn ) ) )
1526     {
1527       window_set_filename ( vw, fn );
1528       rv = window_save ( vw );
1529       vw->modified = FALSE;
1530       break;
1531     }
1532   }
1533   gtk_widget_hide ( vw->save_dia );
1534   return rv;
1535 }
1536
1537 static gboolean window_save ( VikWindow *vw )
1538 {
1539   if ( a_file_save ( vik_layers_panel_get_top_layer ( vw->viking_vlp ), vw->viking_vvp, vw->filename ) )
1540   {
1541     update_recently_used_document ( vw->filename );
1542     return TRUE;
1543   }
1544   else
1545   {
1546     a_dialog_error_msg ( GTK_WINDOW(vw), _("The filename you requested could not be opened for writing.") );
1547     return FALSE;
1548   }
1549 }
1550
1551 static gboolean save_file ( GtkAction *a, VikWindow *vw )
1552 {
1553   if ( ! vw->filename )
1554     return save_file_as ( NULL, vw );
1555   else
1556   {
1557     vw->modified = FALSE;
1558     return window_save ( vw );
1559   }
1560 }
1561
1562 static void acquire_from_gps ( GtkAction *a, VikWindow *vw )
1563 {
1564   a_acquire(vw, vw->viking_vlp, vw->viking_vvp, &vik_datasource_gps_interface );
1565 }
1566
1567 static void acquire_from_google ( GtkAction *a, VikWindow *vw )
1568 {
1569   a_acquire(vw, vw->viking_vlp, vw->viking_vvp, &vik_datasource_google_interface );
1570 }
1571
1572 #ifdef VIK_CONFIG_GEOCACHES
1573 static void acquire_from_gc ( GtkAction *a, VikWindow *vw )
1574 {
1575   a_acquire(vw, vw->viking_vlp, vw->viking_vvp, &vik_datasource_gc_interface );
1576 }
1577 #endif
1578
1579 static void goto_address( GtkAction *a, VikWindow *vw)
1580 {
1581   a_vik_goto(vw, vw->viking_vlp, vw->viking_vvp);
1582 }
1583
1584 static void mapcache_flush_cb ( GtkAction *a, VikWindow *vw )
1585 {
1586   a_mapcache_flush();
1587 }
1588
1589 static void preferences_cb ( GtkAction *a, VikWindow *vw )
1590 {
1591   a_preferences_show_window ( GTK_WINDOW(vw) );
1592 }
1593
1594 static void clear_cb ( GtkAction *a, VikWindow *vw )
1595 {
1596   vik_layers_panel_clear ( vw->viking_vlp );
1597   window_set_filename ( vw, NULL );
1598   draw_update ( vw );
1599 }
1600
1601 static void window_close ( GtkAction *a, VikWindow *vw )
1602 {
1603   if ( ! delete_event ( vw ) )
1604     gtk_widget_destroy ( GTK_WIDGET(vw) );
1605 }
1606
1607 static gboolean save_file_and_exit ( GtkAction *a, VikWindow *vw )
1608 {
1609   if (save_file( NULL, vw)) {
1610     window_close( NULL, vw);
1611     return(TRUE);
1612   }
1613   else
1614     return(FALSE);
1615 }
1616
1617 static void zoom_to_cb ( GtkAction *a, VikWindow *vw )
1618 {
1619   gdouble xmpp = vik_viewport_get_xmpp ( vw->viking_vvp ), ympp = vik_viewport_get_ympp ( vw->viking_vvp );
1620   if ( a_dialog_custom_zoom ( GTK_WINDOW(vw), &xmpp, &ympp ) )
1621   {
1622     vik_viewport_set_xmpp ( vw->viking_vvp, xmpp );
1623     vik_viewport_set_ympp ( vw->viking_vvp, ympp );
1624     draw_update ( vw );
1625   }
1626 }
1627
1628 static void save_image_file ( VikWindow *vw, const gchar *fn, guint w, guint h, gdouble zoom, gboolean save_as_png )
1629 {
1630   /* more efficient way: stuff draws directly to pixbuf (fork viewport) */
1631   GdkPixbuf *pixbuf_to_save;
1632   gdouble old_xmpp, old_ympp;
1633   GError *error = NULL;
1634
1635   /* backup old zoom & set new */
1636   old_xmpp = vik_viewport_get_xmpp ( vw->viking_vvp );
1637   old_ympp = vik_viewport_get_ympp ( vw->viking_vvp );
1638   vik_viewport_set_zoom ( vw->viking_vvp, zoom );
1639
1640   /* reset width and height: */
1641   vik_viewport_configure_manually ( vw->viking_vvp, w, h );
1642
1643   /* draw all layers */
1644   draw_redraw ( vw );
1645
1646   /* save buffer as file. */
1647   pixbuf_to_save = gdk_pixbuf_get_from_drawable ( NULL, GDK_DRAWABLE(vik_viewport_get_pixmap ( vw->viking_vvp )), NULL, 0, 0, 0, 0, w, h);
1648   gdk_pixbuf_save ( pixbuf_to_save, fn, save_as_png ? "png" : "jpeg", &error, NULL );
1649   if (error)
1650   {
1651     g_warning("Unable to write to file %s: %s", fn, error->message );
1652     g_error_free (error);
1653   }
1654   g_object_unref ( G_OBJECT(pixbuf_to_save) );
1655
1656   /* pretend like nothing happened ;) */
1657   vik_viewport_set_xmpp ( vw->viking_vvp, old_xmpp );
1658   vik_viewport_set_ympp ( vw->viking_vvp, old_ympp );
1659   vik_viewport_configure ( vw->viking_vvp );
1660   draw_update ( vw );
1661 }
1662
1663 static void save_image_dir ( VikWindow *vw, const gchar *fn, guint w, guint h, gdouble zoom, gboolean save_as_png, guint tiles_w, guint tiles_h )
1664 {
1665   gulong size = sizeof(gchar) * (strlen(fn) + 15);
1666   gchar *name_of_file = g_malloc ( size );
1667   guint x = 1, y = 1;
1668   struct UTM utm_orig, utm;
1669
1670   /* *** copied from above *** */
1671   GdkPixbuf *pixbuf_to_save;
1672   gdouble old_xmpp, old_ympp;
1673   GError *error = NULL;
1674
1675   /* backup old zoom & set new */
1676   old_xmpp = vik_viewport_get_xmpp ( vw->viking_vvp );
1677   old_ympp = vik_viewport_get_ympp ( vw->viking_vvp );
1678   vik_viewport_set_zoom ( vw->viking_vvp, zoom );
1679
1680   /* reset width and height: do this only once for all images (same size) */
1681   vik_viewport_configure_manually ( vw->viking_vvp, w, h );
1682   /* *** end copy from above *** */
1683
1684   g_assert ( vik_viewport_get_coord_mode ( vw->viking_vvp ) == VIK_COORD_UTM );
1685
1686   g_mkdir(fn,0777);
1687
1688   utm_orig = *((const struct UTM *)vik_viewport_get_center ( vw->viking_vvp ));
1689
1690   for ( y = 1; y <= tiles_h; y++ )
1691   {
1692     for ( x = 1; x <= tiles_w; x++ )
1693     {
1694       g_snprintf ( name_of_file, size, "%s%cy%d-x%d.%s", fn, G_DIR_SEPARATOR, y, x, save_as_png ? "png" : "jpg" );
1695       utm = utm_orig;
1696       if ( tiles_w & 0x1 )
1697         utm.easting += ((gdouble)x - ceil(((gdouble)tiles_w)/2)) * (w*zoom);
1698       else
1699         utm.easting += ((gdouble)x - (((gdouble)tiles_w)+1)/2) * (w*zoom);
1700       if ( tiles_h & 0x1 ) /* odd */
1701         utm.northing -= ((gdouble)y - ceil(((gdouble)tiles_h)/2)) * (h*zoom);
1702       else /* even */
1703         utm.northing -= ((gdouble)y - (((gdouble)tiles_h)+1)/2) * (h*zoom);
1704
1705       /* move to correct place. */
1706       vik_viewport_set_center_utm ( vw->viking_vvp, &utm );
1707
1708       draw_redraw ( vw );
1709
1710       /* save buffer as file. */
1711       pixbuf_to_save = gdk_pixbuf_get_from_drawable ( NULL, GDK_DRAWABLE(vik_viewport_get_pixmap ( vw->viking_vvp )), NULL, 0, 0, 0, 0, w, h);
1712       gdk_pixbuf_save ( pixbuf_to_save, name_of_file, save_as_png ? "png" : "jpeg", &error, NULL );
1713       if (error)
1714       {
1715         g_warning("Unable to write to file %s: %s", name_of_file, error->message );
1716         g_error_free (error);
1717       }
1718
1719       g_object_unref ( G_OBJECT(pixbuf_to_save) );
1720     }
1721   }
1722
1723   vik_viewport_set_center_utm ( vw->viking_vvp, &utm_orig );
1724   vik_viewport_set_xmpp ( vw->viking_vvp, old_xmpp );
1725   vik_viewport_set_ympp ( vw->viking_vvp, old_ympp );
1726   vik_viewport_configure ( vw->viking_vvp );
1727   draw_update ( vw );
1728
1729   g_free ( name_of_file );
1730 }
1731
1732 static void draw_to_image_file_current_window_cb(GtkWidget* widget,GdkEventButton *event,gpointer *pass_along)
1733 {
1734   VikWindow *vw = VIK_WINDOW(pass_along[0]);
1735   GtkSpinButton *width_spin = GTK_SPIN_BUTTON(pass_along[1]), *height_spin = GTK_SPIN_BUTTON(pass_along[2]);
1736   GtkSpinButton *zoom_spin = GTK_SPIN_BUTTON(pass_along[3]);
1737   gdouble width_min, width_max, height_min, height_max;
1738   gint width, height;
1739
1740   gtk_spin_button_get_range ( width_spin, &width_min, &width_max );
1741   gtk_spin_button_get_range ( height_spin, &height_min, &height_max );
1742
1743   /* TODO: support for xzoom and yzoom values */
1744   width = vik_viewport_get_width ( vw->viking_vvp ) * vik_viewport_get_xmpp ( vw->viking_vvp ) / gtk_spin_button_get_value ( zoom_spin );
1745   height = vik_viewport_get_height ( vw->viking_vvp ) * vik_viewport_get_xmpp ( vw->viking_vvp ) / gtk_spin_button_get_value ( zoom_spin );
1746
1747   if ( width > width_max || width < width_min || height > height_max || height < height_min )
1748     a_dialog_info_msg ( GTK_WINDOW(vw), _("Viewable region outside allowable pixel size bounds for image. Clipping width/height values.") );
1749
1750   gtk_spin_button_set_value ( width_spin, width );
1751   gtk_spin_button_set_value ( height_spin, height );
1752 }
1753
1754 static void draw_to_image_file_total_area_cb (GtkSpinButton *spinbutton, gpointer *pass_along)
1755 {
1756   GtkSpinButton *width_spin = GTK_SPIN_BUTTON(pass_along[1]), *height_spin = GTK_SPIN_BUTTON(pass_along[2]);
1757   GtkSpinButton *zoom_spin = GTK_SPIN_BUTTON(pass_along[3]);
1758   gchar *label_text;
1759   gdouble w, h;
1760   w = gtk_spin_button_get_value(width_spin) * gtk_spin_button_get_value(zoom_spin);
1761   h = gtk_spin_button_get_value(height_spin) * gtk_spin_button_get_value(zoom_spin);
1762   if (pass_along[4]) /* save many images; find TOTAL area covered */
1763   {
1764     w *= gtk_spin_button_get_value(GTK_SPIN_BUTTON(pass_along[4]));
1765     h *= gtk_spin_button_get_value(GTK_SPIN_BUTTON(pass_along[5]));
1766   }
1767   label_text = g_strdup_printf ( _("Total area: %ldm x %ldm (%.3f sq. km)"), (glong)w, (glong)h, (w*h/1000000));
1768   gtk_label_set_text(GTK_LABEL(pass_along[6]), label_text);
1769   g_free ( label_text );
1770 }
1771
1772 static void draw_to_image_file ( VikWindow *vw, const gchar *fn, gboolean one_image_only )
1773 {
1774   /* todo: default for answers inside VikWindow or static (thruout instance) */
1775   GtkWidget *dialog = gtk_dialog_new_with_buttons ( _("Save to Image File"), GTK_WINDOW(vw),
1776                                                   GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
1777                                                   GTK_STOCK_CANCEL,
1778                                                   GTK_RESPONSE_REJECT,
1779                                                   GTK_STOCK_OK,
1780                                                   GTK_RESPONSE_ACCEPT,
1781                                                   NULL );
1782   GtkWidget *width_label, *width_spin, *height_label, *height_spin;
1783   GtkWidget *png_radio, *jpeg_radio;
1784   GtkWidget *current_window_button;
1785   gpointer current_window_pass_along[7];
1786   GtkWidget *zoom_label, *zoom_spin;
1787   GtkWidget *total_size_label;
1788
1789   /* only used if (!one_image_only) */
1790   GtkWidget *tiles_width_spin = NULL, *tiles_height_spin = NULL;
1791
1792
1793   width_label = gtk_label_new ( _("Width (pixels):") );
1794   width_spin = gtk_spin_button_new ( GTK_ADJUSTMENT(gtk_adjustment_new ( vw->draw_image_width, 10, 5000, 10, 100, 0 )), 10, 0 );
1795   height_label = gtk_label_new ( _("Height (pixels):") );
1796   height_spin = gtk_spin_button_new ( GTK_ADJUSTMENT(gtk_adjustment_new ( vw->draw_image_height, 10, 5000, 10, 100, 0 )), 10, 0 );
1797
1798   zoom_label = gtk_label_new ( _("Zoom (meters per pixel):") );
1799   /* TODO: separate xzoom and yzoom factors */
1800   zoom_spin = gtk_spin_button_new ( GTK_ADJUSTMENT(gtk_adjustment_new ( vik_viewport_get_xmpp(vw->viking_vvp), VIK_VIEWPORT_MIN_ZOOM, VIK_VIEWPORT_MAX_ZOOM/2.0, 1, 100, 3 )), 16, 3);
1801
1802   total_size_label = gtk_label_new ( NULL );
1803
1804   current_window_button = gtk_button_new_with_label ( _("Area in current viewable window") );
1805   current_window_pass_along [0] = vw;
1806   current_window_pass_along [1] = width_spin;
1807   current_window_pass_along [2] = height_spin;
1808   current_window_pass_along [3] = zoom_spin;
1809   current_window_pass_along [4] = NULL; /* used for one_image_only != 1 */
1810   current_window_pass_along [5] = NULL;
1811   current_window_pass_along [6] = total_size_label;
1812   g_signal_connect ( G_OBJECT(current_window_button), "button_press_event", G_CALLBACK(draw_to_image_file_current_window_cb), current_window_pass_along );
1813
1814   png_radio = gtk_radio_button_new_with_label ( NULL, _("Save as PNG") );
1815   jpeg_radio = gtk_radio_button_new_with_label_from_widget ( GTK_RADIO_BUTTON(png_radio), _("Save as JPEG") );
1816
1817   if ( ! vw->draw_image_save_as_png )
1818     gtk_toggle_button_set_active ( GTK_TOGGLE_BUTTON(jpeg_radio), TRUE );
1819
1820   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), width_label, FALSE, FALSE, 0);
1821   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), width_spin, FALSE, FALSE, 0);
1822   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), height_label, FALSE, FALSE, 0);
1823   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), height_spin, FALSE, FALSE, 0);
1824   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), current_window_button, FALSE, FALSE, 0);
1825   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), png_radio, FALSE, FALSE, 0);
1826   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), jpeg_radio, FALSE, FALSE, 0);
1827   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), zoom_label, FALSE, FALSE, 0);
1828   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), zoom_spin, FALSE, FALSE, 0);
1829
1830   if ( ! one_image_only )
1831   {
1832     GtkWidget *tiles_width_label, *tiles_height_label;
1833
1834
1835     tiles_width_label = gtk_label_new ( _("East-west image tiles:") );
1836     tiles_width_spin = gtk_spin_button_new ( GTK_ADJUSTMENT(gtk_adjustment_new ( 5, 1, 10, 1, 100, 0 )), 1, 0 );
1837     tiles_height_label = gtk_label_new ( _("North-south image tiles:") );
1838     tiles_height_spin = gtk_spin_button_new ( GTK_ADJUSTMENT(gtk_adjustment_new ( 5, 1, 10, 1, 100, 0 )), 1, 0 );
1839     gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), tiles_width_label, FALSE, FALSE, 0);
1840     gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), tiles_width_spin, FALSE, FALSE, 0);
1841     gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), tiles_height_label, FALSE, FALSE, 0);
1842     gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), tiles_height_spin, FALSE, FALSE, 0);
1843
1844     current_window_pass_along [4] = tiles_width_spin;
1845     current_window_pass_along [5] = tiles_height_spin;
1846     g_signal_connect ( G_OBJECT(tiles_width_spin), "value-changed", G_CALLBACK(draw_to_image_file_total_area_cb), current_window_pass_along );
1847     g_signal_connect ( G_OBJECT(tiles_height_spin), "value-changed", G_CALLBACK(draw_to_image_file_total_area_cb), current_window_pass_along );
1848   }
1849   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), total_size_label, FALSE, FALSE, 0);
1850   g_signal_connect ( G_OBJECT(width_spin), "value-changed", G_CALLBACK(draw_to_image_file_total_area_cb), current_window_pass_along );
1851   g_signal_connect ( G_OBJECT(height_spin), "value-changed", G_CALLBACK(draw_to_image_file_total_area_cb), current_window_pass_along );
1852   g_signal_connect ( G_OBJECT(zoom_spin), "value-changed", G_CALLBACK(draw_to_image_file_total_area_cb), current_window_pass_along );
1853
1854   draw_to_image_file_total_area_cb ( NULL, current_window_pass_along ); /* set correct size info now */
1855
1856   gtk_widget_show_all ( GTK_DIALOG(dialog)->vbox );
1857
1858   if ( gtk_dialog_run ( GTK_DIALOG(dialog) ) == GTK_RESPONSE_ACCEPT )
1859   {
1860     gtk_widget_hide ( GTK_WIDGET(dialog) );
1861     if ( one_image_only )
1862       save_image_file ( vw, fn, 
1863                       vw->draw_image_width = gtk_spin_button_get_value_as_int ( GTK_SPIN_BUTTON(width_spin) ),
1864                       vw->draw_image_height = gtk_spin_button_get_value_as_int ( GTK_SPIN_BUTTON(height_spin) ),
1865                       gtk_spin_button_get_value ( GTK_SPIN_BUTTON(zoom_spin) ), /* do not save this value, default is current zoom */
1866                       vw->draw_image_save_as_png = gtk_toggle_button_get_active ( GTK_TOGGLE_BUTTON(png_radio) ) );
1867     else {
1868       if ( vik_viewport_get_coord_mode(vw->viking_vvp) == VIK_COORD_UTM )
1869         save_image_dir ( vw, fn, 
1870                        vw->draw_image_width = gtk_spin_button_get_value_as_int ( GTK_SPIN_BUTTON(width_spin) ),
1871                        vw->draw_image_height = gtk_spin_button_get_value_as_int ( GTK_SPIN_BUTTON(height_spin) ),
1872                        gtk_spin_button_get_value ( GTK_SPIN_BUTTON(zoom_spin) ), /* do not save this value, default is current zoom */
1873                        vw->draw_image_save_as_png = gtk_toggle_button_get_active ( GTK_TOGGLE_BUTTON(png_radio) ),
1874                        gtk_spin_button_get_value ( GTK_SPIN_BUTTON(tiles_width_spin) ),
1875                        gtk_spin_button_get_value ( GTK_SPIN_BUTTON(tiles_height_spin) ) );
1876       else
1877         a_dialog_error_msg ( GTK_WINDOW(vw), _("You must be in UTM mode to use this feature") );
1878     }
1879   }
1880   gtk_widget_destroy ( GTK_WIDGET(dialog) );
1881 }
1882
1883
1884 static void draw_to_image_file_cb ( GtkAction *a, VikWindow *vw )
1885 {
1886   const gchar *fn;
1887   if (!vw->save_img_dia) {
1888     vw->save_img_dia = gtk_file_chooser_dialog_new (_("Save Image"),
1889                                       GTK_WINDOW(vw),
1890                                       GTK_FILE_CHOOSER_ACTION_SAVE,
1891                                       GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
1892                                       GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
1893                                       NULL);
1894     gtk_window_set_transient_for ( GTK_WINDOW(vw->save_img_dia), GTK_WINDOW(vw) );
1895     gtk_window_set_destroy_with_parent ( GTK_WINDOW(vw->save_img_dia), TRUE );
1896   }
1897
1898   while ( gtk_dialog_run ( GTK_DIALOG(vw->save_img_dia) ) == GTK_RESPONSE_ACCEPT )
1899   {
1900     fn = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER(vw->save_img_dia) );
1901     if ( g_file_test ( fn, G_FILE_TEST_EXISTS ) == FALSE || a_dialog_overwrite ( GTK_WINDOW(vw->save_img_dia), _("The file \"%s\" exists, do you wish to overwrite it?"), a_file_basename ( fn ) ) )
1902     {
1903       draw_to_image_file ( vw, fn, TRUE );
1904       break;
1905     }
1906   }
1907   gtk_widget_hide ( vw->save_img_dia );
1908 }
1909
1910 static void draw_to_image_dir_cb ( GtkAction *a, VikWindow *vw )
1911 {
1912   gchar *fn = NULL;
1913   
1914   if (!vw->save_img_dir_dia) {
1915     vw->save_img_dir_dia = gtk_file_chooser_dialog_new (_("Choose a directory to hold images"),
1916                                       GTK_WINDOW(vw),
1917                                       GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER,
1918                                       GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
1919                                       GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,
1920                                       NULL);
1921     gtk_window_set_transient_for ( GTK_WINDOW(vw->save_img_dir_dia), GTK_WINDOW(vw) );
1922     gtk_window_set_destroy_with_parent ( GTK_WINDOW(vw->save_img_dir_dia), TRUE );
1923   }
1924   
1925   while ( gtk_dialog_run ( GTK_DIALOG(vw->save_img_dir_dia) ) == GTK_RESPONSE_ACCEPT )
1926   {
1927     fn = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER(vw->save_img_dir_dia) );
1928     if ( fn )
1929     {
1930       draw_to_image_file ( vw, fn, FALSE );
1931       g_free(fn);
1932       fn = NULL;
1933       break;
1934     }
1935   }
1936   gtk_widget_hide ( vw->save_img_dir_dia );
1937 }
1938
1939 #if GTK_CHECK_VERSION(2,10,0)
1940 static void print_cb ( GtkAction *a, VikWindow *vw )
1941 {
1942   a_print(vw, vw->viking_vvp);
1943 }
1944 #endif
1945
1946 /* really a misnomer: changes coord mode (actual coordinates) AND/OR draw mode (viewport only) */
1947 static void window_change_coord_mode_cb ( GtkAction *old_a, GtkAction *a, VikWindow *vw )
1948 {
1949   VikViewportDrawMode drawmode;
1950   if (!strcmp(gtk_action_get_name(a), "ModeUTM")) {
1951     drawmode = VIK_VIEWPORT_DRAWMODE_UTM;
1952   }
1953   else if (!strcmp(gtk_action_get_name(a), "ModeExpedia")) {
1954     drawmode = VIK_VIEWPORT_DRAWMODE_EXPEDIA;
1955   }
1956   else if (!strcmp(gtk_action_get_name(a), "ModeMercator")) {
1957     drawmode = VIK_VIEWPORT_DRAWMODE_MERCATOR;
1958   }
1959   else {
1960     g_critical("Houston, we've had a problem.");
1961     return;
1962   }
1963
1964   if ( !vw->only_updating_coord_mode_ui )
1965   {
1966     VikViewportDrawMode olddrawmode = vik_viewport_get_drawmode ( vw->viking_vvp );
1967     if ( olddrawmode != drawmode )
1968     {
1969       /* this takes care of coord mode too */
1970       vik_viewport_set_drawmode ( vw->viking_vvp, drawmode );
1971       if ( drawmode == VIK_VIEWPORT_DRAWMODE_UTM ) {
1972         vik_layers_panel_change_coord_mode ( vw->viking_vlp, VIK_COORD_UTM );
1973       } else if ( olddrawmode == VIK_VIEWPORT_DRAWMODE_UTM ) {
1974         vik_layers_panel_change_coord_mode ( vw->viking_vlp, VIK_COORD_LATLON );
1975       }
1976       draw_update ( vw );
1977     }
1978   }
1979 }
1980
1981 static void set_draw_scale ( GtkAction *a, VikWindow *vw )
1982 {
1983   GtkWidget *check_box = gtk_ui_manager_get_widget ( vw->uim, "/ui/MainMenu/View/ShowScale" );
1984   g_assert(check_box);
1985   gboolean state = gtk_check_menu_item_get_active ( GTK_CHECK_MENU_ITEM(check_box));
1986   vik_viewport_set_draw_scale ( vw->viking_vvp, state );
1987   draw_update ( vw );
1988 }
1989
1990 static void set_draw_centermark ( GtkAction *a, VikWindow *vw )
1991 {
1992   GtkWidget *check_box = gtk_ui_manager_get_widget ( vw->uim, "/ui/MainMenu/View/ShowCenterMark" );
1993   g_assert(check_box);
1994   gboolean state = gtk_check_menu_item_get_active ( GTK_CHECK_MENU_ITEM(check_box));
1995   vik_viewport_set_draw_centermark ( vw->viking_vvp, state );
1996   draw_update ( vw );
1997 }
1998
1999 static void set_bg_color ( GtkAction *a, VikWindow *vw )
2000 {
2001   GtkWidget *colorsd = gtk_color_selection_dialog_new ( _("Choose a background color") );
2002   GdkColor *color = vik_viewport_get_background_gdkcolor ( vw->viking_vvp );
2003   gtk_color_selection_set_previous_color ( GTK_COLOR_SELECTION(GTK_COLOR_SELECTION_DIALOG(colorsd)->colorsel), color );
2004   gtk_color_selection_set_current_color ( GTK_COLOR_SELECTION(GTK_COLOR_SELECTION_DIALOG(colorsd)->colorsel), color );
2005   if ( gtk_dialog_run ( GTK_DIALOG(colorsd) ) == GTK_RESPONSE_OK )
2006   {
2007     gtk_color_selection_get_current_color ( GTK_COLOR_SELECTION(GTK_COLOR_SELECTION_DIALOG(colorsd)->colorsel), color );
2008     vik_viewport_set_background_gdkcolor ( vw->viking_vvp, color );
2009     draw_update ( vw );
2010   }
2011   g_free ( color );
2012   gtk_widget_destroy ( colorsd );
2013 }
2014
2015
2016
2017 /***********************************************************************************************
2018  ** GUI Creation
2019  ***********************************************************************************************/
2020
2021 static GtkActionEntry entries[] = {
2022   { "File", NULL, N_("_File"), 0, 0, 0 },
2023   { "Edit", NULL, N_("_Edit"), 0, 0, 0 },
2024   { "View", NULL, N_("_View"), 0, 0, 0 },
2025   { "SetZoom", NULL, N_("_Zoom"), 0, 0, 0 },
2026   { "SetPan", NULL, N_("_Pan"), 0, 0, 0 },
2027   { "Layers", NULL, N_("_Layers"), 0, 0, 0 },
2028   { "Tools", NULL, N_("_Tools"), 0, 0, 0 },
2029   { "Exttools", NULL, N_("_Webtools"), 0, 0, 0 },
2030   { "Help", NULL, N_("_Help"), 0, 0, 0 },
2031
2032   { "New",       GTK_STOCK_NEW,          N_("_New"),                          "<control>N", N_("New file"),                                     (GCallback)newwindow_cb          },
2033   { "Open",      GTK_STOCK_OPEN,         N_("_Open"),                         "<control>O", N_("Open a file"),                                  (GCallback)load_file             },
2034   { "OpenRecentFile", NULL,         N_("Open _Recent file"),                         NULL, NULL,                                  (GCallback)NULL             },
2035   { "Append",    GTK_STOCK_ADD,          N_("A_ppend File"),                  NULL,         N_("Append data from a different file"),            (GCallback)load_file             },
2036   { "Acquire", NULL, N_("A_cquire"), 0, 0, 0 },
2037   { "AcquireGPS",   NULL,                N_("From _GPS"),                 NULL,         N_("Transfer data from a GPS device"),              (GCallback)acquire_from_gps      },
2038   { "AcquireGoogle",   NULL,             N_("Google _Directions"),        NULL,         N_("Get driving directions from Google"),           (GCallback)acquire_from_google   },
2039 #ifdef VIK_CONFIG_GEOCACHES
2040   { "AcquireGC",   NULL,                 N_("Geo_caches"),                NULL,         N_("Get Geocaches from geocaching.com"),            (GCallback)acquire_from_gc       },
2041 #endif
2042   { "Save",      GTK_STOCK_SAVE,         N_("_Save"),                         "<control>S", N_("Save the file"),                                (GCallback)save_file             },
2043   { "SaveAs",    GTK_STOCK_SAVE_AS,      N_("Save _As"),                      NULL,         N_("Save the file under different name"),           (GCallback)save_file_as          },
2044   { "GenImg",    GTK_STOCK_CLEAR,        N_("_Generate Image File"),          NULL,         N_("Save a snapshot of the workspace into a file"), (GCallback)draw_to_image_file_cb },
2045   { "GenImgDir", GTK_STOCK_DND_MULTIPLE, N_("Generate _Directory of Images"), NULL,         N_("FIXME:IMGDIR"),                                 (GCallback)draw_to_image_dir_cb  },
2046
2047 #if GTK_CHECK_VERSION(2,10,0)
2048   { "Print",    GTK_STOCK_PRINT,        N_("_Print..."),          NULL,         N_("Print maps"), (GCallback)print_cb },
2049 #endif
2050
2051   { "Exit",      GTK_STOCK_QUIT,         N_("E_xit"),                         "<control>W", N_("Exit the program"),                             (GCallback)window_close          },
2052   { "SaveExit",  GTK_STOCK_QUIT,         N_("Save and Exit"),                 NULL, N_("Save and Exit the program"),                             (GCallback)save_file_and_exit          },
2053
2054   { "GotoSearch",   GTK_STOCK_JUMP_TO,                 N_("Go To location"),                      NULL,         N_("Go to address/place using text search"),            (GCallback)goto_address       },
2055   { "GotoLL",    GTK_STOCK_QUIT,         N_("_Go to Lat\\/Lon..."),           NULL,         N_("Go to arbitrary lat\\/lon coordinate"),         (GCallback)draw_goto_cb          },
2056   { "GotoUTM",   GTK_STOCK_QUIT,         N_("Go to UTM..."),                  NULL,         N_("Go to arbitrary UTM coordinate"),               (GCallback)draw_goto_cb          },
2057   { "SetBGColor",GTK_STOCK_SELECT_COLOR, N_("Set Background Color..."),       NULL,         NULL,                                           (GCallback)set_bg_color          },
2058   { "ZoomIn",    GTK_STOCK_ZOOM_IN,      N_("Zoom _In"),                   "<control>plus", NULL,                                           (GCallback)draw_zoom_cb          },
2059   { "ZoomOut",   GTK_STOCK_ZOOM_OUT,     N_("Zoom _Out"),                 "<control>minus", NULL,                                           (GCallback)draw_zoom_cb          },
2060   { "ZoomTo",    GTK_STOCK_ZOOM_FIT,     N_("Zoom _To"),               "<control>Z", NULL,                                           (GCallback)zoom_to_cb            },
2061   { "Zoom0.25",  NULL,                   N_("0.25"),                          NULL,         NULL,                                           (GCallback)draw_zoom_cb          },
2062   { "Zoom0.5",   NULL,                   N_("0.5"),                           NULL,         NULL,                                           (GCallback)draw_zoom_cb          },
2063   { "Zoom1",     NULL,                   N_("1"),                             NULL,         NULL,                                           (GCallback)draw_zoom_cb          },
2064   { "Zoom2",     NULL,                   N_("2"),                             NULL,         NULL,                                           (GCallback)draw_zoom_cb          },
2065   { "Zoom4",     NULL,                   N_("4"),                             NULL,         NULL,                                           (GCallback)draw_zoom_cb          },
2066   { "Zoom8",     NULL,                   N_("8"),                             NULL,         NULL,                                           (GCallback)draw_zoom_cb          },
2067   { "Zoom16",    NULL,                   N_("16"),                            NULL,         NULL,                                           (GCallback)draw_zoom_cb          },
2068   { "Zoom32",    NULL,                   N_("32"),                            NULL,         NULL,                                           (GCallback)draw_zoom_cb          },
2069   { "Zoom64",    NULL,                   N_("64"),                            NULL,         NULL,                                           (GCallback)draw_zoom_cb          },
2070   { "Zoom128",   NULL,                   N_("128"),                           NULL,         NULL,                                           (GCallback)draw_zoom_cb          },
2071   { "PanNorth",  NULL,                   N_("Pan North"),                  "<control>Up", NULL,                                           (GCallback)draw_pan_cb },
2072   { "PanEast",  NULL,                    N_("Pan East"),                   "<control>Right", NULL,                                           (GCallback)draw_pan_cb },
2073   { "PanSouth",  NULL,                   N_("Pan South"),                  "<control>Down", NULL,                                           (GCallback)draw_pan_cb },
2074   { "PanWest",  NULL,                    N_("Pan West"),                   "<control>Left", NULL,                                           (GCallback)draw_pan_cb },
2075   { "BGJobs",    GTK_STOCK_EXECUTE,      N_("Background _Jobs"),              NULL,         NULL,                                           (GCallback)a_background_show_window },
2076
2077   { "Cut",       GTK_STOCK_CUT,          N_("Cu_t"),                          NULL,         NULL,                                           (GCallback)menu_cut_layer_cb     },
2078   { "Copy",      GTK_STOCK_COPY,         N_("_Copy"),                         NULL,         NULL,                                           (GCallback)menu_copy_layer_cb    },
2079   { "Paste",     GTK_STOCK_PASTE,        N_("_Paste"),                        NULL,         NULL,                                           (GCallback)menu_paste_layer_cb   },
2080   { "Delete",    GTK_STOCK_DELETE,       N_("_Delete"),                       NULL,         NULL,                                           (GCallback)menu_delete_layer_cb  },
2081   { "DeleteAll", NULL,                   N_("Delete All"),                    NULL,         NULL,                                           (GCallback)clear_cb              },
2082   { "MapCacheFlush",NULL, N_("Flush Map cache"),                              NULL,         NULL,                                           (GCallback)mapcache_flush_cb     },
2083   { "Preferences",GTK_STOCK_PREFERENCES, N_("_Preferences..."),               NULL,         NULL,                                           (GCallback)preferences_cb              },
2084   { "Properties",GTK_STOCK_PROPERTIES,   N_("_Properties"),                   NULL,         NULL,                                           (GCallback)menu_properties_cb    },
2085
2086   { "About",     GTK_STOCK_ABOUT,        N_("_About"),                        NULL,         NULL,                                           (GCallback)help_about_cb    },
2087 };
2088
2089 /* Radio items */
2090 static GtkRadioActionEntry mode_entries[] = {
2091   { "ModeUTM",         NULL,         N_("_UTM Mode"),               "<control>u", NULL, 0 },
2092   { "ModeExpedia",     NULL,         N_("_Expedia Mode"),           "<control>e", NULL, 1 },
2093   { "ModeMercator",    NULL,         N_("_Mercator Mode"),            "<control>g", NULL, 4 }
2094 };
2095
2096 static GtkRadioActionEntry tool_entries[] = {
2097   { "Pan",      "vik-icon-pan",        N_("_Pan"),                         "<control><shift>P", N_("Pan Tool"),  0 },
2098   { "Zoom",      "vik-icon-zoom",        N_("_Zoom"),                         "<control><shift>Z", N_("Zoom Tool"),  1 },
2099   { "Ruler",     "vik-icon-ruler",       N_("_Ruler"),                        "<control><shift>R", N_("Ruler Tool"), 2 }
2100 };
2101
2102 static GtkToggleActionEntry toggle_entries[] = {
2103   { "ShowScale", NULL,                   N_("Show Scale"),                    NULL,         N_("Show Scale"),                                           (GCallback)set_draw_scale, TRUE   },
2104   { "ShowCenterMark", NULL,                   N_("Show Center Mark"),                    NULL,         N_("Show Center Mark"),                                           (GCallback)set_draw_centermark, TRUE   },
2105   { "FullScreen",    GTK_STOCK_FULLSCREEN,      N_("Full Screen"),                   "F11", N_("Activate full screen mode"),                                           (GCallback)full_screen_cb, FALSE },
2106   { "ViewSidePanel", GTK_STOCK_INDEX,   N_("Show Side Panel"),                   "F9",         N_("Show Side Panel"),                                           (GCallback)view_side_panel_cb, TRUE    },
2107 };
2108
2109 #include "menu.xml.h"
2110 static void window_create_ui( VikWindow *window )
2111 {
2112   GtkUIManager *uim;
2113   GtkActionGroup *action_group;
2114   GtkAccelGroup *accel_group;
2115   GError *error;
2116   guint i, j, mid;
2117   GtkIconFactory *icon_factory;
2118   GtkIconSet *icon_set; 
2119   GtkRadioActionEntry *tools = NULL, *radio;
2120   guint ntools;
2121   
2122   uim = gtk_ui_manager_new ();
2123   window->uim = uim;
2124
2125   toolbox_add_tool(window->vt, &ruler_tool, TOOL_LAYER_TYPE_NONE);
2126   toolbox_add_tool(window->vt, &zoom_tool, TOOL_LAYER_TYPE_NONE);
2127   toolbox_add_tool(window->vt, &pan_tool, TOOL_LAYER_TYPE_NONE);
2128
2129   error = NULL;
2130   if (!(mid = gtk_ui_manager_add_ui_from_string (uim, menu_xml, -1, &error))) {
2131     g_error_free (error);
2132     exit (1);
2133   }
2134
2135   action_group = gtk_action_group_new ("MenuActions");
2136   gtk_action_group_set_translation_domain(action_group, PACKAGE_NAME);
2137   gtk_action_group_add_actions (action_group, entries, G_N_ELEMENTS (entries), window);
2138   gtk_action_group_add_toggle_actions (action_group, toggle_entries, G_N_ELEMENTS (toggle_entries), window);
2139   gtk_action_group_add_radio_actions (action_group, mode_entries, G_N_ELEMENTS (mode_entries), 4, (GCallback)window_change_coord_mode_cb, window);
2140
2141   icon_factory = gtk_icon_factory_new ();
2142   gtk_icon_factory_add_default (icon_factory); 
2143
2144   register_vik_icons(icon_factory);
2145
2146   ntools = 0;
2147   for (i=0; i<G_N_ELEMENTS(tool_entries); i++) {
2148       tools = g_renew(GtkRadioActionEntry, tools, ntools+1);
2149       radio = &tools[ntools];
2150       ntools++;
2151       *radio = tool_entries[i];
2152       radio->value = ntools;
2153   }  
2154
2155   for (i=0; i<VIK_LAYER_NUM_TYPES; i++) {
2156     GtkActionEntry action;
2157     gtk_ui_manager_add_ui(uim, mid,  "/ui/MainMenu/Layers/", 
2158                           vik_layer_get_interface(i)->name,
2159                           vik_layer_get_interface(i)->name,
2160                           GTK_UI_MANAGER_MENUITEM, FALSE);
2161
2162     icon_set = gtk_icon_set_new_from_pixbuf (gdk_pixbuf_from_pixdata (vik_layer_get_interface(i)->icon, FALSE, NULL ));
2163     gtk_icon_factory_add (icon_factory, vik_layer_get_interface(i)->name, icon_set);
2164     gtk_icon_set_unref (icon_set);
2165
2166     action.name = vik_layer_get_interface(i)->name;
2167     action.stock_id = vik_layer_get_interface(i)->name;
2168     action.label = g_strdup_printf( _("New %s Layer"), vik_layer_get_interface(i)->name);
2169     action.accelerator = NULL;
2170     action.tooltip = NULL;
2171     action.callback = (GCallback)menu_addlayer_cb;
2172     gtk_action_group_add_actions(action_group, &action, 1, window);
2173
2174     if ( vik_layer_get_interface(i)->tools_count ) {
2175       gtk_ui_manager_add_ui(uim, mid,  "/ui/MainMenu/Tools/", vik_layer_get_interface(i)->name, NULL, GTK_UI_MANAGER_SEPARATOR, FALSE);
2176       gtk_ui_manager_add_ui(uim, mid,  "/ui/MainToolbar/ToolItems/", vik_layer_get_interface(i)->name, NULL, GTK_UI_MANAGER_SEPARATOR, FALSE);
2177     }
2178
2179     for ( j = 0; j < vik_layer_get_interface(i)->tools_count; j++ ) {
2180       tools = g_renew(GtkRadioActionEntry, tools, ntools+1);
2181       radio = &tools[ntools];
2182       ntools++;
2183       
2184       gtk_ui_manager_add_ui(uim, mid,  "/ui/MainMenu/Tools", 
2185                             _(vik_layer_get_interface(i)->tools[j].name),
2186                             vik_layer_get_interface(i)->tools[j].name,
2187                             GTK_UI_MANAGER_MENUITEM, FALSE);
2188       gtk_ui_manager_add_ui(uim, mid,  "/ui/MainToolbar/ToolItems", 
2189                             _(vik_layer_get_interface(i)->tools[j].name),
2190                             vik_layer_get_interface(i)->tools[j].name,
2191                             GTK_UI_MANAGER_TOOLITEM, FALSE);
2192
2193       toolbox_add_tool(window->vt, &(vik_layer_get_interface(i)->tools[j]), i);
2194
2195       radio->name = vik_layer_get_interface(i)->tools[j].name;
2196       radio->stock_id = vik_layer_get_interface(i)->tools[j].name,
2197       radio->label = _(vik_layer_get_interface(i)->tools[j].name);
2198       radio->accelerator = NULL;
2199       radio->tooltip = _(vik_layer_get_interface(i)->tools[j].name);
2200       radio->value = ntools;
2201     }
2202   }
2203   g_object_unref (icon_factory);
2204
2205   gtk_action_group_add_radio_actions(action_group, tools, ntools, 0, (GCallback)menu_tool_cb, window);
2206   g_free(tools);
2207
2208   gtk_ui_manager_insert_action_group (uim, action_group, 0);
2209
2210   for (i=0; i<VIK_LAYER_NUM_TYPES; i++) {
2211     for ( j = 0; j < vik_layer_get_interface(i)->tools_count; j++ ) {
2212       GtkAction *action = gtk_action_group_get_action(action_group,
2213                             vik_layer_get_interface(i)->tools[j].name);
2214       g_object_set(action, "sensitive", FALSE, NULL);
2215     }
2216   }
2217   window->action_group = action_group;
2218
2219   accel_group = gtk_ui_manager_get_accel_group (uim);
2220   gtk_window_add_accel_group (GTK_WINDOW (window), accel_group);
2221   gtk_ui_manager_ensure_update (uim);
2222   
2223   setup_recent_files(window);
2224 }
2225
2226
2227
2228 static struct { 
2229   const GdkPixdata *data;
2230   gchar *stock_id;
2231 } stock_icons[] = {
2232   { &begintr_18_pixbuf,         "Begin Track"      },
2233   { &iscissors_18_pixbuf,       "Magic Scissors"   },
2234   { &mover_22_pixbuf,           "vik-icon-pan"     },
2235   { &demdl_18_pixbuf,           "DEM Download/Import"     },
2236   { &showpic_18_pixbuf,         "Show Picture"      },
2237   { &addtr_18_pixbuf,           "Create Track"      },
2238   { &edtr_18_pixbuf,            "Edit Trackpoint"   },
2239   { &addwp_18_pixbuf,           "Create Waypoint"   },
2240   { &edwp_18_pixbuf,            "Edit Waypoint"     },
2241   { &zoom_18_pixbuf,            "vik-icon-zoom"     },
2242   { &ruler_18_pixbuf,           "vik-icon-ruler"    },
2243   { &geozoom_18_pixbuf,         "Georef Zoom Tool"  },
2244   { &geomove_18_pixbuf,         "Georef Move Map"   },
2245   { &mapdl_18_pixbuf,           "Maps Download"     },
2246   { &showpic_18_pixbuf,         "Show Picture"      },
2247 };
2248  
2249 static gint n_stock_icons = G_N_ELEMENTS (stock_icons);
2250
2251 static void
2252 register_vik_icons (GtkIconFactory *icon_factory)
2253 {
2254   GtkIconSet *icon_set; 
2255   gint i;
2256
2257   for (i = 0; i < n_stock_icons; i++) {
2258     icon_set = gtk_icon_set_new_from_pixbuf (gdk_pixbuf_from_pixdata (
2259                    stock_icons[i].data, FALSE, NULL ));
2260     gtk_icon_factory_add (icon_factory, stock_icons[i].stock_id, icon_set);
2261     gtk_icon_set_unref (icon_set);
2262   }
2263 }
2264