]> git.street.me.uk Git - andy/viking.git/blob - src/vikwindow.c
Go to location using Google Maps search.
[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 #include "viking.h"
22 #include "background.h"
23 #include "acquire.h"
24 #include "datasources.h"
25 #include "googlesearch.h"
26
27 #define VIKING_TITLE " - Viking"
28
29 #include <glib/gprintf.h>
30 #include <stdlib.h>
31 #include <math.h>
32 #include <string.h>
33 #include <ctype.h>
34 #include <glib/gprintf.h>
35 #ifdef WINDOWS
36 /* TODO IMPORTANT: mkdir for windows header? is it called 'mkdir' */
37 #define make_dir(dir) mkdir(dir)
38 #else
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #define make_dir(dir) mkdir(dir,0777)
42 #endif
43
44 #define VIKING_WINDOW_WIDTH      1000
45 #define VIKING_WINDOW_HEIGHT     800
46 #define DRAW_IMAGE_DEFAULT_WIDTH 1280
47 #define DRAW_IMAGE_DEFAULT_HEIGHT 1024
48 #define DRAW_IMAGE_DEFAULT_SAVE_AS_PNG TRUE
49
50 static void window_finalize ( GObject *gob );
51 static GObjectClass *parent_class;
52
53 static void window_init ( VikWindow *vw );
54 static void window_class_init ( VikWindowClass *klass );
55
56 static void draw_update ( VikWindow *vw );
57
58 static void newwindow_cb ( GtkAction *a, VikWindow *vw );
59
60 /* Drawing & stuff */
61
62 static gboolean delete_event( VikWindow *vw );
63
64 static void draw_sync ( VikWindow *vw );
65 static void draw_redraw ( VikWindow *vw );
66 static void draw_scroll  ( VikWindow *vw, GdkEventScroll *event );
67 static void draw_click  ( VikWindow *vw, GdkEventButton *event );
68 static void draw_release ( VikWindow *vw, GdkEventButton *event );
69 static void draw_mouse_motion ( VikWindow *vw, GdkEventMotion *event );
70 static void draw_zoom_cb ( GtkAction *a, VikWindow *vw );
71 static void draw_goto_cb ( GtkAction *a, VikWindow *vw );
72
73 static void draw_status ();
74
75 /* End Drawing Functions */
76
77 static void menu_addlayer_cb ( GtkAction *a, VikWindow *vw );
78 static void menu_properties_cb ( GtkAction *a, VikWindow *vw );
79 static void menu_delete_layer_cb ( GtkAction *a, VikWindow *vw );
80
81 /* tool management */
82 typedef struct {
83   VikToolInterface ti;
84   gpointer state;
85 } toolbox_tool_t;
86
87 typedef struct {
88   int                   active_tool;
89   int                   n_tools;
90   toolbox_tool_t        *tools;
91   VikWindow *vw;
92 } toolbox_tools_t;
93
94 static void menu_tool_cb ( GtkAction *old, GtkAction *a, VikWindow *vw );
95 static toolbox_tools_t* toolbox_create(VikWindow *vw);
96 static void toolbox_add_tool(toolbox_tools_t *vt, VikToolInterface *vti);
97 static int toolbox_get_tool(toolbox_tools_t *vt, const gchar *tool_name);
98 static void toolbox_activate(toolbox_tools_t *vt, const gchar *tool_name);
99 static void toolbox_click (toolbox_tools_t *vt, GdkEventButton *event);
100 static void toolbox_move (toolbox_tools_t *vt, GdkEventButton *event);
101 static void toolbox_release (toolbox_tools_t *vt, GdkEventButton *event);
102
103
104 /* ui creation */
105 static void window_create_ui( VikWindow *window );
106 static void register_vik_icons (GtkIconFactory *icon_factory);
107
108 /* i/o */
109 static void load_file ( GtkAction *a, VikWindow *vw );
110 static gboolean save_file_as ( GtkAction *a, VikWindow *vw );
111 static gboolean save_file ( GtkAction *a, VikWindow *vw );
112 static gboolean save_file_and_exit ( GtkAction *a, VikWindow *vw );
113 static gboolean window_save ( VikWindow *vw );
114
115 struct _VikWindow {
116   GtkWindow gtkwindow;
117   VikViewport *viking_vvp;
118   VikLayersPanel *viking_vlp;
119   VikStatusbar *viking_vs;
120
121   GtkToolbar *toolbar;
122
123   GtkItemFactory *item_factory;
124
125   /* tool management state */
126   guint current_tool;
127   toolbox_tools_t *vt;
128   guint16 tool_layer_id;
129   guint16 tool_tool_id;
130
131   GtkActionGroup *action_group;
132
133   gint pan_x, pan_y;
134
135   guint draw_image_width, draw_image_height;
136   gboolean draw_image_save_as_png;
137
138   gchar *filename;
139   gboolean modified;
140
141   GtkWidget *open_dia, *save_dia;
142
143   gboolean only_updating_coord_mode_ui; /* hack for a bug in GTK */
144   GtkUIManager *uim;
145 };
146
147 enum {
148  TOOL_ZOOM = 0,
149  TOOL_RULER,
150  TOOL_LAYER,
151  NUMBER_OF_TOOLS
152 };
153
154 enum {
155   VW_NEWWINDOW_SIGNAL,
156   VW_OPENWINDOW_SIGNAL,
157   VW_LAST_SIGNAL
158 };
159
160 static guint window_signals[VW_LAST_SIGNAL] = { 0 };
161
162 static gchar *tool_names[NUMBER_OF_TOOLS] = { "Zoom", "Ruler", "Pan" };
163
164 GType vik_window_get_type (void)
165 {
166   static GType vw_type = 0;
167
168   if (!vw_type)
169   {
170     static const GTypeInfo vw_info = 
171     {
172       sizeof (VikWindowClass),
173       NULL, /* base_init */
174       NULL, /* base_finalize */
175       (GClassInitFunc) window_class_init, /* class_init */
176       NULL, /* class_finalize */
177       NULL, /* class_data */
178       sizeof (VikWindow),
179       0,
180       (GInstanceInitFunc) window_init,
181     };
182     vw_type = g_type_register_static ( GTK_TYPE_WINDOW, "VikWindow", &vw_info, 0 );
183   }
184
185   return vw_type;
186 }
187
188 void vik_window_selected_layer(VikWindow *vw, VikLayer *vl)
189 {
190   int i, j, tool_count;
191   VikLayerInterface *layer_interface;
192
193   if (!vw->action_group) return;
194
195   for (i=0; i<VIK_LAYER_NUM_TYPES; i++) {
196     GtkAction *action;
197     layer_interface = vik_layer_get_interface(i);
198     tool_count = layer_interface->tools_count;
199
200     for (j = 0; j < tool_count; j++) {
201       action = gtk_action_group_get_action(vw->action_group,
202             layer_interface->tools[j].name);
203       g_object_set(action, "sensitive", i == vl->type, NULL);
204     }
205   }
206 }
207
208 static void window_finalize ( GObject *gob )
209 {
210   VikWindow *vw = VIK_WINDOW(gob);
211   g_return_if_fail ( vw != NULL );
212
213   a_background_remove_status ( vw->viking_vs );
214
215   G_OBJECT_CLASS(parent_class)->finalize(gob);
216 }
217
218 static void window_class_init ( VikWindowClass *klass )
219 {
220   /* destructor */
221   GObjectClass *object_class;
222
223   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);
224   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);
225
226   object_class = G_OBJECT_CLASS (klass);
227
228   object_class->finalize = window_finalize;
229
230   parent_class = g_type_class_peek_parent (klass);
231
232 }
233
234 static void window_init ( VikWindow *vw )
235 {
236   GtkWidget *main_vbox;
237   GtkWidget *hpaned;
238
239   vw->action_group = NULL;
240
241   vw->viking_vvp = vik_viewport_new();
242   vw->viking_vlp = vik_layers_panel_new();
243   vik_layers_panel_set_viewport ( vw->viking_vlp, vw->viking_vvp );
244   vw->viking_vs = vik_statusbar_new();
245
246   vw->vt = toolbox_create(vw);
247   window_create_ui(vw);
248   gtk_window_set_title ( GTK_WINDOW(vw), "Untitled" VIKING_TITLE );
249   
250   toolbox_activate(vw->vt, "Zoom");
251
252   vw->filename = NULL;
253   vw->item_factory = NULL;
254
255   vw->modified = FALSE;
256   vw->only_updating_coord_mode_ui = FALSE;
257   
258
259   vw->pan_x = vw->pan_y = -1;
260   vw->draw_image_width = DRAW_IMAGE_DEFAULT_WIDTH;
261   vw->draw_image_height = DRAW_IMAGE_DEFAULT_HEIGHT;
262   vw->draw_image_save_as_png = DRAW_IMAGE_DEFAULT_SAVE_AS_PNG;
263
264   main_vbox = gtk_vbox_new(FALSE, 1);
265   gtk_container_add (GTK_CONTAINER (vw), main_vbox);
266
267   gtk_box_pack_start (GTK_BOX(main_vbox), gtk_ui_manager_get_widget (vw->uim, "/MainMenu"), FALSE, TRUE, 0);
268   gtk_box_pack_start (GTK_BOX(main_vbox), gtk_ui_manager_get_widget (vw->uim, "/MainToolbar"), FALSE, TRUE, 0);
269   gtk_toolbar_set_icon_size(GTK_TOOLBAR(gtk_ui_manager_get_widget (vw->uim, "/MainToolbar")), GTK_ICON_SIZE_SMALL_TOOLBAR);
270   gtk_toolbar_set_style (GTK_TOOLBAR(gtk_ui_manager_get_widget (vw->uim, "/MainToolbar")), GTK_TOOLBAR_ICONS);
271
272   g_signal_connect (G_OBJECT (vw), "delete_event", G_CALLBACK (delete_event), NULL);
273
274   g_signal_connect_swapped (G_OBJECT(vw->viking_vvp), "expose_event", G_CALLBACK(draw_sync), vw);
275   g_signal_connect_swapped (G_OBJECT(vw->viking_vvp), "configure_event", G_CALLBACK(draw_redraw), vw);
276   gtk_widget_add_events ( GTK_WIDGET(vw->viking_vvp), GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK );
277   g_signal_connect_swapped (G_OBJECT(vw->viking_vvp), "scroll_event", G_CALLBACK(draw_scroll), vw);
278   g_signal_connect_swapped (G_OBJECT(vw->viking_vvp), "button_press_event", G_CALLBACK(draw_click), vw);
279   g_signal_connect_swapped (G_OBJECT(vw->viking_vvp), "button_release_event", G_CALLBACK(draw_release), vw);
280   g_signal_connect_swapped (G_OBJECT(vw->viking_vvp), "motion_notify_event", G_CALLBACK(draw_mouse_motion), vw);
281   g_signal_connect_swapped (G_OBJECT(vw->viking_vlp), "update", G_CALLBACK(draw_update), vw);
282
283   gtk_window_set_default_size ( GTK_WINDOW(vw), VIKING_WINDOW_WIDTH, VIKING_WINDOW_HEIGHT);
284
285   hpaned = gtk_hpaned_new ();
286   gtk_paned_add1 ( GTK_PANED(hpaned), GTK_WIDGET (vw->viking_vlp) );
287   gtk_paned_add2 ( GTK_PANED(hpaned), GTK_WIDGET (vw->viking_vvp) );
288
289   /* This packs the button into the window (a gtk container). */
290   gtk_box_pack_start (GTK_BOX(main_vbox), hpaned, TRUE, TRUE, 0);
291
292   gtk_box_pack_end (GTK_BOX(main_vbox), GTK_WIDGET(vw->viking_vs), FALSE, TRUE, 0);
293
294   a_background_add_status(vw->viking_vs);
295
296   vw->open_dia = NULL;
297   vw->save_dia = NULL;
298 }
299
300 VikWindow *vik_window_new ()
301 {
302   return VIK_WINDOW ( g_object_new ( VIK_WINDOW_TYPE, NULL ) );
303 }
304
305 static gboolean delete_event( VikWindow *vw )
306 {
307 #ifdef VIKING_PROMPT_IF_MODIFIED
308   if ( vw->modified )
309 #else
310   if (0)
311 #endif
312   {
313     GtkDialog *dia;
314     dia = GTK_DIALOG ( gtk_message_dialog_new ( GTK_WINDOW(vw), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE,
315       "Do you want to save the changes you made to the document \"%s\"?\n\nYour changes will be lost if you don't save them.",
316       vw->filename ? a_file_basename ( vw->filename ) : "Untitled" ) );
317     gtk_dialog_add_buttons ( dia, "Don't Save", GTK_RESPONSE_NO, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_SAVE, GTK_RESPONSE_YES, NULL );
318     switch ( gtk_dialog_run ( dia ) )
319     {
320       case GTK_RESPONSE_NO: gtk_widget_destroy ( GTK_WIDGET(dia) ); return FALSE;
321       case GTK_RESPONSE_CANCEL: gtk_widget_destroy ( GTK_WIDGET(dia) ); return TRUE;
322       default: gtk_widget_destroy ( GTK_WIDGET(dia) ); return ! save_file(NULL, vw);
323     }
324   }
325   return FALSE;
326 }
327
328 /* Drawing stuff */
329 static void newwindow_cb ( GtkAction *a, VikWindow *vw )
330 {
331   g_signal_emit ( G_OBJECT(vw), window_signals[VW_NEWWINDOW_SIGNAL], 0 );
332 }
333
334 static void draw_update ( VikWindow *vw )
335 {
336   draw_redraw (vw);
337   draw_sync (vw);
338 }
339
340 static void draw_sync ( VikWindow *vw )
341 {
342   vik_viewport_sync(vw->viking_vvp);
343   draw_status ( vw );
344   /* other things may be necc here later. */
345 }
346
347 static void draw_status ( VikWindow *vw )
348 {
349   static gchar zoom_level[22];
350   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" );
351   if ( vw->current_tool == TOOL_LAYER )
352     vik_statusbar_set_message ( vw->viking_vs, 0, vik_layer_get_interface(vw->tool_layer_id)->tools[vw->tool_tool_id].name );
353   else
354     vik_statusbar_set_message ( vw->viking_vs, 0, tool_names[vw->current_tool] );
355
356   vik_statusbar_set_message ( vw->viking_vs, 2, zoom_level );
357 }
358
359 static void draw_redraw ( VikWindow *vw )
360 {
361   vik_viewport_clear ( vw->viking_vvp);
362   vik_layers_panel_draw_all ( vw->viking_vlp );
363   vik_viewport_draw_scale ( vw->viking_vvp );
364 }
365
366 gboolean draw_buf_done = TRUE;
367
368 static gboolean draw_buf(gpointer data)
369 {
370   gpointer *pass_along = data;
371   gdk_threads_enter();
372   gdk_draw_drawable (pass_along[0], pass_along[1],
373                      pass_along[2], 0, 0, 0, 0, -1, -1);
374   draw_buf_done = TRUE;
375   gdk_threads_leave();
376   return FALSE;
377 }
378
379
380 /* Mouse event handlers ************************************************************************/
381
382 static void draw_click (VikWindow *vw, GdkEventButton *event)
383 {
384
385   /* middle button pressed.  we reserve all middle button and scroll events
386    * for panning and zooming; tools only get left/right/movement 
387    */
388   if ( event->button == 2) {
389     /* set panning origin */
390     vw->pan_x = (gint) event->x;
391     vw->pan_y = (gint) event->y;
392   } 
393   else {
394     toolbox_click(vw->vt, event);
395   }
396 }
397
398 static void draw_mouse_motion (VikWindow *vw, GdkEventMotion *event)
399 {
400   static VikCoord coord;
401   static struct UTM utm;
402   static struct LatLon ll;
403   static char pointer_buf[36];
404
405   toolbox_move(vw->vt, (GdkEventButton *)event);
406
407   vik_viewport_screen_to_coord ( vw->viking_vvp, event->x, event->y, &coord );
408   vik_coord_to_utm ( &coord, &utm );
409   a_coords_utm_to_latlon ( &utm, &ll );
410   g_snprintf ( pointer_buf, 36, "Cursor: %f %f", ll.lat, ll.lon );
411   vik_statusbar_set_message ( vw->viking_vs, 4, pointer_buf );
412
413   if ( vw->pan_x != -1 ) {
414     vik_viewport_pan_sync ( vw->viking_vvp, event->x - vw->pan_x, event->y - vw->pan_y );
415   }
416 }
417
418 static void draw_release ( VikWindow *vw, GdkEventButton *event )
419 {
420   if ( event->button == 2 ) {  /* move / pan */
421     if ( ABS(vw->pan_x - event->x) <= 1 && ABS(vw->pan_y - event->y) <= 1 )
422         vik_viewport_set_center_screen ( vw->viking_vvp, vw->pan_x, vw->pan_y );
423       else
424          vik_viewport_set_center_screen ( vw->viking_vvp, vik_viewport_get_width(vw->viking_vvp)/2 - event->x + vw->pan_x,
425                                          vik_viewport_get_height(vw->viking_vvp)/2 - event->y + vw->pan_y );
426       draw_update ( vw );
427       vw->pan_x = vw->pan_y = -1;
428   }
429   else {
430     toolbox_release(vw->vt, event);
431   }
432 }
433
434 static void draw_scroll (VikWindow *vw, GdkEventScroll *event)
435 {
436   if ( event->direction == GDK_SCROLL_UP )
437     vik_viewport_zoom_in (vw->viking_vvp);
438   else
439     vik_viewport_zoom_out(vw->viking_vvp);
440   draw_update(vw);
441 }
442
443
444
445 /********************************************************************************
446  ** Ruler tool code
447  ********************************************************************************/
448 static void draw_ruler(VikViewport *vvp, GdkDrawable *d, GdkGC *gc, gint x1, gint y1, gint x2, gint y2, gdouble distance)
449 {
450   PangoFontDescription *pfd;
451   PangoLayout *pl;
452   gchar str[128];
453   GdkGC *labgc = vik_viewport_new_gc ( vvp, "#cccccc", 1);
454   GdkGC *thickgc = gdk_gc_new(d);
455   
456   gdouble len = sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
457   gdouble dx = (x2-x1)/len*10; 
458   gdouble dy = (y2-y1)/len*10;
459   gdouble c = cos(15.0 * M_PI/180.0);
460   gdouble s = sin(15.0 * M_PI/180.0);
461   gdouble angle;
462   gdouble baseangle = 0;
463   gint i;
464
465   /* draw line with arrow ends */
466   {
467     gint tmp_x1=x1, tmp_y1=y1, tmp_x2=x2, tmp_y2=y2;
468     a_viewport_clip_line(&tmp_x1, &tmp_y1, &tmp_x2, &tmp_y2);
469     gdk_draw_line(d, gc, tmp_x1, tmp_y1, tmp_x2, tmp_y2);
470   }
471
472   a_viewport_clip_line(&x1, &y1, &x2, &y2);
473   gdk_draw_line(d, gc, x1, y1, x2, y2);
474
475   gdk_draw_line(d, gc, x1 - dy, y1 + dx, x1 + dy, y1 - dx);
476   gdk_draw_line(d, gc, x2 - dy, y2 + dx, x2 + dy, y2 - dx);
477   gdk_draw_line(d, gc, x2, y2, x2 - (dx * c + dy * s), y2 - (dy * c - dx * s));
478   gdk_draw_line(d, gc, x2, y2, x2 - (dx * c - dy * s), y2 - (dy * c + dx * s));
479   gdk_draw_line(d, gc, x1, y1, x1 + (dx * c + dy * s), y1 + (dy * c - dx * s));
480   gdk_draw_line(d, gc, x1, y1, x1 + (dx * c - dy * s), y1 + (dy * c + dx * s));
481
482   /* draw compass */
483 #define CR 80
484 #define CW 4
485   angle = atan2(dy, dx) + M_PI_2;
486
487   if ( vik_viewport_get_drawmode ( vvp ) == VIK_VIEWPORT_DRAWMODE_UTM) {
488     VikCoord test;
489     struct LatLon ll;
490     struct UTM u;
491     gint tx, ty;
492
493     vik_viewport_screen_to_coord ( vvp, x1, y1, &test );
494     vik_coord_to_latlon ( &test, &ll );
495     ll.lat += vik_viewport_get_ympp ( vvp ) * vik_viewport_get_height ( vvp ) / 11000.0; // about 11km per degree latitude
496     a_coords_latlon_to_utm ( &ll, &u );
497     vik_coord_load_from_utm ( &test, VIK_VIEWPORT_DRAWMODE_UTM, &u );
498     vik_viewport_coord_to_screen ( vvp, &test, &tx, &ty );
499
500     baseangle = M_PI - atan2(tx-x1, ty-y1);
501     angle -= baseangle;
502   }
503
504   if (angle<0) 
505     angle+=2*M_PI;
506   if (angle>2*M_PI)
507     angle-=2*M_PI;
508
509   {
510     GdkColor color;
511     gdk_gc_copy(thickgc, gc);
512     gdk_gc_set_line_attributes(thickgc, CW, GDK_LINE_SOLID, GDK_CAP_BUTT, GDK_JOIN_MITER);
513     gdk_color_parse("#2255cc", &color);
514     gdk_gc_set_rgb_fg_color(thickgc, &color);
515   }
516   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);
517
518
519   gdk_gc_copy(thickgc, gc);
520   gdk_gc_set_line_attributes(thickgc, 2, GDK_LINE_SOLID, GDK_CAP_BUTT, GDK_JOIN_MITER);
521   for (i=0; i<180; i++) {
522     c = cos(i*M_PI/90.0 + baseangle);
523     s = sin(i*M_PI/90.0 + baseangle);
524
525     if (i%5) {
526       gdk_draw_line (d, gc, x1 + CR*c, y1 + CR*s, x1 + (CR+CW)*c, y1 + (CR+CW)*s);
527     } else {
528       gdouble ticksize = 2*CW;
529       gdk_draw_line (d, thickgc, x1 + (CR-CW)*c, y1 + (CR-CW)*s, x1 + (CR+ticksize)*c, y1 + (CR+ticksize)*s);
530     }
531   }
532
533   gdk_draw_arc (d, gc, FALSE, x1-CR, y1-CR, 2*CR, 2*CR, 0, 64*360);
534   gdk_draw_arc (d, gc, FALSE, x1-CR-CW, y1-CR-CW, 2*(CR+CW), 2*(CR+CW), 0, 64*360);
535   gdk_draw_arc (d, gc, FALSE, x1-CR+CW, y1-CR+CW, 2*(CR-CW), 2*(CR-CW), 0, 64*360);
536   c = (CR+CW*2)*cos(baseangle);
537   s = (CR+CW*2)*sin(baseangle);
538   gdk_draw_line (d, gc, x1-c, y1-s, x1+c, y1+s);
539   gdk_draw_line (d, gc, x1+s, y1-c, x1-s, y1+c);
540
541   /* draw labels */
542 #define LABEL(x, y, w, h) { \
543     gdk_draw_rectangle(d, labgc, TRUE, (x)-2, (y)-1, (w)+4, (h)+1); \
544     gdk_draw_rectangle(d, gc, FALSE, (x)-2, (y)-1, (w)+4, (h)+1); \
545     gdk_draw_layout(d, gc, (x), (y), pl); } 
546   {
547     gint wd, hd, xd, yd;
548     gint wb, hb, xb, yb;
549
550     pl = gtk_widget_create_pango_layout (GTK_WIDGET(vvp), NULL);
551
552     pfd = pango_font_description_from_string ("Sans 8"); // FIXME: settable option? global variable?
553     pango_layout_set_font_description (pl, pfd);
554     pango_font_description_free (pfd);
555
556     pango_layout_set_text(pl, "N", -1);
557     gdk_draw_layout(d, gc, x1-5, y1-CR-3*CW-8, pl);
558
559     /* draw label with distance */
560     if (distance >= 1000 && distance < 100000) {
561       g_sprintf(str, "%3.2f km", distance/1000.0);
562     } else if (distance < 1000) {
563       g_sprintf(str, "%d m", (int)distance);
564     } else {
565       g_sprintf(str, "%d km", (int)distance/1000);
566     }
567     pango_layout_set_text(pl, str, -1);
568
569     pango_layout_get_pixel_size ( pl, &wd, &hd );
570     if (dy>0) {
571       xd = (x1+x2)/2 + dy;
572       yd = (y1+y2)/2 - hd/2 - dx;
573     } else {
574       xd = (x1+x2)/2 - dy;
575       yd = (y1+y2)/2 - hd/2 + dx;
576     }
577
578     if ( xd < -5 || yd < -5 || xd > vik_viewport_get_width(vvp)+5 || yd > vik_viewport_get_height(vvp)+5 ) {
579       xd = x2 + 10;
580       yd = y2 - 5;
581     }
582
583     LABEL(xd, yd, wd, hd);
584
585     /* draw label with bearing */
586     g_sprintf(str, "%3.1f°", angle*180.0/M_PI);
587     pango_layout_set_text(pl, str, -1);
588     pango_layout_get_pixel_size ( pl, &wb, &hb );
589     xb = x1 + CR*cos(angle-M_PI_2);
590     yb = y1 + CR*sin(angle-M_PI_2);
591
592     if ( xb < -5 || yb < -5 || xb > vik_viewport_get_width(vvp)+5 || yb > vik_viewport_get_height(vvp)+5 ) {
593       xb = x2 + 10;
594       yb = y2 + 10;
595     }
596
597     {
598       GdkRectangle r1 = {xd-2, yd-1, wd+4, hd+1}, r2 = {xb-2, yb-1, wb+4, hb+1};
599       if (gdk_rectangle_intersect(&r1, &r2, &r2)) {
600         xb = xd + wd + 5;
601       }
602     }
603     LABEL(xb, yb, wb, hb);
604   }
605 #undef LABEL
606
607   g_object_unref ( G_OBJECT ( pl ) );
608   g_object_unref ( G_OBJECT ( labgc ) );
609   g_object_unref ( G_OBJECT ( thickgc ) );
610 }
611
612 typedef struct {
613   VikWindow *vw;
614   VikViewport *vvp;
615   gboolean has_oldcoord;
616   VikCoord oldcoord;
617 } ruler_tool_state_t;
618
619 static gpointer ruler_create (VikWindow *vw, VikViewport *vvp) 
620 {
621   ruler_tool_state_t *s = g_new(ruler_tool_state_t, 1);
622   s->vw = vw;
623   s->vvp = vvp;
624   s->has_oldcoord = FALSE;
625   return s;
626 }
627
628 static void ruler_destroy (ruler_tool_state_t *s)
629 {
630   g_free(s);
631 }
632
633 static VikLayerToolFuncStatus ruler_click (VikLayer *vl, GdkEventButton *event, ruler_tool_state_t *s)
634 {
635   struct LatLon ll;
636   VikCoord coord;
637   gchar *temp;
638   if ( event->button == 1 ) {
639     vik_viewport_screen_to_coord ( s->vvp, (gint) event->x, (gint) event->y, &coord );
640     vik_coord_to_latlon ( &coord, &ll );
641     if ( s->has_oldcoord ) {
642       temp = g_strdup_printf ( "%f %f DIFF %f meters", ll.lat, ll.lon, vik_coord_diff( &coord, &(s->oldcoord) ) );
643       s->has_oldcoord = FALSE;
644     }
645     else {
646       temp = g_strdup_printf ( "%f %f", ll.lat, ll.lon );
647       s->has_oldcoord = TRUE;
648     }
649
650     vik_statusbar_set_message ( s->vw->viking_vs, 3, temp );
651     g_free ( temp );
652
653     s->oldcoord = coord;
654   }
655   else {
656     vik_viewport_set_center_screen ( s->vvp, (gint) event->x, (gint) event->y );
657     draw_update ( s->vw );
658   }
659   return VIK_LAYER_TOOL_ACK;
660 }
661
662 static VikLayerToolFuncStatus ruler_move (VikLayer *vl, GdkEventButton *event, ruler_tool_state_t *s)
663 {
664   VikViewport *vvp = s->vvp;
665   VikWindow *vw = s->vw;
666
667   struct LatLon ll;
668   VikCoord coord;
669   gchar *temp;
670
671   if ( s->has_oldcoord ) {
672     int oldx, oldy, w1, h1, w2, h2;
673     static GdkPixmap *buf = NULL;
674     w1 = vik_viewport_get_width(vvp); 
675     h1 = vik_viewport_get_height(vvp);
676     if (!buf) {
677       buf = gdk_pixmap_new ( GTK_WIDGET(vvp)->window, w1, h1, -1 );
678     }
679     gdk_drawable_get_size(buf, &w2, &h2);
680     if (w1 != w2 || h1 != h2) {
681       g_object_unref ( G_OBJECT ( buf ) );
682       buf = gdk_pixmap_new ( GTK_WIDGET(vvp)->window, w1, h1, -1 );
683     }
684
685     vik_viewport_screen_to_coord ( vvp, (gint) event->x, (gint) event->y, &coord );
686     vik_coord_to_latlon ( &coord, &ll );
687     vik_viewport_coord_to_screen ( vvp, &s->oldcoord, &oldx, &oldy );
688
689     gdk_draw_drawable (buf, GTK_WIDGET(vvp)->style->black_gc, 
690                        vik_viewport_get_pixmap(vvp), 0, 0, 0, 0, -1, -1);
691     draw_ruler(vvp, buf, GTK_WIDGET(vvp)->style->black_gc, oldx, oldy, event->x, event->y, vik_coord_diff( &coord, &(s->oldcoord)) );
692     if (draw_buf_done) {
693       static gpointer pass_along[3];
694       pass_along[0] = GTK_WIDGET(vvp)->window;
695       pass_along[1] = GTK_WIDGET(vvp)->style->black_gc;
696       pass_along[2] = buf;
697       g_idle_add_full (G_PRIORITY_HIGH_IDLE + 10, draw_buf, pass_along, NULL);
698       draw_buf_done = FALSE;
699     }
700
701     temp = g_strdup_printf ( "%f %f DIFF %f meters", ll.lat, ll.lon, vik_coord_diff( &coord, &(s->oldcoord) ) );
702     vik_statusbar_set_message ( vw->viking_vs, 3, temp );
703     g_free ( temp );
704   }
705   return VIK_LAYER_TOOL_ACK;
706 }
707
708 static VikLayerToolFuncStatus ruler_release (VikLayer *vl, GdkEventButton *event, ruler_tool_state_t *s)
709 {
710   return VIK_LAYER_TOOL_ACK;
711 }
712
713 static void ruler_deactivate (VikLayer *vl, ruler_tool_state_t *s)
714 {
715   draw_update ( s->vw );
716 }
717
718 static VikToolInterface ruler_tool = 
719   { "Ruler", 
720     (VikToolConstructorFunc) ruler_create,
721     (VikToolDestructorFunc) ruler_destroy,
722     (VikToolActivationFunc) NULL,
723     (VikToolActivationFunc) ruler_deactivate, 
724     (VikToolMouseFunc) ruler_click, 
725     (VikToolMouseFunc) ruler_move, 
726     (VikToolMouseFunc) ruler_release };
727 /*** end ruler code ********************************************************/
728
729
730
731 /********************************************************************************
732  ** Zoom tool code
733  ********************************************************************************/
734 static gpointer zoomtool_create (VikWindow *vw, VikViewport *vvp)
735 {
736   return vw;
737 }
738
739 static VikLayerToolFuncStatus zoomtool_click (VikLayer *vl, GdkEventButton *event, VikWindow *vw)
740 {
741   vw->modified = TRUE;
742   vik_viewport_set_center_screen ( vw->viking_vvp, (gint) event->x, (gint) event->y );
743   if ( event->button == 1 )
744     vik_viewport_zoom_in (vw->viking_vvp);
745   else if ( event->button == 3 )
746     vik_viewport_zoom_out (vw->viking_vvp);
747   draw_update ( vw );
748   return VIK_LAYER_TOOL_ACK;
749 }
750
751 static VikLayerToolFuncStatus zoomtool_move (VikLayer *vl, GdkEventButton *event, VikViewport *vvp)
752 {
753   return VIK_LAYER_TOOL_ACK;
754 }
755
756 static VikLayerToolFuncStatus zoomtool_release (VikLayer *vl, GdkEventButton *event, VikViewport *vvp)
757 {
758   return VIK_LAYER_TOOL_ACK;
759 }
760
761 static VikToolInterface zoom_tool = 
762   { "Zoom", 
763     (VikToolConstructorFunc) zoomtool_create,
764     (VikToolDestructorFunc) NULL,
765     (VikToolActivationFunc) NULL,
766     (VikToolActivationFunc) NULL,
767     (VikToolMouseFunc) zoomtool_click, 
768     (VikToolMouseFunc) zoomtool_move,
769     (VikToolMouseFunc) zoomtool_release };
770 /*** end ruler code ********************************************************/
771
772
773
774 static void draw_zoom_cb ( GtkAction *a, VikWindow *vw )
775 {
776   guint what = 128;
777
778   if (!strcmp(gtk_action_get_name(a), "ZoomIn")) {
779     what = -3;
780   } 
781   else if (!strcmp(gtk_action_get_name(a), "ZoomOut")) {
782     what = -4;
783   }
784   else if (!strcmp(gtk_action_get_name(a), "Zoom0.25")) {
785     what = -2;
786   }
787   else if (!strcmp(gtk_action_get_name(a), "Zoom0.5")) {
788     what = -1;
789   }
790   else {
791     gchar *s = (gchar *)gtk_action_get_name(a);
792     what = atoi(s+4);
793   }
794
795   switch (what)
796   {
797     case -3: vik_viewport_zoom_in ( vw->viking_vvp ); break;
798     case -4: vik_viewport_zoom_out ( vw->viking_vvp ); break;
799     case -1: vik_viewport_set_zoom ( vw->viking_vvp, 0.5 ); break;
800     case -2: vik_viewport_set_zoom ( vw->viking_vvp, 0.25 ); break;
801     default: vik_viewport_set_zoom ( vw->viking_vvp, what );
802   }
803   draw_update ( vw );
804 }
805
806 void draw_goto_cb ( GtkAction *a, VikWindow *vw )
807 {
808   VikCoord new_center;
809
810   if (!strcmp(gtk_action_get_name(a), "GotoLL")) {
811     struct LatLon ll, llold;
812     vik_coord_to_latlon ( vik_viewport_get_center ( vw->viking_vvp ), &llold );
813     if ( a_dialog_goto_latlon ( GTK_WINDOW(vw), &ll, &llold ) )
814       vik_coord_load_from_latlon ( &new_center, vik_viewport_get_coord_mode(vw->viking_vvp), &ll );
815     else
816       return;
817   }
818   else if (!strcmp(gtk_action_get_name(a), "GotoUTM")) {
819     struct UTM utm, utmold;
820     vik_coord_to_utm ( vik_viewport_get_center ( vw->viking_vvp ), &utmold );
821     if ( a_dialog_goto_utm ( GTK_WINDOW(vw), &utm, &utmold ) )
822       vik_coord_load_from_utm ( &new_center, vik_viewport_get_coord_mode(vw->viking_vvp), &utm );
823     else
824      return;
825   }
826   else {
827     fprintf(stderr, "Houston we have a problem\n");
828     return;
829   }
830
831   vik_viewport_set_center_coord ( vw->viking_vvp, &new_center );
832   draw_update ( vw );
833 }
834
835 static void menu_addlayer_cb ( GtkAction *a, VikWindow *vw )
836 {
837   gint type;
838   for ( type = 0; type < VIK_LAYER_NUM_TYPES; type++ ) {
839     if (!strcmp(vik_layer_get_interface(type)->name, gtk_action_get_name(a))) {
840       if ( vik_layers_panel_new_layer ( vw->viking_vlp, type ) ) {
841         draw_update ( vw );
842         vw->modified = TRUE;
843       }
844     }
845   }
846 }
847
848 static void menu_copy_layer_cb ( GtkAction *a, VikWindow *vw )
849 {
850   a_clipboard_copy_selected ( vw->viking_vlp );
851 }
852
853 static void menu_cut_layer_cb ( GtkAction *a, VikWindow *vw )
854 {
855   a_clipboard_copy_selected ( vw->viking_vlp );
856   menu_delete_layer_cb ( a, vw );
857 }
858
859 static void menu_paste_layer_cb ( GtkAction *a, VikWindow *vw )
860 {
861   if ( a_clipboard_paste ( vw->viking_vlp ) )
862   {
863     draw_update ( vw );
864     vw->modified = TRUE;
865   }
866 }
867
868 static void menu_properties_cb ( GtkAction *a, VikWindow *vw )
869 {
870   if ( ! vik_layers_panel_properties ( vw->viking_vlp ) )
871     a_dialog_info_msg ( GTK_WINDOW(vw), "You must select a layer to show its properties." );
872 }
873
874 static void help_about_cb ( GtkAction *a, VikWindow *vw )
875 {
876   a_dialog_about(GTK_WINDOW(vw));
877 }
878
879 static void menu_delete_layer_cb ( GtkAction *a, VikWindow *vw )
880 {
881   if ( vik_layers_panel_get_selected ( vw->viking_vlp ) )
882   {
883     vik_layers_panel_delete_selected ( vw->viking_vlp );
884     vw->modified = TRUE;
885   }
886   else
887     a_dialog_info_msg ( GTK_WINDOW(vw), "You must select a layer to delete." );
888 }
889
890 /***************************************
891  ** tool management routines
892  **
893  ***************************************/
894
895 static toolbox_tools_t* toolbox_create(VikWindow *vw)
896 {
897   toolbox_tools_t *vt = g_new(toolbox_tools_t, 1);
898   vt->tools = NULL;
899   vt->n_tools = 0;
900   vt->active_tool = -1;
901   vt->vw = vw;
902   if (!vw->viking_vvp) {
903     printf("Error: no viewport found.\n");
904     exit(1);
905   }
906   return vt;
907 }
908
909 static void toolbox_add_tool(toolbox_tools_t *vt, VikToolInterface *vti)
910 {
911   vt->tools = g_renew(toolbox_tool_t, vt->tools, vt->n_tools+1);
912   vt->tools[vt->n_tools].ti = *vti;
913   if (vti->create) {
914     vt->tools[vt->n_tools].state = vti->create(vt->vw, vt->vw->viking_vvp);
915   } 
916   else {
917     vt->tools[vt->n_tools].state = NULL;
918   }
919   vt->n_tools++;
920 }
921
922 static int toolbox_get_tool(toolbox_tools_t *vt, const gchar *tool_name)
923 {
924   int i;
925   for (i=0; i<vt->n_tools; i++) {
926     if (!strcmp(tool_name, vt->tools[i].ti.name)) {
927       break;
928     }
929   }
930   return i;
931 }
932
933 static void toolbox_activate(toolbox_tools_t *vt, const gchar *tool_name)
934 {
935   int tool = toolbox_get_tool(vt, tool_name);
936   toolbox_tool_t *t = &vt->tools[tool];
937   VikLayer *vl = vik_layers_panel_get_selected ( vt->vw->viking_vlp );
938
939   if (tool == vt->n_tools) {
940     printf("panic: trying to activate a non-existent tool... \n");
941     exit(1);
942   }
943   /* is the tool already active? */
944   if (vt->active_tool == tool) {
945     return;
946   }
947
948   if (vt->active_tool != -1) {
949     if (vt->tools[vt->active_tool].ti.deactivate) {
950       vt->tools[vt->active_tool].ti.deactivate(NULL, vt->tools[vt->active_tool].state);
951     }
952   }
953   if (t->ti.activate) {
954     t->ti.activate(vl, t->state);
955   }
956   vt->active_tool = tool;
957 }
958
959 static void toolbox_click (toolbox_tools_t *vt, GdkEventButton *event)
960 {
961   VikLayer *vl = vik_layers_panel_get_selected ( vt->vw->viking_vlp );
962   if (vt->active_tool != -1 && vt->tools[vt->active_tool].ti.click) {
963     vt->tools[vt->active_tool].ti.click(vl, event, vt->tools[vt->active_tool].state);
964   }
965 }
966
967 static void toolbox_move (toolbox_tools_t *vt, GdkEventButton *event)
968 {
969   VikLayer *vl = vik_layers_panel_get_selected ( vt->vw->viking_vlp );
970   if (vt->active_tool != -1 && vt->tools[vt->active_tool].ti.move) {
971     vt->tools[vt->active_tool].ti.move(vl, event, vt->tools[vt->active_tool].state);
972   }
973 }
974
975 static void toolbox_release (toolbox_tools_t *vt, GdkEventButton *event)
976 {
977   VikLayer *vl = vik_layers_panel_get_selected ( vt->vw->viking_vlp );
978   if (vt->active_tool != -1 && vt->tools[vt->active_tool].ti.release) {
979     vt->tools[vt->active_tool].ti.release(vl, event, vt->tools[vt->active_tool].state);
980   }
981 }
982 /** End tool management ************************************/
983
984
985
986 /* this function gets called whenever a toolbar tool is clicked */
987 static void menu_tool_cb ( GtkAction *old, GtkAction *a, VikWindow *vw )
988 {
989   /* White Magic, my friends ... White Magic... */
990   int i, j;
991
992   toolbox_activate(vw->vt, gtk_action_get_name(a));
993
994   if (!strcmp(gtk_action_get_name(a), "Zoom")) {
995     vw->current_tool = TOOL_ZOOM;
996   } 
997   else if (!strcmp(gtk_action_get_name(a), "Ruler")) {
998     vw->current_tool = TOOL_RULER;
999   }
1000   else {
1001     /* TODO: only enable tools from active layer */
1002     for (i=0; i<VIK_LAYER_NUM_TYPES; i++) {
1003       for ( j = 0; j < vik_layer_get_interface(i)->tools_count; j++ ) {
1004         if (!strcmp(vik_layer_get_interface(i)->tools[j].name, gtk_action_get_name(a))) {
1005           vw->current_tool = TOOL_LAYER;
1006           vw->tool_layer_id = i;
1007           vw->tool_tool_id = j;
1008         }
1009       }
1010     }
1011   }
1012   draw_status ( vw );
1013 }
1014
1015 static void window_set_filename ( VikWindow *vw, const gchar *filename )
1016 {
1017   gchar *title;
1018   if ( vw->filename )
1019     g_free ( vw->filename );
1020   if ( filename == NULL )
1021   {
1022     vw->filename = NULL;
1023     gtk_window_set_title ( GTK_WINDOW(vw), "Untitled" VIKING_TITLE );
1024   }
1025   else
1026   {
1027     vw->filename = g_strdup(filename);
1028     title = g_strconcat ( a_file_basename ( filename ), VIKING_TITLE, NULL );
1029     gtk_window_set_title ( GTK_WINDOW(vw), title );
1030     g_free ( title );
1031   }
1032 }
1033
1034 void vik_window_open_file ( VikWindow *vw, const gchar *filename, gboolean change_filename )
1035 {
1036   switch ( a_file_load ( vik_layers_panel_get_top_layer(vw->viking_vlp), vw->viking_vvp, filename ) )
1037   {
1038     case 0:
1039       a_dialog_error_msg ( GTK_WINDOW(vw), "The file you requested could not be opened." );
1040       break;
1041     case 1:
1042     {
1043       GtkWidget *mode_button;
1044       gchar *buttonname;
1045       if ( change_filename )
1046         window_set_filename ( vw, filename );
1047       switch ( vik_viewport_get_drawmode ( vw->viking_vvp ) ) {
1048         case VIK_VIEWPORT_DRAWMODE_UTM: buttonname = "/ui/MainMenu/View/ModeUTM"; break;
1049         case VIK_VIEWPORT_DRAWMODE_EXPEDIA: buttonname = "/ui/MainMenu/View/ModeExpedia"; break;
1050         case VIK_VIEWPORT_DRAWMODE_GOOGLE: buttonname = "/ui/MainMenu/View/ModeGoogle"; break;
1051         default: buttonname = "/ui/MainMenu/View/ModeKH";
1052       }
1053       mode_button = gtk_ui_manager_get_widget ( vw->uim, buttonname );
1054       g_assert ( mode_button );
1055       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. */
1056       gtk_check_menu_item_set_active ( GTK_CHECK_MENU_ITEM(mode_button), TRUE );
1057       vw->only_updating_coord_mode_ui = FALSE;
1058
1059       vik_layers_panel_change_coord_mode ( vw->viking_vlp, vik_viewport_get_coord_mode ( vw->viking_vvp ) );
1060     }
1061     default: draw_update ( vw );
1062   }
1063 }
1064
1065 static void load_file ( GtkAction *a, VikWindow *vw )
1066 {
1067   gboolean newwindow;
1068   if (!strcmp(gtk_action_get_name(a), "Open")) {
1069     newwindow = TRUE;
1070   } 
1071   else if (!strcmp(gtk_action_get_name(a), "Append")) {
1072     newwindow = FALSE;
1073   } 
1074   else {
1075     fprintf(stderr, "Houston we got a problem\n");
1076     return;
1077   }
1078     
1079   if ( ! vw->open_dia )
1080   {
1081     vw->open_dia = gtk_file_selection_new ("Please select a GPS data file to open. " );
1082     gtk_file_selection_set_select_multiple ( GTK_FILE_SELECTION(vw->open_dia), TRUE );
1083     gtk_window_set_transient_for ( GTK_WINDOW(vw->open_dia), GTK_WINDOW(vw) );
1084     gtk_window_set_destroy_with_parent ( GTK_WINDOW(vw->open_dia), TRUE );
1085   }
1086   if ( gtk_dialog_run ( GTK_DIALOG(vw->open_dia) ) == GTK_RESPONSE_OK )
1087   {
1088     gtk_widget_hide ( vw->open_dia );
1089 #ifdef VIKING_PROMPT_IF_MODIFIED
1090     if ( (vw->modified || vw->filename) && newwindow )
1091 #else
1092     if ( vw->filename && newwindow )
1093 #endif
1094       g_signal_emit ( G_OBJECT(vw), window_signals[VW_OPENWINDOW_SIGNAL], 0, gtk_file_selection_get_selections (GTK_FILE_SELECTION(vw->open_dia) ) );
1095     else {
1096       gchar **files = gtk_file_selection_get_selections (GTK_FILE_SELECTION(vw->open_dia) );
1097       gboolean change_fn = newwindow && (!files[1]); /* only change fn if one file */
1098       while ( *files ) {
1099         vik_window_open_file ( vw, *files, change_fn );
1100         files++;
1101       }
1102     }
1103   }
1104   else
1105     gtk_widget_hide ( vw->open_dia );
1106 }
1107
1108 static gboolean save_file_as ( GtkAction *a, VikWindow *vw )
1109 {
1110   gboolean rv = FALSE;
1111   const gchar *fn;
1112   if ( ! vw->save_dia )
1113   {
1114     vw->save_dia = gtk_file_selection_new ("Save as Viking File. " );
1115     gtk_window_set_transient_for ( GTK_WINDOW(vw->save_dia), GTK_WINDOW(vw) );
1116     gtk_window_set_destroy_with_parent ( GTK_WINDOW(vw->save_dia), TRUE );
1117   }
1118
1119   while ( gtk_dialog_run ( GTK_DIALOG(vw->save_dia) ) == GTK_RESPONSE_OK )
1120   {
1121     fn = gtk_file_selection_get_filename (GTK_FILE_SELECTION(vw->save_dia) );
1122     if ( access ( fn, F_OK ) != 0 || a_dialog_overwrite ( GTK_WINDOW(vw->save_dia), "The file \"%s\" exists, do you wish to overwrite it?", a_file_basename ( fn ) ) )
1123     {
1124       window_set_filename ( vw, fn );
1125       rv = window_save ( vw );
1126       vw->modified = FALSE;
1127       break;
1128     }
1129   }
1130   gtk_widget_hide ( vw->save_dia );
1131   return rv;
1132 }
1133
1134 static gboolean window_save ( VikWindow *vw )
1135 {
1136   if ( a_file_save ( vik_layers_panel_get_top_layer ( vw->viking_vlp ), vw->viking_vvp, vw->filename ) )
1137     return TRUE;
1138   else
1139   {
1140     a_dialog_error_msg ( GTK_WINDOW(vw), "The filename you requested could not be opened for writing." );
1141     return FALSE;
1142   }
1143 }
1144
1145 static gboolean save_file ( GtkAction *a, VikWindow *vw )
1146 {
1147   if ( ! vw->filename )
1148     return save_file_as ( NULL, vw );
1149   else
1150   {
1151     vw->modified = FALSE;
1152     return window_save ( vw );
1153   }
1154 }
1155
1156 static void acquire_from_gps ( GtkAction *a, VikWindow *vw )
1157 {
1158   a_acquire(vw, vw->viking_vlp, vw->viking_vvp, &vik_datasource_gps_interface );
1159 }
1160
1161 static void acquire_from_google ( GtkAction *a, VikWindow *vw )
1162 {
1163   a_acquire(vw, vw->viking_vlp, vw->viking_vvp, &vik_datasource_google_interface );
1164 }
1165
1166 static void acquire_from_gc ( GtkAction *a, VikWindow *vw )
1167 {
1168   a_acquire(vw, vw->viking_vlp, vw->viking_vvp, &vik_datasource_gc_interface );
1169 }
1170
1171 static void goto_address( GtkAction *a, VikWindow *vw)
1172 {
1173   a_google_search(vw, vw->viking_vlp, vw->viking_vvp);
1174 }
1175
1176 static void clear_cb ( GtkAction *a, VikWindow *vw )
1177 {
1178   vik_layers_panel_clear ( vw->viking_vlp );
1179   window_set_filename ( vw, NULL );
1180   draw_update ( vw );
1181 }
1182
1183 static void window_close ( GtkAction *a, VikWindow *vw )
1184 {
1185   if ( ! delete_event ( vw ) )
1186     gtk_widget_destroy ( GTK_WIDGET(vw) );
1187 }
1188
1189 static gboolean save_file_and_exit ( GtkAction *a, VikWindow *vw )
1190 {
1191   if (save_file( NULL, vw)) {
1192     window_close( NULL, vw);
1193     return(TRUE);
1194   }
1195   else
1196     return(FALSE);
1197 }
1198
1199 static void zoom_to_cb ( GtkAction *a, VikWindow *vw )
1200 {
1201   gdouble xmpp = vik_viewport_get_xmpp ( vw->viking_vvp ), ympp = vik_viewport_get_ympp ( vw->viking_vvp );
1202   if ( a_dialog_custom_zoom ( GTK_WINDOW(vw), &xmpp, &ympp ) )
1203   {
1204     vik_viewport_set_xmpp ( vw->viking_vvp, xmpp );
1205     vik_viewport_set_ympp ( vw->viking_vvp, ympp );
1206     draw_update ( vw );
1207   }
1208 }
1209
1210 static void save_image_file ( VikWindow *vw, const gchar *fn, guint w, guint h, gdouble zoom, gboolean save_as_png )
1211 {
1212   /* more efficient way: stuff draws directly to pixbuf (fork viewport) */
1213   GdkPixbuf *pixbuf_to_save;
1214   gdouble old_xmpp, old_ympp;
1215   GError *error = NULL;
1216
1217   /* backup old zoom & set new */
1218   old_xmpp = vik_viewport_get_xmpp ( vw->viking_vvp );
1219   old_ympp = vik_viewport_get_ympp ( vw->viking_vvp );
1220   vik_viewport_set_zoom ( vw->viking_vvp, zoom );
1221
1222   /* reset width and height: */
1223   vik_viewport_configure_manually ( vw->viking_vvp, w, h );
1224
1225   /* draw all layers */
1226   draw_redraw ( vw );
1227
1228   /* save buffer as file. */
1229   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);
1230   gdk_pixbuf_save ( pixbuf_to_save, fn, save_as_png ? "png" : "jpeg", &error, NULL );
1231   if (error)
1232   {
1233     fprintf(stderr, "Unable to write to file %s: %s", fn, error->message );
1234     g_error_free (error);
1235   }
1236   g_object_unref ( G_OBJECT(pixbuf_to_save) );
1237
1238   /* pretend like nothing happened ;) */
1239   vik_viewport_set_xmpp ( vw->viking_vvp, old_xmpp );
1240   vik_viewport_set_ympp ( vw->viking_vvp, old_ympp );
1241   vik_viewport_configure ( vw->viking_vvp );
1242   draw_update ( vw );
1243 }
1244
1245 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 )
1246 {
1247   gulong size = sizeof(gchar) * (strlen(fn) + 15);
1248   gchar *name_of_file = g_malloc ( size );
1249   guint x = 1, y = 1;
1250   struct UTM utm_orig, utm;
1251
1252   /* *** copied from above *** */
1253   GdkPixbuf *pixbuf_to_save;
1254   gdouble old_xmpp, old_ympp;
1255   GError *error = NULL;
1256
1257   /* backup old zoom & set new */
1258   old_xmpp = vik_viewport_get_xmpp ( vw->viking_vvp );
1259   old_ympp = vik_viewport_get_ympp ( vw->viking_vvp );
1260   vik_viewport_set_zoom ( vw->viking_vvp, zoom );
1261
1262   /* reset width and height: do this only once for all images (same size) */
1263   vik_viewport_configure_manually ( vw->viking_vvp, w, h );
1264   /* *** end copy from above *** */
1265
1266   g_assert ( vik_viewport_get_coord_mode ( vw->viking_vvp ) == VIK_COORD_UTM );
1267
1268   make_dir(fn);
1269
1270   utm_orig = *((const struct UTM *)vik_viewport_get_center ( vw->viking_vvp ));
1271
1272   for ( y = 1; y <= tiles_h; y++ )
1273   {
1274     for ( x = 1; x <= tiles_w; x++ )
1275     {
1276       g_snprintf ( name_of_file, size, "%s%cy%d-x%d.%s", fn, VIKING_FILE_SEP, y, x, save_as_png ? "png" : "jpg" );
1277       utm = utm_orig;
1278       if ( tiles_w & 0x1 )
1279         utm.easting += ((gdouble)x - ceil(((gdouble)tiles_w)/2)) * (w*zoom);
1280       else
1281         utm.easting += ((gdouble)x - (((gdouble)tiles_w)+1)/2) * (w*zoom);
1282       if ( tiles_h & 0x1 ) /* odd */
1283         utm.northing -= ((gdouble)y - ceil(((gdouble)tiles_h)/2)) * (h*zoom);
1284       else /* even */
1285         utm.northing -= ((gdouble)y - (((gdouble)tiles_h)+1)/2) * (h*zoom);
1286
1287       /* move to correct place. */
1288       vik_viewport_set_center_utm ( vw->viking_vvp, &utm );
1289
1290       draw_redraw ( vw );
1291
1292       /* save buffer as file. */
1293       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);
1294       gdk_pixbuf_save ( pixbuf_to_save, name_of_file, save_as_png ? "png" : "jpeg", &error, NULL );
1295       if (error)
1296       {
1297         fprintf(stderr, "Unable to write to file %s: %s", name_of_file, error->message );
1298         g_error_free (error);
1299       }
1300
1301       g_object_unref ( G_OBJECT(pixbuf_to_save) );
1302     }
1303   }
1304
1305   vik_viewport_set_center_utm ( vw->viking_vvp, &utm_orig );
1306   vik_viewport_set_xmpp ( vw->viking_vvp, old_xmpp );
1307   vik_viewport_set_ympp ( vw->viking_vvp, old_ympp );
1308   vik_viewport_configure ( vw->viking_vvp );
1309   draw_update ( vw );
1310
1311   g_free ( name_of_file );
1312 }
1313
1314 static void draw_to_image_file_current_window_cb(GtkWidget* widget,GdkEventButton *event,gpointer *pass_along)
1315 {
1316   VikWindow *vw = VIK_WINDOW(pass_along[0]);
1317   GtkSpinButton *width_spin = GTK_SPIN_BUTTON(pass_along[1]), *height_spin = GTK_SPIN_BUTTON(pass_along[2]);
1318   GtkSpinButton *zoom_spin = GTK_SPIN_BUTTON(pass_along[3]);
1319   gdouble width_min, width_max, height_min, height_max;
1320   gint width, height;
1321
1322   gtk_spin_button_get_range ( width_spin, &width_min, &width_max );
1323   gtk_spin_button_get_range ( height_spin, &height_min, &height_max );
1324
1325   /* TODO: support for xzoom and yzoom values */
1326   width = vik_viewport_get_width ( vw->viking_vvp ) * vik_viewport_get_xmpp ( vw->viking_vvp ) / gtk_spin_button_get_value ( zoom_spin );
1327   height = vik_viewport_get_height ( vw->viking_vvp ) * vik_viewport_get_xmpp ( vw->viking_vvp ) / gtk_spin_button_get_value ( zoom_spin );
1328
1329   if ( width > width_max || width < width_min || height > height_max || height < height_min )
1330     a_dialog_info_msg ( GTK_WINDOW(vw), "Viewable region outside allowable pixel size bounds for image. Clipping width/height values." );
1331
1332   gtk_spin_button_set_value ( width_spin, width );
1333   gtk_spin_button_set_value ( height_spin, height );
1334 }
1335
1336 static void draw_to_image_file_total_area_cb (GtkSpinButton *spinbutton, gpointer *pass_along)
1337 {
1338   GtkSpinButton *width_spin = GTK_SPIN_BUTTON(pass_along[1]), *height_spin = GTK_SPIN_BUTTON(pass_along[2]);
1339   GtkSpinButton *zoom_spin = GTK_SPIN_BUTTON(pass_along[3]);
1340   gchar *label_text;
1341   gdouble w, h;
1342   w = gtk_spin_button_get_value(width_spin) * gtk_spin_button_get_value(zoom_spin);
1343   h = gtk_spin_button_get_value(height_spin) * gtk_spin_button_get_value(zoom_spin);
1344   if (pass_along[4]) /* save many images; find TOTAL area covered */
1345   {
1346     w *= gtk_spin_button_get_value(GTK_SPIN_BUTTON(pass_along[4]));
1347     h *= gtk_spin_button_get_value(GTK_SPIN_BUTTON(pass_along[5]));
1348   }
1349   label_text = g_strdup_printf ( "Total area: %ldm x %ldm (%.3f sq. km)", (glong)w, (glong)h, (w*h/1000000));
1350   gtk_label_set_text(GTK_LABEL(pass_along[6]), label_text);
1351   g_free ( label_text );
1352 }
1353
1354 static void draw_to_image_file ( VikWindow *vw, const gchar *fn, gboolean one_image_only )
1355 {
1356   /* todo: default for answers inside VikWindow or static (thruout instance) */
1357   GtkWidget *dialog = gtk_dialog_new_with_buttons ( "Save to Image File", GTK_WINDOW(vw),
1358                                                   GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
1359                                                   GTK_STOCK_CANCEL,
1360                                                   GTK_RESPONSE_REJECT,
1361                                                   GTK_STOCK_OK,
1362                                                   GTK_RESPONSE_ACCEPT,
1363                                                   0 );
1364   GtkWidget *width_label, *width_spin, *height_label, *height_spin;
1365   GtkWidget *png_radio, *jpeg_radio;
1366   GtkWidget *current_window_button;
1367   gpointer current_window_pass_along[7];
1368   GtkWidget *zoom_label, *zoom_spin;
1369   GtkWidget *total_size_label;
1370
1371   /* only used if (!one_image_only) */
1372   GtkWidget *tiles_width_spin = NULL, *tiles_height_spin = NULL;
1373
1374
1375   width_label = gtk_label_new ( "Width (pixels):" );
1376   width_spin = gtk_spin_button_new ( GTK_ADJUSTMENT(gtk_adjustment_new ( vw->draw_image_width, 10, 5000, 10, 100, 0 )), 10, 0 );
1377   height_label = gtk_label_new ( "Height (pixels):" );
1378   height_spin = gtk_spin_button_new ( GTK_ADJUSTMENT(gtk_adjustment_new ( vw->draw_image_height, 10, 5000, 10, 100, 0 )), 10, 0 );
1379
1380   zoom_label = gtk_label_new ( "Zoom (meters per pixel):" );
1381   /* TODO: separate xzoom and yzoom factors */
1382   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);
1383
1384   total_size_label = gtk_label_new ( NULL );
1385
1386   current_window_button = gtk_button_new_with_label ( "Area in current viewable window" );
1387   current_window_pass_along [0] = vw;
1388   current_window_pass_along [1] = width_spin;
1389   current_window_pass_along [2] = height_spin;
1390   current_window_pass_along [3] = zoom_spin;
1391   current_window_pass_along [4] = NULL; /* used for one_image_only != 1 */
1392   current_window_pass_along [5] = NULL;
1393   current_window_pass_along [6] = total_size_label;
1394   g_signal_connect ( G_OBJECT(current_window_button), "button_press_event", G_CALLBACK(draw_to_image_file_current_window_cb), current_window_pass_along );
1395
1396   png_radio = gtk_radio_button_new_with_label ( NULL, "Save as PNG" );
1397   jpeg_radio = gtk_radio_button_new_with_label_from_widget ( GTK_RADIO_BUTTON(png_radio), "Save as JPEG" );
1398
1399   if ( ! vw->draw_image_save_as_png )
1400     gtk_toggle_button_set_active ( GTK_TOGGLE_BUTTON(jpeg_radio), TRUE );
1401
1402   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), width_label, FALSE, FALSE, 0);
1403   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), width_spin, FALSE, FALSE, 0);
1404   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), height_label, FALSE, FALSE, 0);
1405   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), height_spin, FALSE, FALSE, 0);
1406   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), current_window_button, FALSE, FALSE, 0);
1407   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), png_radio, FALSE, FALSE, 0);
1408   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), jpeg_radio, FALSE, FALSE, 0);
1409   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), zoom_label, FALSE, FALSE, 0);
1410   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), zoom_spin, FALSE, FALSE, 0);
1411
1412   if ( ! one_image_only )
1413   {
1414     GtkWidget *tiles_width_label, *tiles_height_label;
1415
1416
1417     tiles_width_label = gtk_label_new ( "East-west image tiles:" );
1418     tiles_width_spin = gtk_spin_button_new ( GTK_ADJUSTMENT(gtk_adjustment_new ( 5, 1, 10, 1, 100, 0 )), 1, 0 );
1419     tiles_height_label = gtk_label_new ( "North-south image tiles:" );
1420     tiles_height_spin = gtk_spin_button_new ( GTK_ADJUSTMENT(gtk_adjustment_new ( 5, 1, 10, 1, 100, 0 )), 1, 0 );
1421     gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), tiles_width_label, FALSE, FALSE, 0);
1422     gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), tiles_width_spin, FALSE, FALSE, 0);
1423     gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), tiles_height_label, FALSE, FALSE, 0);
1424     gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), tiles_height_spin, FALSE, FALSE, 0);
1425
1426     current_window_pass_along [4] = tiles_width_spin;
1427     current_window_pass_along [5] = tiles_height_spin;
1428     g_signal_connect ( G_OBJECT(tiles_width_spin), "value-changed", G_CALLBACK(draw_to_image_file_total_area_cb), current_window_pass_along );
1429     g_signal_connect ( G_OBJECT(tiles_height_spin), "value-changed", G_CALLBACK(draw_to_image_file_total_area_cb), current_window_pass_along );
1430   }
1431   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), total_size_label, FALSE, FALSE, 0);
1432   g_signal_connect ( G_OBJECT(width_spin), "value-changed", G_CALLBACK(draw_to_image_file_total_area_cb), current_window_pass_along );
1433   g_signal_connect ( G_OBJECT(height_spin), "value-changed", G_CALLBACK(draw_to_image_file_total_area_cb), current_window_pass_along );
1434   g_signal_connect ( G_OBJECT(zoom_spin), "value-changed", G_CALLBACK(draw_to_image_file_total_area_cb), current_window_pass_along );
1435
1436   draw_to_image_file_total_area_cb ( NULL, current_window_pass_along ); /* set correct size info now */
1437
1438   gtk_widget_show_all ( GTK_DIALOG(dialog)->vbox );
1439
1440   if ( gtk_dialog_run ( GTK_DIALOG(dialog) ) == GTK_RESPONSE_ACCEPT )
1441   {
1442     gtk_widget_hide ( GTK_WIDGET(dialog) );
1443     if ( one_image_only )
1444       save_image_file ( vw, fn, 
1445                       vw->draw_image_width = gtk_spin_button_get_value_as_int ( GTK_SPIN_BUTTON(width_spin) ),
1446                       vw->draw_image_height = gtk_spin_button_get_value_as_int ( GTK_SPIN_BUTTON(height_spin) ),
1447                       gtk_spin_button_get_value ( GTK_SPIN_BUTTON(zoom_spin) ), /* do not save this value, default is current zoom */
1448                       vw->draw_image_save_as_png = gtk_toggle_button_get_active ( GTK_TOGGLE_BUTTON(png_radio) ) );
1449     else {
1450       if ( vik_viewport_get_coord_mode(vw->viking_vvp) == VIK_COORD_UTM )
1451         save_image_dir ( vw, fn, 
1452                        vw->draw_image_width = gtk_spin_button_get_value_as_int ( GTK_SPIN_BUTTON(width_spin) ),
1453                        vw->draw_image_height = gtk_spin_button_get_value_as_int ( GTK_SPIN_BUTTON(height_spin) ),
1454                        gtk_spin_button_get_value ( GTK_SPIN_BUTTON(zoom_spin) ), /* do not save this value, default is current zoom */
1455                        vw->draw_image_save_as_png = gtk_toggle_button_get_active ( GTK_TOGGLE_BUTTON(png_radio) ),
1456                        gtk_spin_button_get_value ( GTK_SPIN_BUTTON(tiles_width_spin) ),
1457                        gtk_spin_button_get_value ( GTK_SPIN_BUTTON(tiles_height_spin) ) );
1458       else
1459         a_dialog_error_msg ( GTK_WINDOW(vw), "You must be in UTM mode to use this feature" );
1460     }
1461   }
1462   gtk_widget_destroy ( GTK_WIDGET(dialog) );
1463 }
1464
1465
1466 static void draw_to_image_file_cb ( GtkAction *a, VikWindow *vw )
1467 {
1468   GtkWidget *file_selector;
1469   const gchar *fn;
1470   file_selector = gtk_file_selection_new ("Save Image");
1471
1472   while ( gtk_dialog_run ( GTK_DIALOG(file_selector) ) == GTK_RESPONSE_OK )
1473   {
1474     fn = gtk_file_selection_get_filename (GTK_FILE_SELECTION(file_selector) );
1475     if ( access ( fn, F_OK ) != 0 || a_dialog_overwrite ( GTK_WINDOW(file_selector), "The file \"%s\" exists, do you wish to overwrite it?", a_file_basename ( fn ) ) )
1476     {
1477       gtk_widget_hide ( file_selector );
1478       draw_to_image_file ( vw, fn, TRUE );
1479       break;
1480     }
1481   }
1482   gtk_widget_destroy ( file_selector );
1483 }
1484
1485 static void draw_to_image_dir_cb ( GtkAction *a, VikWindow *vw )
1486 {
1487   GtkWidget *file_selector;
1488   const gchar *fn;
1489   file_selector = gtk_file_selection_new ("Choose a name for a new directory to hold images");
1490
1491   while ( gtk_dialog_run ( GTK_DIALOG(file_selector) ) == GTK_RESPONSE_OK )
1492   {
1493     fn = gtk_file_selection_get_filename (GTK_FILE_SELECTION(file_selector) );
1494     if ( access ( fn, F_OK ) == 0 )
1495       a_dialog_info_msg_extra ( GTK_WINDOW(file_selector), "The file %s exists. Please choose a name for a new directory to hold images in that does not exist.", a_file_basename(fn) );
1496     else
1497     {
1498       gtk_widget_hide ( file_selector );
1499       draw_to_image_file ( vw, fn, FALSE );
1500       break;
1501     }
1502   }
1503   gtk_widget_destroy ( file_selector );
1504 }
1505
1506 /* really a misnomer: changes coord mode (actual coordinates) AND/OR draw mode (viewport only) */
1507 static void window_change_coord_mode_cb ( GtkAction *old_a, GtkAction *a, VikWindow *vw )
1508 {
1509   VikViewportDrawMode drawmode;
1510   if (!strcmp(gtk_action_get_name(a), "ModeUTM")) {
1511     drawmode = VIK_VIEWPORT_DRAWMODE_UTM;
1512   }
1513   else if (!strcmp(gtk_action_get_name(a), "ModeExpedia")) {
1514     drawmode = VIK_VIEWPORT_DRAWMODE_EXPEDIA;
1515   }
1516   else if (!strcmp(gtk_action_get_name(a), "ModeGoogle")) {
1517     drawmode = VIK_VIEWPORT_DRAWMODE_GOOGLE;
1518   }
1519   else if (!strcmp(gtk_action_get_name(a), "ModeKH")) {
1520     drawmode = VIK_VIEWPORT_DRAWMODE_KH;
1521   }
1522   else if (!strcmp(gtk_action_get_name(a), "ModeMercator")) {
1523     drawmode = VIK_VIEWPORT_DRAWMODE_MERCATOR;
1524   }
1525   else {
1526     fprintf(stderr, "Houston, we got a problem!\n");
1527     return;
1528   }
1529
1530   if ( !vw->only_updating_coord_mode_ui )
1531   {
1532     VikViewportDrawMode olddrawmode = vik_viewport_get_drawmode ( vw->viking_vvp );
1533     if ( olddrawmode != drawmode )
1534     {
1535       /* this takes care of coord mode too */
1536       vik_viewport_set_drawmode ( vw->viking_vvp, drawmode );
1537       if ( drawmode == VIK_VIEWPORT_DRAWMODE_UTM ) {
1538         vik_layers_panel_change_coord_mode ( vw->viking_vlp, VIK_COORD_UTM );
1539       } else if ( olddrawmode == VIK_VIEWPORT_DRAWMODE_UTM ) {
1540         vik_layers_panel_change_coord_mode ( vw->viking_vlp, VIK_COORD_LATLON );
1541       }
1542       draw_update ( vw );
1543     }
1544   }
1545 }
1546
1547 static void set_draw_scale ( GtkAction *a, VikWindow *vw )
1548 {
1549   vik_viewport_set_draw_scale ( vw->viking_vvp, !vik_viewport_get_draw_scale(vw->viking_vvp) );
1550   draw_update ( vw );
1551 }
1552
1553 static void set_bg_color ( GtkAction *a, VikWindow *vw )
1554 {
1555   GtkWidget *colorsd = gtk_color_selection_dialog_new ("Choose a background color");
1556   GdkColor *color = vik_viewport_get_background_gdkcolor ( vw->viking_vvp );
1557   gtk_color_selection_set_previous_color ( GTK_COLOR_SELECTION(GTK_COLOR_SELECTION_DIALOG(colorsd)->colorsel), color );
1558   gtk_color_selection_set_current_color ( GTK_COLOR_SELECTION(GTK_COLOR_SELECTION_DIALOG(colorsd)->colorsel), color );
1559   if ( gtk_dialog_run ( GTK_DIALOG(colorsd) ) == GTK_RESPONSE_OK )
1560   {
1561     gtk_color_selection_get_current_color ( GTK_COLOR_SELECTION(GTK_COLOR_SELECTION_DIALOG(colorsd)->colorsel), color );
1562     vik_viewport_set_background_gdkcolor ( vw->viking_vvp, color );
1563     draw_update ( vw );
1564   }
1565   g_free ( color );
1566   gtk_widget_destroy ( colorsd );
1567 }
1568
1569
1570
1571 /***********************************************************************************************
1572  ** GUI Creation
1573  ***********************************************************************************************/
1574
1575 static GtkActionEntry entries[] = {
1576   { "File", NULL, "_File", 0, 0, 0 },
1577   { "Edit", NULL, "_Edit", 0, 0, 0 },
1578   { "View", NULL, "_View", 0, 0, 0 },
1579   { "SetZoom", NULL, "_Zoom", 0, 0, 0 },
1580   { "Layers", NULL, "_Layers", 0, 0, 0 },
1581   { "Tools", NULL, "_Tools", 0, 0, 0 },
1582   { "Help", NULL, "_Help", 0, 0, 0 },
1583
1584   { "New",       GTK_STOCK_NEW,          "_New",                          "<control>N", "New file",                                     (GCallback)newwindow_cb          },
1585   { "Open",      GTK_STOCK_OPEN,         "_Open",                         "<control>O", "Open a file",                                  (GCallback)load_file             },
1586   { "Append",    GTK_STOCK_ADD,          "A_ppend File",                  NULL,         "Append data from a different file",            (GCallback)load_file             },
1587   { "Acquire", NULL, "A_cquire", 0, 0, 0 },
1588   { "AcquireGPS",   NULL,                "From _GPS",                     NULL,         "Transfer data from a GPS device",              (GCallback)acquire_from_gps      },
1589   { "AcquireGoogle",   NULL,             "Google _Directions",            NULL,         "Get driving directions from Google",           (GCallback)acquire_from_google   },
1590   { "AcquireGC",   NULL,                 "Geo_caches",                    NULL,         "Get Geocaches from geocaching.com",            (GCallback)acquire_from_gc       },
1591   { "Save",      GTK_STOCK_SAVE,         "_Save",                         "<control>S", "Save the file",                                (GCallback)save_file             },
1592   { "SaveAs",    GTK_STOCK_SAVE_AS,      "Save _As",                      NULL,         "Save the file under different name",           (GCallback)save_file_as          },
1593   { "GenImg",    GTK_STOCK_CLEAR,        "_Generate Image File",          NULL,         "Save a snapshot of the workspace into a file", (GCallback)draw_to_image_file_cb },
1594   { "GenImgDir", GTK_STOCK_DND_MULTIPLE, "Generate _Directory of Images", NULL,         "FIXME:IMGDIR",                                 (GCallback)draw_to_image_dir_cb  },
1595   { "Exit",      GTK_STOCK_QUIT,         "E_xit",                         "<control>W", "Exit the program",                             (GCallback)window_close          },
1596   { "SaveExit",  GTK_STOCK_QUIT,         "Save and Exit",                 NULL, "Save and Exit the program",                             (GCallback)save_file_and_exit          },
1597
1598   { "GoogleMapsSearch",   GTK_STOCK_GO_FORWARD,                 "Go To Google Maps location",                     NULL,         "Get location using Google Maps search",            (GCallback)goto_address       },
1599   { "GotoLL",    GTK_STOCK_QUIT,         "_Go to Lat\\/Lon...",           NULL,         "Go to arbitrary lat\\/lon coordinate",         (GCallback)draw_goto_cb          },
1600   { "GotoUTM",   GTK_STOCK_QUIT,         "Go to UTM...",                  NULL,         "Go to arbitrary UTM coordinate",               (GCallback)draw_goto_cb          },
1601   { "SetBGColor",GTK_STOCK_SELECT_COLOR, "Set Background Color...",       NULL,         NULL,                                           (GCallback)set_bg_color          },
1602   { "ZoomIn",    GTK_STOCK_ZOOM_IN,      "Zoom _In",                   "<control>plus", NULL,                                           (GCallback)draw_zoom_cb          },
1603   { "ZoomOut",   GTK_STOCK_ZOOM_OUT,     "Zoom _Out",                 "<control>minus", NULL,                                           (GCallback)draw_zoom_cb          },
1604   { "ZoomTo",    GTK_STOCK_ZOOM_FIT,     "Zoom _To",               "<control><shift>Z", NULL,                                           (GCallback)zoom_to_cb            },
1605   { "Zoom0.25",  NULL,                   "0.25",                          NULL,         NULL,                                           (GCallback)draw_zoom_cb          },
1606   { "Zoom0.5",   NULL,                   "0.5",                           NULL,         NULL,                                           (GCallback)draw_zoom_cb          },
1607   { "Zoom1",     NULL,                   "1",                             NULL,         NULL,                                           (GCallback)draw_zoom_cb          },
1608   { "Zoom2",     NULL,                   "2",                             NULL,         NULL,                                           (GCallback)draw_zoom_cb          },
1609   { "Zoom4",     NULL,                   "4",                             NULL,         NULL,                                           (GCallback)draw_zoom_cb          },
1610   { "Zoom8",     NULL,                   "8",                             NULL,         NULL,                                           (GCallback)draw_zoom_cb          },
1611   { "Zoom16",    NULL,                   "16",                            NULL,         NULL,                                           (GCallback)draw_zoom_cb          },
1612   { "Zoom32",    NULL,                   "32",                            NULL,         NULL,                                           (GCallback)draw_zoom_cb          },
1613   { "Zoom64",    NULL,                   "64",                            NULL,         NULL,                                           (GCallback)draw_zoom_cb          },
1614   { "Zoom128",   NULL,                   "128",                           NULL,         NULL,                                           (GCallback)draw_zoom_cb          },
1615   { "BGJobs",    GTK_STOCK_EXECUTE,      "Background _Jobs",              NULL,         NULL,                                           (GCallback)a_background_show_window },
1616
1617   { "Cut",       GTK_STOCK_CUT,          "Cu_t",                          NULL,         NULL,                                           (GCallback)menu_cut_layer_cb     },
1618   { "Copy",      GTK_STOCK_COPY,         "_Copy",                         NULL,         NULL,                                           (GCallback)menu_copy_layer_cb    },
1619   { "Paste",     GTK_STOCK_PASTE,        "_Paste",                        NULL,         NULL,                                           (GCallback)menu_paste_layer_cb   },
1620   { "Delete",    GTK_STOCK_DELETE,       "_Delete",                       NULL,         NULL,                                           (GCallback)menu_delete_layer_cb  },
1621   { "DeleteAll", NULL,                   "Delete All",                    NULL,         NULL,                                           (GCallback)clear_cb              },
1622   { "Properties",GTK_STOCK_PROPERTIES,   "_Properties",                   NULL,         NULL,                                           (GCallback)menu_properties_cb    },
1623
1624   { "About",     GTK_STOCK_ABOUT,        "_About",                        NULL,         NULL,                                           (GCallback)help_about_cb    },
1625 };
1626
1627 /* Radio items */
1628 static GtkRadioActionEntry mode_entries[] = {
1629   { "ModeUTM",         NULL,         "_UTM Mode",               "<control>u", NULL, 0 },
1630   { "ModeExpedia",     NULL,         "_Expedia Mode",           "<control>e", NULL, 1 },
1631   { "ModeGoogle",      NULL,         "_Old Google Mode",        "<control>o", NULL, 2 },
1632   { "ModeKH",          NULL,         "Old _KH Mode",            "<control>k", NULL, 3 },
1633   { "ModeMercator",    NULL,         "_Google Mode",            "<control>g", NULL, 4 }
1634 };
1635
1636 static GtkRadioActionEntry tool_entries[] = {
1637   { "Zoom",      "vik-icon-zoom",        "_Zoom",                         "<control><shift>Z", "Zoom Tool",  0 },
1638   { "Ruler",     "vik-icon-ruler",       "_Ruler",                        "<control><shift>R", "Ruler Tool", 1 }
1639 };
1640
1641 static GtkToggleActionEntry toggle_entries[] = {
1642   { "ShowScale", NULL,                   "Show Scale",                    NULL,         NULL,                                           (GCallback)set_draw_scale, TRUE   },
1643 };
1644
1645 #include "menu.xml.h"
1646 static void window_create_ui( VikWindow *window )
1647 {
1648   GtkUIManager *uim;
1649   GtkActionGroup *action_group;
1650   GtkAccelGroup *accel_group;
1651   GError *error;
1652   guint i, j, mid;
1653   GtkIconFactory *icon_factory;
1654   GtkIconSet *icon_set; 
1655   GtkRadioActionEntry *tools = NULL, *radio;
1656   guint ntools;
1657   
1658   uim = gtk_ui_manager_new ();
1659   window->uim = uim;
1660
1661   toolbox_add_tool(window->vt, &ruler_tool);
1662   toolbox_add_tool(window->vt, &zoom_tool);
1663
1664   error = NULL;
1665   if (!(mid = gtk_ui_manager_add_ui_from_string (uim, menu_xml, -1, &error))) {
1666     g_error_free (error);
1667     exit (1);
1668   }
1669
1670   action_group = gtk_action_group_new ("MenuActions");
1671   gtk_action_group_add_actions (action_group, entries, G_N_ELEMENTS (entries), window);
1672   gtk_action_group_add_toggle_actions (action_group, toggle_entries, G_N_ELEMENTS (toggle_entries), window);
1673   gtk_action_group_add_radio_actions (action_group, mode_entries, G_N_ELEMENTS (mode_entries), 0, (GCallback)window_change_coord_mode_cb, window);
1674
1675   icon_factory = gtk_icon_factory_new ();
1676   gtk_icon_factory_add_default (icon_factory); 
1677
1678   register_vik_icons(icon_factory);
1679
1680   ntools = 0;
1681   for (i=0; i<G_N_ELEMENTS(tool_entries); i++) {
1682       tools = g_renew(GtkRadioActionEntry, tools, ntools+1);
1683       radio = &tools[ntools];
1684       ntools++;
1685       *radio = tool_entries[i];
1686       radio->value = ntools;
1687   }  
1688
1689   for (i=0; i<VIK_LAYER_NUM_TYPES; i++) {
1690     GtkActionEntry action;
1691     gtk_ui_manager_add_ui(uim, mid,  "/ui/MainMenu/Layers/", 
1692                           vik_layer_get_interface(i)->name,
1693                           vik_layer_get_interface(i)->name,
1694                           GTK_UI_MANAGER_MENUITEM, FALSE);
1695
1696     icon_set = gtk_icon_set_new_from_pixbuf (gdk_pixbuf_from_pixdata (vik_layer_get_interface(i)->icon, FALSE, NULL ));
1697     gtk_icon_factory_add (icon_factory, vik_layer_get_interface(i)->name, icon_set);
1698     gtk_icon_set_unref (icon_set);
1699
1700     action.name = vik_layer_get_interface(i)->name;
1701     action.stock_id = vik_layer_get_interface(i)->name;
1702     action.label = g_strdup_printf("New %s Layer", vik_layer_get_interface(i)->name);
1703     action.accelerator = NULL;
1704     action.tooltip = NULL;
1705     action.callback = (GCallback)menu_addlayer_cb;
1706     gtk_action_group_add_actions(action_group, &action, 1, window);
1707
1708     if ( vik_layer_get_interface(i)->tools_count ) {
1709       gtk_ui_manager_add_ui(uim, mid,  "/ui/MainMenu/Tools/", vik_layer_get_interface(i)->name, NULL, GTK_UI_MANAGER_SEPARATOR, FALSE);
1710       gtk_ui_manager_add_ui(uim, mid,  "/ui/MainToolbar/ToolItems/", vik_layer_get_interface(i)->name, NULL, GTK_UI_MANAGER_SEPARATOR, FALSE);
1711     }
1712
1713     for ( j = 0; j < vik_layer_get_interface(i)->tools_count; j++ ) {
1714       tools = g_renew(GtkRadioActionEntry, tools, ntools+1);
1715       radio = &tools[ntools];
1716       ntools++;
1717       
1718       gtk_ui_manager_add_ui(uim, mid,  "/ui/MainMenu/Tools", 
1719                             vik_layer_get_interface(i)->tools[j].name,
1720                             vik_layer_get_interface(i)->tools[j].name,
1721                             GTK_UI_MANAGER_MENUITEM, FALSE);
1722       gtk_ui_manager_add_ui(uim, mid,  "/ui/MainToolbar/ToolItems", 
1723                             vik_layer_get_interface(i)->tools[j].name,
1724                             vik_layer_get_interface(i)->tools[j].name,
1725                             GTK_UI_MANAGER_TOOLITEM, FALSE);
1726
1727       toolbox_add_tool(window->vt, &(vik_layer_get_interface(i)->tools[j]));
1728
1729       radio->name = vik_layer_get_interface(i)->tools[j].name;
1730       radio->stock_id = vik_layer_get_interface(i)->tools[j].name,
1731       radio->label = vik_layer_get_interface(i)->tools[j].name;
1732       radio->accelerator = NULL;
1733       radio->tooltip = vik_layer_get_interface(i)->tools[j].name;
1734       radio->value = ntools;
1735     }
1736   }
1737   g_object_unref (icon_factory);
1738
1739   gtk_action_group_add_radio_actions(action_group, tools, ntools, 0, (GCallback)menu_tool_cb, window);
1740   g_free(tools);
1741
1742   gtk_ui_manager_insert_action_group (uim, action_group, 0);
1743
1744   for (i=0; i<VIK_LAYER_NUM_TYPES; i++) {
1745     for ( j = 0; j < vik_layer_get_interface(i)->tools_count; j++ ) {
1746       GtkAction *action = gtk_action_group_get_action(action_group,
1747                             vik_layer_get_interface(i)->tools[j].name);
1748       g_object_set(action, "sensitive", FALSE, NULL);
1749     }
1750   }
1751   window->action_group = action_group;
1752
1753   accel_group = gtk_ui_manager_get_accel_group (uim);
1754   gtk_window_add_accel_group (GTK_WINDOW (window), accel_group);
1755   gtk_ui_manager_ensure_update (uim);
1756 }
1757
1758
1759
1760 #include "icons/icons.h"
1761 static struct { 
1762   const GdkPixdata *data;
1763   gchar *stock_id;
1764 } stock_icons[] = {
1765   { &addtr_18,          "Create Track"      },
1766   { &edtr_18,           "Edit Trackpoint"   },
1767   { &addwp_18,          "Create Waypoint"   },
1768   { &edwp_18,           "Edit Waypoint"     },
1769   { &zoom_18,           "vik-icon-zoom"     },
1770   { &ruler_18,          "vik-icon-ruler"    },
1771   { &geozoom_18,        "Georef Zoom Tool"  },
1772   { &geomove_18,        "Georef Move Map"   },
1773   { &mapdl_18,          "Maps Download"     },
1774   { &showpic_18,        "Show Picture"      },
1775 };
1776  
1777 static gint n_stock_icons = G_N_ELEMENTS (stock_icons);
1778
1779 static void
1780 register_vik_icons (GtkIconFactory *icon_factory)
1781 {
1782   GtkIconSet *icon_set; 
1783   gint i;
1784
1785   for (i = 0; i < n_stock_icons; i++) {
1786     icon_set = gtk_icon_set_new_from_pixbuf (gdk_pixbuf_from_pixdata (
1787                    stock_icons[i].data, FALSE, NULL ));
1788     gtk_icon_factory_add (icon_factory, stock_icons[i].stock_id, icon_set);
1789     gtk_icon_set_unref (icon_set);
1790   }
1791 }