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