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