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