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