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