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