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