]> git.street.me.uk Git - andy/viking.git/blob - src/viktrwlayer_propwin.c
Add new graph type Elevation/Time in the track properties window.
[andy/viking.git] / src / viktrwlayer_propwin.c
1 /*
2  * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
3  *
4  * Copyright (C) 2003-2005, Evan Battaglia <gtoevan@gmx.net>
5  * Copyright (C) 2005-2007, Alex Foobarian <foobarian@gmail.com>
6  * Copyright (C) 2007-2008, Quy Tonthat <qtonthat@gmail.com>
7  * Copyright (C) 2011, Rob Norris <rw_norris@hotmail.com>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  *
23  */
24
25 #ifdef HAVE_CONFIG_H
26 #include "config.h"
27 #endif
28
29 #ifdef HAVE_MATH_H
30 #include <math.h>
31 #endif
32
33 #include <gtk/gtk.h>
34 #include <glib/gi18n.h>
35 #include <time.h>
36 #ifdef HAVE_STRING_H
37 #include <string.h>
38 #endif
39 #include "coords.h"
40 #include "vikcoord.h"
41 #include "viktrack.h"
42 #include "viktrwlayer.h"
43 #include "viktrwlayer_propwin.h"
44 #include "vikwaypoint.h"
45 #include "dialog.h"
46 #include "globals.h"
47 #include "dems.h"
48
49 #include "vikviewport.h" /* ugh */
50 #include "viktreeview.h" /* ugh */
51 #include <gdk-pixbuf/gdk-pixdata.h>
52 #include "viklayer.h" /* ugh */
53 #include "vikaggregatelayer.h"
54 #include "viklayerspanel.h" /* ugh */
55
56 #define PROPWIN_PROFILE_WIDTH 600
57 #define PROPWIN_PROFILE_HEIGHT 300
58
59 #define PROPWIN_LABEL_FONT "Sans 7"
60
61 typedef enum {
62   PROPWIN_GRAPH_TYPE_ELEVATION_DISTANCE,
63   PROPWIN_GRAPH_TYPE_SPEED_TIME,
64   PROPWIN_GRAPH_TYPE_DISTANCE_TIME,
65   PROPWIN_GRAPH_TYPE_ELEVATION_TIME,
66   PROPWIN_GRAPH_TYPE_END,
67 } VikPropWinGraphType_t;
68
69 /* (Hopefully!) Human friendly altitude grid sizes - note no fixed 'ratio' just numbers that look nice...*/
70 static const gdouble chunksa[] = {2.0, 5.0, 10.0, 15.0, 20.0,
71                                   25.0, 50.0, 75.0, 100.0,
72                                   150.0, 200.0, 250.0, 375.0, 500.0,
73                                   750.0, 1000.0, 2000.0, 5000.0, 10000.0, 100000.0};
74
75 /* (Hopefully!) Human friendly grid sizes - note no fixed 'ratio' just numbers that look nice...*/
76 /* As need to cover walking speeds - have many low numbers (but also may go up to airplane speeds!) */
77 static const gdouble chunkss[] = {1.0, 2.0, 3.0, 4.0, 5.0, 8.0, 10.0,
78                                   15.0, 20.0, 25.0, 40.0, 50.0, 75.0,
79                                   100.0, 150.0, 200.0, 250.0, 375.0, 500.0,
80                                   750.0, 1000.0, 10000.0};
81
82 /* (Hopefully!) Human friendly distance grid sizes - note no fixed 'ratio' just numbers that look nice...*/
83 static const gdouble chunksd[] = {0.1, 0.5, 1.0, 2.0, 3.0, 4.0, 5.0, 8.0, 10.0,
84                                   15.0, 20.0, 25.0, 40.0, 50.0, 75.0,
85                                   100.0, 150.0, 200.0, 250.0, 375.0, 500.0,
86                                   750.0, 1000.0, 10000.0};
87
88 typedef struct _propsaved {
89   gboolean saved;
90   GdkImage *img;
91 } PropSaved;
92
93 typedef struct _propwidgets {
94   gboolean  configure_dialog;
95   VikTrwLayer *vtl;
96   VikTrack *tr;
97   gchar *track_name;
98   gint      profile_width;
99   gint      profile_height;
100   gint      profile_width_old;
101   gint      profile_height_old;
102   gint      profile_width_offset;
103   gint      profile_height_offset;
104   GtkWidget *dialog;
105   GtkWidget *w_comment;
106   GtkWidget *w_track_length;
107   GtkWidget *w_tp_count;
108   GtkWidget *w_segment_count;
109   GtkWidget *w_duptp_count;
110   GtkWidget *w_max_speed;
111   GtkWidget *w_avg_speed;
112   GtkWidget *w_avg_dist;
113   GtkWidget *w_elev_range;
114   GtkWidget *w_elev_gain;
115   GtkWidget *w_time_start;
116   GtkWidget *w_time_end;
117   GtkWidget *w_time_dur;
118   GtkWidget *w_cur_dist; /*< Current distance */
119   GtkWidget *w_cur_elevation;
120   GtkWidget *w_cur_time; /*< Current time */
121   GtkWidget *w_cur_speed;
122   GtkWidget *w_cur_dist_dist; /*< Current distance on distance graph */
123   GtkWidget *w_cur_dist_time; /*< Current time on distance graph */
124   GtkWidget *w_cur_elev_elev;
125   GtkWidget *w_cur_elev_time;
126   GtkWidget *w_show_dem;
127   GtkWidget *w_show_alt_gps_speed;
128   GtkWidget *w_show_gps_speed;
129   GtkWidget *w_show_dist_speed;
130   GtkWidget *w_show_elev_speed;
131   gdouble   track_length;
132   PropSaved elev_graph_saved_img;
133   PropSaved speed_graph_saved_img;
134   PropSaved dist_graph_saved_img;
135   PropSaved elev_time_graph_saved_img;
136   GtkWidget *elev_box;
137   GtkWidget *speed_box;
138   GtkWidget *dist_box;
139   GtkWidget *elev_time_box;
140   gdouble   *altitudes;
141   gdouble   *ats; // altitudes in time
142   gdouble   min_altitude;
143   gdouble   max_altitude;
144   gdouble   draw_min_altitude;
145   gint      cia; // Chunk size Index into Altitudes
146   gdouble   *speeds;
147   gdouble   min_speed;
148   gdouble   max_speed;
149   gdouble   draw_min_speed;
150   gint      cis; // Chunk size Index into Speeds
151   gdouble   *distances;
152   gint      cid; // Chunk size Index into Distance
153   VikTrackpoint *marker_tp;
154   gboolean  is_marker_drawn;
155   VikTrackpoint *blob_tp;
156   gboolean  is_blob_drawn;
157 } PropWidgets;
158
159 static PropWidgets *prop_widgets_new()
160 {
161   PropWidgets *widgets = g_malloc0(sizeof(PropWidgets));
162
163   return widgets;
164 }
165
166 static void prop_widgets_free(PropWidgets *widgets)
167 {
168   if (widgets->elev_graph_saved_img.img)
169     g_object_unref(widgets->elev_graph_saved_img.img);
170   if (widgets->speed_graph_saved_img.img)
171     g_object_unref(widgets->speed_graph_saved_img.img);
172   if (widgets->dist_graph_saved_img.img)
173     g_object_unref(widgets->dist_graph_saved_img.img);
174   if (widgets->elev_time_graph_saved_img.img)
175     g_object_unref(widgets->elev_time_graph_saved_img.img);
176   if (widgets->altitudes)
177     g_free(widgets->altitudes);
178   if (widgets->speeds)
179     g_free(widgets->speeds);
180   if (widgets->distances)
181     g_free(widgets->distances);
182   if (widgets->ats)
183     g_free(widgets->ats);
184   g_free(widgets);
185 }
186
187 static void minmax_array(const gdouble *array, gdouble *min, gdouble *max, gboolean NO_ALT_TEST, gint PROFILE_WIDTH)
188 {
189   *max = -1000;
190   *min = 20000;
191   guint i;
192   for ( i=0; i < PROFILE_WIDTH; i++ ) {
193     if ( NO_ALT_TEST || (array[i] != VIK_DEFAULT_ALTITUDE) ) {
194       if ( array[i] > *max )
195         *max = array[i];
196       if ( array[i] < *min )
197         *min = array[i];
198     }
199   }
200 }
201
202 #define MARGIN 70
203 #define LINES 5
204 /**
205  * Returns via pointers:
206  *   the new minimum value to be used for the altitude graph
207  *   the index in to the altitudes chunk sizes array (ci = Chunk Index)
208  */
209 static void get_new_min_and_chunk_index_altitude (gdouble mina, gdouble maxa, gdouble *new_min, gint *ci)
210 {
211   /* Get unitized chunk */
212   /* Find suitable chunk index */
213   *ci = 0;
214   gdouble diffa_chunk = (maxa - mina)/LINES;
215
216   /* Loop through to find best match */
217   while (diffa_chunk > chunksa[*ci]) {
218     (*ci)++;
219     /* Last Resort Check */
220     if ( *ci == sizeof(chunksa)/sizeof(chunksa[0]) )
221       break;
222   }
223
224   /* Ensure adjusted minimum .. maximum covers mina->maxa */
225
226   // Now work out adjusted minimum point to the nearest lowest chunk divisor value
227   // When negative ensure logic uses lowest value
228   if ( mina < 0 )
229     *new_min = (gdouble) ( ( (gint)(mina - chunksa[*ci]) / (gint)chunksa[*ci] ) * (gint)chunksa[*ci] );
230   else
231     *new_min = (gdouble) ( ( (gint)mina / (gint)chunksa[*ci] ) * (gint)chunksa[*ci] );
232
233   // Range not big enough - as new minimum has lowered
234   if ((*new_min + (chunksa[*ci] * LINES) < maxa)) {
235     // Next chunk should cover it
236     if ( *ci < sizeof(chunksa)/sizeof(chunksa[0]) ) {
237       (*ci)++;
238     }
239   }
240 }
241
242 /**
243  * Returns via pointers:
244  *   the new minimum value to be used for the appropriate graph
245  *   the index in to that array (ci = Chunk Index)
246  */
247 static void get_new_min_and_chunk_index (gdouble mins, gdouble maxs, const gdouble *chunks, size_t chunky, gdouble *new_min, gint *ci)
248 {
249   *ci = 0;
250   gdouble diff_chunk = (maxs - mins)/LINES;
251
252   /* Loop through to find best match */
253   while (diff_chunk > chunks[*ci]) {
254     (*ci)++;
255     /* Last Resort Check */
256     if ( *ci == chunky )
257       break;
258   }
259   *new_min = (gdouble) ( (gint)((mins / chunks[*ci] ) * chunks[*ci]) );
260
261   // Speeds are never negative so don't need to worry about a negative new minimum
262 }
263
264 static VikTrackpoint *set_center_at_graph_position(gdouble event_x,
265                                                    gint img_width,
266                                                    VikTrwLayer *vtl,
267                                                    VikLayersPanel *vlp,
268                                                    VikViewport *vvp,
269                                                    VikTrack *tr,
270                                                    gboolean time_base,
271                                                    gint PROFILE_WIDTH)
272 {
273   VikTrackpoint *trackpoint;
274   gdouble x = event_x - img_width / 2 + PROFILE_WIDTH / 2 - MARGIN / 2;
275   if (x < 0)
276     x = 0;
277   if (x > PROFILE_WIDTH)
278     x = PROFILE_WIDTH;
279
280   if (time_base)
281     trackpoint = vik_track_get_closest_tp_by_percentage_time ( tr, (gdouble) x / PROFILE_WIDTH, NULL );
282   else
283     trackpoint = vik_track_get_closest_tp_by_percentage_dist ( tr, (gdouble) x / PROFILE_WIDTH, NULL );
284
285   if ( trackpoint ) {
286     VikCoord coord = trackpoint->coord;
287     if ( vlp ) {
288       vik_viewport_set_center_coord ( vik_layers_panel_get_viewport(vlp), &coord );
289       vik_layers_panel_emit_update ( vlp );
290     }
291     else {
292       /* since vlp not set, vvp should be valid instead! */
293       if ( vvp )
294         vik_viewport_set_center_coord ( vvp, &coord );
295       vik_layer_emit_update ( VIK_LAYER(vtl) );
296     }
297   }
298   return trackpoint;
299 }
300
301 /**
302  * Returns whether the marker was drawn or not and whether the blob was drawn or not
303  */
304 static void save_image_and_draw_graph_marks (GtkWidget *image,
305                                              gdouble marker_x,
306                                              GdkGC *gc,
307                                              gint blob_x,
308                                              gint blob_y,
309                                              PropSaved *saved_img,
310                                              gint PROFILE_WIDTH,
311                                              gint PROFILE_HEIGHT,
312                                              gboolean *marker_drawn,
313                                              gboolean *blob_drawn)
314 {
315   GdkPixmap *pix = NULL;
316   /* the pixmap = margin + graph area */
317   gtk_image_get_pixmap(GTK_IMAGE(image), &pix, NULL);
318
319   /* Restore previously saved image */
320   if (saved_img->saved) {
321     gdk_draw_image(GDK_DRAWABLE(pix), gc, saved_img->img, 0, 0, 0, 0, MARGIN+PROFILE_WIDTH, PROFILE_HEIGHT);
322     saved_img->saved = FALSE;
323   }
324
325   // ATM always save whole image - as anywhere could have changed
326   if (saved_img->img)
327     gdk_drawable_copy_to_image(GDK_DRAWABLE(pix), saved_img->img, 0, 0, 0, 0, MARGIN+PROFILE_WIDTH, PROFILE_HEIGHT);
328   else
329     saved_img->img = gdk_drawable_copy_to_image(GDK_DRAWABLE(pix), saved_img->img, 0, 0, 0, 0, MARGIN+PROFILE_WIDTH, PROFILE_HEIGHT);
330   saved_img->saved = TRUE;
331
332   if ((marker_x >= MARGIN) && (marker_x < (PROFILE_WIDTH + MARGIN))) {
333     gdk_draw_line (GDK_DRAWABLE(pix), gc, marker_x, 0, marker_x, image->allocation.height);
334     *marker_drawn = TRUE;
335   }
336   else
337     *marker_drawn = FALSE;
338
339   // Draw a square blob to indicate where we are on track for this graph
340   if ( (blob_x >= MARGIN) && (blob_x < (PROFILE_WIDTH + MARGIN)) && (blob_y < PROFILE_HEIGHT) ) {
341     gdk_draw_rectangle (GDK_DRAWABLE(pix), gc, TRUE, blob_x-3, blob_y-3, 6, 6);
342     *blob_drawn = TRUE;
343   }
344   else
345     *blob_drawn = FALSE;
346   
347   // Anywhere on image could have changed
348   if (*marker_drawn || *blob_drawn)
349     gtk_widget_queue_draw(image);
350 }
351
352 /**
353  * Return the percentage of how far a trackpoint is a long a track via the time method
354  */
355 static gdouble tp_percentage_by_time ( VikTrack *tr, VikTrackpoint *trackpoint )
356 {
357   gdouble pc = NAN;
358   if (trackpoint == NULL)
359     return pc;
360   time_t t_start, t_end, t_total;
361   t_start = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
362   t_end = VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->timestamp;
363   t_total = t_end - t_start;
364   pc = (gdouble)(trackpoint->timestamp - t_start)/t_total;
365   return pc;
366 }
367
368 /**
369  * Return the percentage of how far a trackpoint is a long a track via the distance method
370  */
371 static gdouble tp_percentage_by_distance ( VikTrack *tr, VikTrackpoint *trackpoint, gdouble track_length )
372 {
373   gdouble pc = NAN;
374   if (trackpoint == NULL)
375     return pc;
376   gdouble dist = 0.0;
377   GList *iter;
378   for (iter = tr->trackpoints->next; iter != NULL; iter = iter->next) {
379     dist += vik_coord_diff(&(VIK_TRACKPOINT(iter->data)->coord),
380                            &(VIK_TRACKPOINT(iter->prev->data)->coord));
381     /* Assuming trackpoint is not a copy */
382     if (trackpoint == VIK_TRACKPOINT(iter->data))
383       break;
384   }
385   if (iter != NULL)
386     pc = dist/track_length;
387   return pc;
388 }
389
390 static void track_graph_click( GtkWidget *event_box, GdkEventButton *event, gpointer *pass_along, VikPropWinGraphType_t graph_type )
391 {
392   VikTrack *tr = pass_along[0];
393   VikLayersPanel *vlp = pass_along[1];
394   VikViewport *vvp = pass_along[2];
395   PropWidgets *widgets = pass_along[3];
396
397   gboolean is_time_graph = graph_type != PROPWIN_GRAPH_TYPE_ELEVATION_DISTANCE;
398
399   VikTrackpoint *trackpoint = set_center_at_graph_position(event->x, event_box->allocation.width, widgets->vtl, vlp, vvp, tr, is_time_graph, widgets->profile_width);
400   // Unable to get the point so give up
401   if ( trackpoint == NULL ) {
402     gtk_dialog_set_response_sensitive(GTK_DIALOG(widgets->dialog), VIK_TRW_LAYER_PROPWIN_SPLIT_MARKER, FALSE);
403     return;
404   }
405
406   widgets->marker_tp = trackpoint;
407
408   GList *child;
409   GtkWidget *image;
410   GtkWidget *window = gtk_widget_get_toplevel(GTK_WIDGET(event_box));
411   GtkWidget *graph_box;
412   PropSaved *graph_saved_img;
413   gdouble pc = NAN;
414
415   // Attempt to redraw marker on all graph types
416   gint graphite;
417   for ( graphite = PROPWIN_GRAPH_TYPE_ELEVATION_DISTANCE;
418         graphite < PROPWIN_GRAPH_TYPE_END;
419         graphite++ ) {
420
421     // Switch commonal variables to particular graph type
422     switch (graphite) {
423     default:
424     case PROPWIN_GRAPH_TYPE_ELEVATION_DISTANCE:
425       graph_box       = widgets->elev_box;
426       graph_saved_img = &widgets->elev_graph_saved_img;
427       is_time_graph   = FALSE;
428       break;
429     case PROPWIN_GRAPH_TYPE_SPEED_TIME:
430       graph_box       = widgets->speed_box;
431       graph_saved_img = &widgets->speed_graph_saved_img;
432       is_time_graph   = TRUE;
433       break;
434     case PROPWIN_GRAPH_TYPE_DISTANCE_TIME:
435       graph_box       = widgets->dist_box;
436       graph_saved_img = &widgets->dist_graph_saved_img;
437       is_time_graph   = TRUE;
438       break;
439     case PROPWIN_GRAPH_TYPE_ELEVATION_TIME:
440       graph_box       = widgets->elev_time_box;
441       graph_saved_img = &widgets->elev_time_graph_saved_img;
442       is_time_graph   = TRUE;
443       break;
444     }
445
446     // Commonal method of redrawing marker
447     if ( graph_box ) {
448
449       child = gtk_container_get_children(GTK_CONTAINER(graph_box));
450       image = GTK_WIDGET(child->data);
451
452       if (is_time_graph)
453         pc = tp_percentage_by_time ( tr, trackpoint );
454       else
455         pc = tp_percentage_by_distance ( tr, trackpoint, widgets->track_length );
456
457       if (!isnan(pc)) {
458         gdouble marker_x = (pc * widgets->profile_width) + MARGIN;
459         save_image_and_draw_graph_marks(image,
460                                         marker_x,
461                                         window->style->black_gc,
462                                         -1, // Don't draw blob on clicks
463                                         0,
464                                         graph_saved_img,
465                                         widgets->profile_width,
466                                         widgets->profile_height,
467                                         &widgets->is_marker_drawn,
468                                         &widgets->is_blob_drawn);
469       }
470       g_list_free(child);
471     }
472   }
473
474   gtk_dialog_set_response_sensitive(GTK_DIALOG(widgets->dialog), VIK_TRW_LAYER_PROPWIN_SPLIT_MARKER, widgets->is_marker_drawn);
475 }
476
477 static gboolean track_profile_click( GtkWidget *event_box, GdkEventButton *event, gpointer *pass_along )
478 {
479   track_graph_click(event_box, event, pass_along, PROPWIN_GRAPH_TYPE_ELEVATION_DISTANCE);
480   return TRUE;  /* don't call other (further) callbacks */
481 }
482
483 static gboolean track_vt_click( GtkWidget *event_box, GdkEventButton *event, gpointer *pass_along )
484 {
485   track_graph_click(event_box, event, pass_along, PROPWIN_GRAPH_TYPE_SPEED_TIME);
486   return TRUE;  /* don't call other (further) callbacks */
487 }
488
489 static gboolean track_dt_click( GtkWidget *event_box, GdkEventButton *event, gpointer *pass_along )
490 {
491   track_graph_click(event_box, event, pass_along, PROPWIN_GRAPH_TYPE_DISTANCE_TIME);
492   return TRUE;  /* don't call other (further) callbacks */
493 }
494
495 static gboolean track_et_click( GtkWidget *event_box, GdkEventButton *event, gpointer *pass_along )
496 {
497   track_graph_click(event_box, event, pass_along, PROPWIN_GRAPH_TYPE_ELEVATION_TIME);
498   return TRUE;  /* don't call other (further) callbacks */
499 }
500
501 /**
502  * Calculate y position for blob on elevation graph
503  */
504 static gint blobby_altitude ( gdouble x_blob, PropWidgets *widgets )
505 {
506   gint ix = (gint)x_blob;
507   // Ensure ix is inbounds
508   if (ix == widgets->profile_width)
509     ix--;
510
511   gint y_blob = widgets->profile_height-widgets->profile_height*(widgets->altitudes[ix]-widgets->draw_min_altitude)/(chunksa[widgets->cia]*LINES);
512
513   return y_blob;
514 }
515
516 /**
517  * Calculate y position for blob on speed graph
518  */
519 static gint blobby_speed ( gdouble x_blob, PropWidgets *widgets )
520 {
521   gint ix = (gint)x_blob;
522   // Ensure ix is inbounds
523   if (ix == widgets->profile_width)
524     ix--;
525
526   gint y_blob = widgets->profile_height-widgets->profile_height*(widgets->speeds[ix]-widgets->draw_min_speed)/(chunkss[widgets->cis]*LINES);
527
528   return y_blob;
529 }
530
531 /**
532  * Calculate y position for blob on distance graph
533  */
534 static gint blobby_distance ( gdouble x_blob, PropWidgets *widgets )
535 {
536   gint ix = (gint)x_blob;
537   // Ensure ix is inbounds
538   if (ix == widgets->profile_width)
539     ix--;
540
541   gint y_blob = widgets->profile_height-widgets->profile_height*(widgets->distances[ix])/(chunksd[widgets->cid]*LINES);
542   //NB min distance is always 0, so no need to subtract that from this  ______/
543
544   return y_blob;
545 }
546
547 /**
548  * Calculate y position for blob on elevation/time graph
549  */
550 static gint blobby_altitude_time ( gdouble x_blob, PropWidgets *widgets )
551 {
552   gint ix = (gint)x_blob;
553   // Ensure ix is inbounds
554   if (ix == widgets->profile_width)
555     ix--;
556
557   gint y_blob = widgets->profile_height-widgets->profile_height*(widgets->ats[ix]-widgets->draw_min_altitude)/(chunksa[widgets->cia]*LINES);
558   // only difference here [could refactor]?          _____________________/
559   return y_blob;
560 }
561
562
563 void track_profile_move( GtkWidget *event_box, GdkEventMotion *event, gpointer *pass_along )
564 {
565   VikTrack *tr = pass_along[0];
566   PropWidgets *widgets = pass_along[3];
567   int mouse_x, mouse_y;
568   GdkModifierType state;
569
570   if (event->is_hint)
571     gdk_window_get_pointer (event->window, &mouse_x, &mouse_y, &state);
572   else
573     mouse_x = event->x;
574
575   gdouble x = mouse_x - event_box->allocation.width / 2 + widgets->profile_width / 2 - MARGIN / 2;
576   if (x < 0)
577     x = 0;
578   if (x > widgets->profile_width)
579     x = widgets->profile_width;
580
581   gdouble meters_from_start;
582   VikTrackpoint *trackpoint = vik_track_get_closest_tp_by_percentage_dist ( tr, (gdouble) x / widgets->profile_width, &meters_from_start );
583   if (trackpoint && widgets->w_cur_dist) {
584     static gchar tmp_buf[20];
585     vik_units_distance_t dist_units = a_vik_get_units_distance ();
586     switch (dist_units) {
587     case VIK_UNITS_DISTANCE_KILOMETRES:
588       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f km", meters_from_start/1000.0);
589       break;
590     case VIK_UNITS_DISTANCE_MILES:
591       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f miles", VIK_METERS_TO_MILES(meters_from_start) );
592       break;
593     default:
594       g_critical("Houston, we've had a problem. distance=%d", dist_units);
595     }
596     gtk_label_set_text(GTK_LABEL(widgets->w_cur_dist), tmp_buf);
597   }
598
599   // Show track elevation for this position - to the nearest whole number
600   if (trackpoint && widgets->w_cur_elevation) {
601     static gchar tmp_buf[20];
602     if (a_vik_get_units_height () == VIK_UNITS_HEIGHT_FEET)
603       g_snprintf(tmp_buf, sizeof(tmp_buf), "%d ft", (int)VIK_METERS_TO_FEET(trackpoint->altitude));
604     else
605       g_snprintf(tmp_buf, sizeof(tmp_buf), "%d m", (int)trackpoint->altitude);
606     gtk_label_set_text(GTK_LABEL(widgets->w_cur_elevation), tmp_buf);
607   }
608
609   widgets->blob_tp = trackpoint;
610
611   if ( widgets->altitudes == NULL )
612     return;
613
614   GtkWidget *window = gtk_widget_get_toplevel (event_box);
615   GList *child = gtk_container_get_children(GTK_CONTAINER(event_box));
616   GtkWidget *image = GTK_WIDGET(child->data);
617
618   gint y_blob = blobby_altitude (x, widgets);
619
620   gdouble marker_x = -1.0; // i.e. Don't draw unless we get a valid value
621   if (widgets->is_marker_drawn) {
622     gdouble pc = tp_percentage_by_distance ( tr, widgets->marker_tp, widgets->track_length );
623     if (!isnan(pc)) {
624       marker_x = (pc * widgets->profile_width) + MARGIN;
625     }
626   }
627
628   save_image_and_draw_graph_marks (image,
629                                    marker_x,
630                                    window->style->black_gc,
631                                    MARGIN+x,
632                                    y_blob,
633                                    &widgets->elev_graph_saved_img,
634                                    widgets->profile_width,
635                                    widgets->profile_height,
636                                    &widgets->is_marker_drawn,
637                                    &widgets->is_blob_drawn);
638
639   g_list_free(child);
640 }
641
642 void track_vt_move( GtkWidget *event_box, GdkEventMotion *event, gpointer *pass_along )
643 {
644   VikTrack *tr = pass_along[0];
645   PropWidgets *widgets = pass_along[3];
646   int mouse_x, mouse_y;
647   GdkModifierType state;
648
649   if (event->is_hint)
650     gdk_window_get_pointer (event->window, &mouse_x, &mouse_y, &state);
651   else
652     mouse_x = event->x;
653
654   gdouble x = mouse_x - event_box->allocation.width / 2 + widgets->profile_width / 2 - MARGIN / 2;
655   if (x < 0)
656     x = 0;
657   if (x > widgets->profile_width)
658     x = widgets->profile_width;
659
660   time_t seconds_from_start;
661   VikTrackpoint *trackpoint = vik_track_get_closest_tp_by_percentage_time ( tr, (gdouble) x / widgets->profile_width, &seconds_from_start );
662   if (trackpoint && widgets->w_cur_time) {
663     static gchar tmp_buf[20];
664     guint h, m, s;
665     h = seconds_from_start/3600;
666     m = (seconds_from_start - h*3600)/60;
667     s = seconds_from_start - (3600*h) - (60*m);
668     g_snprintf(tmp_buf, sizeof(tmp_buf), "%02d:%02d:%02d", h, m, s);
669
670     gtk_label_set_text(GTK_LABEL(widgets->w_cur_time), tmp_buf);
671   }
672
673   gint ix = (gint)x;
674   // Ensure ix is inbounds
675   if (ix == widgets->profile_width)
676     ix--;
677
678   // Show track speed for this position
679   if (trackpoint && widgets->w_cur_speed) {
680     static gchar tmp_buf[20];
681     // Even if GPS speed available (trackpoint->speed), the text will correspond to the speed map shown
682     // No conversions needed as already in appropriate units
683     vik_units_speed_t speed_units = a_vik_get_units_speed ();
684     switch (speed_units) {
685     case VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
686       g_snprintf(tmp_buf, sizeof(tmp_buf), _("%.1f kph"), widgets->speeds[ix]);
687       break;
688     case VIK_UNITS_SPEED_MILES_PER_HOUR:
689       g_snprintf(tmp_buf, sizeof(tmp_buf), _("%.1f mph"), widgets->speeds[ix]);
690       break;
691     case VIK_UNITS_SPEED_KNOTS:
692       g_snprintf(tmp_buf, sizeof(tmp_buf), _("%.1f knots"), widgets->speeds[ix]);
693       break;
694     default:
695       // VIK_UNITS_SPEED_METRES_PER_SECOND:
696       g_snprintf(tmp_buf, sizeof(tmp_buf), _("%.1f m/s"), widgets->speeds[ix]);
697       break;
698     }
699     gtk_label_set_text(GTK_LABEL(widgets->w_cur_speed), tmp_buf);
700   }
701
702   widgets->blob_tp = trackpoint;
703
704   if ( widgets->speeds == NULL )
705     return;
706
707   GtkWidget *window = gtk_widget_get_toplevel (event_box);
708   GList *child = gtk_container_get_children(GTK_CONTAINER(event_box));
709   GtkWidget *image = GTK_WIDGET(child->data);
710
711   gint y_blob = blobby_speed (x, widgets);
712
713   gdouble marker_x = -1.0; // i.e. Don't draw unless we get a valid value
714   if (widgets->is_marker_drawn) {
715     gdouble pc = tp_percentage_by_time ( tr, widgets->marker_tp );
716     if (!isnan(pc)) {
717       marker_x = (pc * widgets->profile_width) + MARGIN;
718     }
719   }
720
721   save_image_and_draw_graph_marks (image,
722                                    marker_x,
723                                    window->style->black_gc,
724                                    MARGIN+x,
725                                    y_blob,
726                                    &widgets->speed_graph_saved_img,
727                                    widgets->profile_width,
728                                    widgets->profile_height,
729                                    &widgets->is_marker_drawn,
730                                    &widgets->is_blob_drawn);
731
732   g_list_free(child);
733 }
734
735 /**
736  * Update labels and blob marker on mouse moves in the distance/time graph
737  */
738 void track_dt_move( GtkWidget *event_box, GdkEventMotion *event, gpointer *pass_along )
739 {
740   VikTrack *tr = pass_along[0];
741   PropWidgets *widgets = pass_along[3];
742   int mouse_x, mouse_y;
743   GdkModifierType state;
744
745   if (event->is_hint)
746     gdk_window_get_pointer (event->window, &mouse_x, &mouse_y, &state);
747   else
748     mouse_x = event->x;
749
750   gdouble x = mouse_x - event_box->allocation.width / 2 + widgets->profile_width / 2 - MARGIN / 2;
751   if (x < 0)
752     x = 0;
753   if (x > widgets->profile_width)
754     x = widgets->profile_width;
755
756   time_t seconds_from_start;
757   VikTrackpoint *trackpoint = vik_track_get_closest_tp_by_percentage_time ( tr, (gdouble) x / widgets->profile_width, &seconds_from_start );
758   if (trackpoint && widgets->w_cur_dist_time) {
759     static gchar tmp_buf[20];
760     guint h, m, s;
761     h = seconds_from_start/3600;
762     m = (seconds_from_start - h*3600)/60;
763     s = seconds_from_start - (3600*h) - (60*m);
764     g_snprintf(tmp_buf, sizeof(tmp_buf), "%02d:%02d:%02d", h, m, s);
765
766     gtk_label_set_text(GTK_LABEL(widgets->w_cur_dist_time), tmp_buf);
767   }
768
769   gint ix = (gint)x;
770   // Ensure ix is inbounds
771   if (ix == widgets->profile_width)
772     ix--;
773
774   if (trackpoint && widgets->w_cur_dist_dist) {
775     static gchar tmp_buf[20];
776     if ( a_vik_get_units_distance () == VIK_UNITS_DISTANCE_MILES )
777       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f miles", widgets->distances[ix]);
778     else
779       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f km", widgets->distances[ix]);
780     gtk_label_set_text(GTK_LABEL(widgets->w_cur_dist_dist), tmp_buf);
781   }
782
783   widgets->blob_tp = trackpoint;
784
785   if ( widgets->distances == NULL )
786     return;
787
788   GtkWidget *window = gtk_widget_get_toplevel (event_box);
789   GList *child = gtk_container_get_children(GTK_CONTAINER(event_box));
790   GtkWidget *image = GTK_WIDGET(child->data);
791
792   gint y_blob = blobby_distance (x, widgets);
793
794   gdouble marker_x = -1.0; // i.e. Don't draw unless we get a valid value
795   if (widgets->is_marker_drawn) {
796     gdouble pc = tp_percentage_by_time ( tr, widgets->marker_tp );
797     if (!isnan(pc)) {
798       marker_x = (pc * widgets->profile_width) + MARGIN;
799     }
800   }
801
802   save_image_and_draw_graph_marks (image,
803                                    marker_x,
804                                    window->style->black_gc,
805                                    MARGIN+x,
806                                    y_blob,
807                                    &widgets->dist_graph_saved_img,
808                                    widgets->profile_width,
809                                    widgets->profile_height,
810                                    &widgets->is_marker_drawn,
811                                    &widgets->is_blob_drawn);
812
813   g_list_free(child);
814 }
815
816 /**
817  * Update labels and blob marker on mouse moves in the elevation/time graph
818  */
819 void track_et_move( GtkWidget *event_box, GdkEventMotion *event, gpointer *pass_along )
820 {
821   VikTrack *tr = pass_along[0];
822   PropWidgets *widgets = pass_along[3];
823   int mouse_x, mouse_y;
824   GdkModifierType state;
825
826   if (event->is_hint)
827     gdk_window_get_pointer (event->window, &mouse_x, &mouse_y, &state);
828   else
829     mouse_x = event->x;
830
831   gdouble x = mouse_x - event_box->allocation.width / 2 + widgets->profile_width / 2 - MARGIN / 2;
832   if (x < 0)
833     x = 0;
834   if (x > widgets->profile_width)
835     x = widgets->profile_width;
836
837   time_t seconds_from_start;
838   VikTrackpoint *trackpoint = vik_track_get_closest_tp_by_percentage_time ( tr, (gdouble) x / widgets->profile_width, &seconds_from_start );
839   if (trackpoint && widgets->w_cur_elev_time) {
840     static gchar tmp_buf[20];
841     guint h, m, s;
842     h = seconds_from_start/3600;
843     m = (seconds_from_start - h*3600)/60;
844     s = seconds_from_start - (3600*h) - (60*m);
845     g_snprintf(tmp_buf, sizeof(tmp_buf), "%02d:%02d:%02d", h, m, s);
846
847     gtk_label_set_text(GTK_LABEL(widgets->w_cur_elev_time), tmp_buf);
848   }
849
850   gint ix = (gint)x;
851   // Ensure ix is inbounds
852   if (ix == widgets->profile_width)
853     ix--;
854
855   if (trackpoint && widgets->w_cur_elev_elev) {
856     static gchar tmp_buf[20];
857     if (a_vik_get_units_height () == VIK_UNITS_HEIGHT_FEET)
858       g_snprintf(tmp_buf, sizeof(tmp_buf), "%d ft", (int)VIK_METERS_TO_FEET(trackpoint->altitude));
859     else
860       g_snprintf(tmp_buf, sizeof(tmp_buf), "%d m", (int)trackpoint->altitude);
861     gtk_label_set_text(GTK_LABEL(widgets->w_cur_elev_elev), tmp_buf);
862   }
863
864   widgets->blob_tp = trackpoint;
865
866   if ( widgets->ats == NULL )
867     return;
868
869   GtkWidget *window = gtk_widget_get_toplevel (event_box);
870   GList *child = gtk_container_get_children(GTK_CONTAINER(event_box));
871   GtkWidget *image = GTK_WIDGET(child->data);
872
873   gint y_blob = blobby_altitude_time (x, widgets);
874
875   gdouble marker_x = -1.0; // i.e. Don't draw unless we get a valid value
876   if (widgets->is_marker_drawn) {
877     gdouble pc = tp_percentage_by_time ( tr, widgets->marker_tp );
878     if (!isnan(pc)) {
879       marker_x = (pc * widgets->profile_width) + MARGIN;
880     }
881   }
882
883   save_image_and_draw_graph_marks (image,
884                                    marker_x,
885                                    window->style->black_gc,
886                                    MARGIN+x,
887                                    y_blob,
888                                    &widgets->elev_time_graph_saved_img,
889                                    widgets->profile_width,
890                                    widgets->profile_height,
891                                    &widgets->is_marker_drawn,
892                                    &widgets->is_blob_drawn);
893
894   g_list_free(child);
895 }
896
897 /**
898  * Draws DEM points and a respresentative speed on the supplied pixmap
899  *   (which is the elevations graph)
900  */
901 static void draw_dem_alt_speed_dist(VikTrack *tr,
902                                     GdkDrawable *pix,
903                                     GdkGC *alt_gc,
904                                     GdkGC *speed_gc,
905                                     gdouble alt_offset,
906                                     gdouble alt_diff,
907                                     gdouble max_speed_in,
908                                     gint cia,
909                                     gint width,
910                                     gint height,
911                                     gint margin,
912                                     gboolean do_dem,
913                                     gboolean do_speed)
914 {
915   GList *iter;
916   gdouble max_speed = 0;
917   gdouble total_length = vik_track_get_length_including_gaps(tr);
918
919   // Calculate the max speed factor
920   if (do_speed)
921     max_speed = max_speed_in * 110 / 100;
922
923   gdouble dist = 0;
924   for (iter = tr->trackpoints->next; iter; iter = iter->next) {
925     int x;
926     dist += vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord),
927                              &(VIK_TRACKPOINT(iter->prev->data)->coord) );
928     x = (width * dist)/total_length + margin;
929     if (do_dem) {
930       gint16 elev = a_dems_get_elev_by_coord(&(VIK_TRACKPOINT(iter->data)->coord), VIK_DEM_INTERPOL_BEST);
931       elev -= alt_offset;
932       if ( elev != VIK_DEM_INVALID_ELEVATION ) {
933         // Convert into height units
934         if (a_vik_get_units_height () == VIK_UNITS_HEIGHT_FEET)
935           elev =  VIK_METERS_TO_FEET(elev);
936         // No conversion needed if already in metres
937
938         // consider chunk size
939         int y_alt = height - ((height * (elev-alt_offset))/(chunksa[cia]*LINES) );
940         gdk_draw_rectangle(GDK_DRAWABLE(pix), alt_gc, TRUE, x-2, y_alt-2, 4, 4);
941       }
942     }
943     if (do_speed) {
944       // This is just a speed indicator - no actual values can be inferred by user
945       if (!isnan(VIK_TRACKPOINT(iter->data)->speed)) {
946         int y_speed = height - (height * VIK_TRACKPOINT(iter->data)->speed)/max_speed;
947         gdk_draw_rectangle(GDK_DRAWABLE(pix), speed_gc, TRUE, x-2, y_speed-2, 4, 4);
948       }
949     }
950   }
951 }
952
953 /**
954  * Draw just the height profile image
955  */
956 static void draw_elevations (GtkWidget *image, VikTrack *tr, PropWidgets *widgets )
957 {
958   GtkWidget *window;
959   GdkPixmap *pix;
960   gdouble mina, maxa;
961   guint i;
962
963   GdkGC *no_alt_info;
964   GdkGC *dem_alt_gc;
965   GdkGC *gps_speed_gc;
966
967   GdkColor color;
968
969   // Free previous allocation
970   if ( widgets->altitudes )
971     g_free ( widgets->altitudes );
972
973   widgets->altitudes = vik_track_make_elevation_map ( tr, widgets->profile_width );
974
975   if ( widgets->altitudes == NULL )
976     return;
977
978   // Convert into appropriate units
979   vik_units_height_t height_units = a_vik_get_units_height ();
980   if ( height_units == VIK_UNITS_HEIGHT_FEET ) {
981     // Convert altitudes into feet units
982     for ( i = 0; i < widgets->profile_width; i++ ) {
983       widgets->altitudes[i] = VIK_METERS_TO_FEET(widgets->altitudes[i]);
984     }
985   }
986   // Otherwise leave in metres
987
988   minmax_array(widgets->altitudes, &widgets->min_altitude, &widgets->max_altitude, TRUE, widgets->profile_width);
989
990   get_new_min_and_chunk_index_altitude (widgets->min_altitude, widgets->max_altitude, &widgets->draw_min_altitude, &widgets->cia);
991
992   // Assign locally
993   mina = widgets->draw_min_altitude;
994   maxa = widgets->max_altitude;
995
996   window = gtk_widget_get_toplevel (widgets->elev_box);
997
998   pix = gdk_pixmap_new( window->window, widgets->profile_width + MARGIN, widgets->profile_height, -1 );
999
1000   gtk_image_set_from_pixmap ( GTK_IMAGE(image), pix, NULL );
1001
1002   no_alt_info = gdk_gc_new ( window->window );
1003   gdk_color_parse ( "yellow", &color );
1004   gdk_gc_set_rgb_fg_color ( no_alt_info, &color);
1005
1006   dem_alt_gc = gdk_gc_new ( window->window );
1007   gdk_color_parse ( "green", &color );
1008   gdk_gc_set_rgb_fg_color ( dem_alt_gc, &color);
1009
1010   gps_speed_gc = gdk_gc_new ( window->window );
1011   gdk_color_parse ( "red", &color );
1012   gdk_gc_set_rgb_fg_color ( gps_speed_gc, &color);
1013
1014   /* clear the image */
1015   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->bg_gc[0], 
1016                      TRUE, 0, 0, MARGIN, widgets->profile_height);
1017   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->mid_gc[0], 
1018                      TRUE, MARGIN, 0, widgets->profile_width, widgets->profile_height);
1019   
1020   /* draw grid */
1021   for (i=0; i<=LINES; i++) {
1022     PangoFontDescription *pfd;
1023     PangoLayout *pl = gtk_widget_create_pango_layout (GTK_WIDGET(image), NULL);
1024     gchar s[32];
1025     int w, h;
1026
1027     pango_layout_set_alignment (pl, PANGO_ALIGN_RIGHT);
1028     pfd = pango_font_description_from_string (PROPWIN_LABEL_FONT);
1029     pango_layout_set_font_description (pl, pfd);
1030     pango_font_description_free (pfd);
1031     switch (height_units) {
1032     case VIK_UNITS_HEIGHT_METRES:
1033       sprintf(s, "%8dm", (int)(mina + (LINES-i)*chunksa[widgets->cia]));
1034       break;
1035     case VIK_UNITS_HEIGHT_FEET:
1036       // NB values already converted into feet
1037       sprintf(s, "%8dft", (int)(mina + (LINES-i)*chunksa[widgets->cia]));
1038       break;
1039     default:
1040       sprintf(s, "--");
1041       g_critical("Houston, we've had a problem. height=%d", height_units);
1042     }
1043     pango_layout_set_text(pl, s, -1);
1044     pango_layout_get_pixel_size (pl, &w, &h);
1045     gdk_draw_layout(GDK_DRAWABLE(pix), window->style->fg_gc[0], MARGIN-w-3, 
1046                     CLAMP((int)i*widgets->profile_height/LINES - h/2, 0, widgets->profile_height-h), pl);
1047
1048     gdk_draw_line (GDK_DRAWABLE(pix), window->style->dark_gc[0], 
1049                    MARGIN, widgets->profile_height/LINES * i, MARGIN + widgets->profile_width, widgets->profile_height/LINES * i);
1050     g_object_unref ( G_OBJECT ( pl ) );
1051     pl = NULL;
1052   }
1053
1054   /* draw elevations */
1055   for ( i = 0; i < widgets->profile_width; i++ )
1056     if ( widgets->altitudes[i] == VIK_DEFAULT_ALTITUDE )
1057       gdk_draw_line ( GDK_DRAWABLE(pix), no_alt_info, 
1058                       i + MARGIN, 0, i + MARGIN, widgets->profile_height );
1059     else 
1060       gdk_draw_line ( GDK_DRAWABLE(pix), window->style->dark_gc[3], 
1061                       i + MARGIN, widgets->profile_height, i + MARGIN, widgets->profile_height-widgets->profile_height*(widgets->altitudes[i]-mina)/(chunksa[widgets->cia]*LINES) );
1062
1063   // Ensure somekind of max speed when not set
1064   if ( widgets->max_speed < 0.01 )
1065     widgets->max_speed = vik_track_get_max_speed(tr);
1066
1067   draw_dem_alt_speed_dist(tr,
1068                           GDK_DRAWABLE(pix),
1069                           dem_alt_gc,
1070                           gps_speed_gc,
1071                           mina,
1072                           maxa - mina,
1073                           widgets->max_speed,
1074                           widgets->cia,
1075                           widgets->profile_width,
1076                           widgets->profile_height,
1077                           MARGIN,
1078                           gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON(widgets->w_show_dem)),
1079                           gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON(widgets->w_show_alt_gps_speed)));
1080
1081   /* draw border */
1082   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->black_gc, FALSE, MARGIN, 0, widgets->profile_width-1, widgets->profile_height-1);
1083
1084   g_object_unref ( G_OBJECT(pix) );
1085   g_object_unref ( G_OBJECT(no_alt_info) );
1086   g_object_unref ( G_OBJECT(dem_alt_gc) );
1087   g_object_unref ( G_OBJECT(gps_speed_gc) );
1088
1089 }
1090
1091 /**
1092  * Draw just the speed (velocity)/time image
1093  */
1094 static void draw_vt ( GtkWidget *image, VikTrack *tr, PropWidgets *widgets)
1095 {
1096   GtkWidget *window;
1097   GdkPixmap *pix;
1098   gdouble mins, maxs;
1099   guint i;
1100
1101   // Free previous allocation
1102   if ( widgets->speeds )
1103     g_free ( widgets->speeds );
1104
1105   widgets->speeds = vik_track_make_speed_map ( tr, widgets->profile_width );
1106   if ( widgets->speeds == NULL )
1107     return;
1108
1109   // Convert into appropriate units
1110   vik_units_speed_t speed_units = a_vik_get_units_speed ();
1111   switch (speed_units) {
1112   case VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
1113     for ( i = 0; i < widgets->profile_width; i++ ) {
1114       widgets->speeds[i] = VIK_MPS_TO_KPH(widgets->speeds[i]);
1115     }
1116     break;
1117   case VIK_UNITS_SPEED_MILES_PER_HOUR:
1118     for ( i = 0; i < widgets->profile_width; i++ ) {
1119       widgets->speeds[i] = VIK_MPS_TO_MPH(widgets->speeds[i]);
1120     }
1121     break;
1122   case VIK_UNITS_SPEED_KNOTS:
1123     for ( i = 0; i < widgets->profile_width; i++ ) {
1124       widgets->speeds[i] = VIK_MPS_TO_KNOTS(widgets->speeds[i]);
1125     }
1126     break;
1127   default:
1128     // VIK_UNITS_SPEED_METRES_PER_SECOND:
1129     // No need to convert as already in m/s
1130     break;
1131   }
1132
1133   GdkGC *gps_speed_gc;
1134   GdkColor color;
1135
1136   window = gtk_widget_get_toplevel (widgets->speed_box);
1137
1138   pix = gdk_pixmap_new( window->window, widgets->profile_width + MARGIN, widgets->profile_height, -1 );
1139
1140   gtk_image_set_from_pixmap ( GTK_IMAGE(image), pix, NULL );
1141
1142   gps_speed_gc = gdk_gc_new ( window->window );
1143   gdk_color_parse ( "red", &color );
1144   gdk_gc_set_rgb_fg_color ( gps_speed_gc, &color);
1145
1146   minmax_array(widgets->speeds, &widgets->min_speed, &widgets->max_speed, FALSE, widgets->profile_width);
1147   if (widgets->min_speed < 0.0)
1148     widgets->min_speed = 0; /* splines sometimes give negative speeds */
1149
1150   /* Find suitable chunk index */
1151   get_new_min_and_chunk_index (widgets->min_speed, widgets->max_speed, chunkss, sizeof(chunkss)/sizeof(chunkss[0]), &widgets->draw_min_speed, &widgets->cis);
1152
1153   // Assign locally
1154   mins = widgets->draw_min_speed;
1155   maxs = widgets->max_speed;
1156   
1157   /* clear the image */
1158   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->bg_gc[0], 
1159                      TRUE, 0, 0, MARGIN, widgets->profile_height);
1160   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->mid_gc[0], 
1161                      TRUE, MARGIN, 0, widgets->profile_width, widgets->profile_height);
1162
1163   /* draw grid */
1164   for (i=0; i<=LINES; i++) {
1165     PangoFontDescription *pfd;
1166     PangoLayout *pl = gtk_widget_create_pango_layout (GTK_WIDGET(image), NULL);
1167     gchar s[32];
1168     int w, h;
1169
1170     pango_layout_set_alignment (pl, PANGO_ALIGN_RIGHT);
1171     pfd = pango_font_description_from_string (PROPWIN_LABEL_FONT);
1172     pango_layout_set_font_description (pl, pfd);
1173     pango_font_description_free (pfd);
1174     // NB: No need to convert here anymore as numbers are in the appropriate units
1175     switch (speed_units) {
1176     case VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
1177       sprintf(s, "%8dkm/h", (int)(mins + (LINES-i)*chunkss[widgets->cis]));
1178       break;
1179     case VIK_UNITS_SPEED_MILES_PER_HOUR:
1180       sprintf(s, "%8dmph", (int)(mins + (LINES-i)*chunkss[widgets->cis]));
1181       break;
1182     case VIK_UNITS_SPEED_METRES_PER_SECOND:
1183       sprintf(s, "%8dm/s", (int)(mins + (LINES-i)*chunkss[widgets->cis]));
1184       break;
1185     case VIK_UNITS_SPEED_KNOTS:
1186       sprintf(s, "%8dknots", (int)(mins + (LINES-i)*chunkss[widgets->cis]));
1187       break;
1188     default:
1189       sprintf(s, "--");
1190       g_critical("Houston, we've had a problem. speed=%d", speed_units);
1191     }
1192
1193     pango_layout_set_text(pl, s, -1);
1194     pango_layout_get_pixel_size (pl, &w, &h);
1195     gdk_draw_layout(GDK_DRAWABLE(pix), window->style->fg_gc[0], MARGIN-w-3, 
1196                     CLAMP((int)i*widgets->profile_height/LINES - h/2, 0, widgets->profile_height-h), pl);
1197
1198     gdk_draw_line (GDK_DRAWABLE(pix), window->style->dark_gc[0], 
1199                    MARGIN, widgets->profile_height/LINES * i, MARGIN + widgets->profile_width, widgets->profile_height/LINES * i);
1200     g_object_unref ( G_OBJECT ( pl ) );
1201     pl = NULL;
1202   }
1203   
1204
1205   /* draw speeds */
1206   for ( i = 0; i < widgets->profile_width; i++ )
1207       gdk_draw_line ( GDK_DRAWABLE(pix), window->style->dark_gc[3], 
1208                       i + MARGIN, widgets->profile_height, i + MARGIN, widgets->profile_height-widgets->profile_height*(widgets->speeds[i]-mins)/(chunkss[widgets->cis]*LINES) );
1209
1210
1211   time_t beg_time = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
1212   time_t dur =  VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->timestamp - beg_time;
1213
1214   if ( gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widgets->w_show_gps_speed)) ) {
1215     GList *iter;
1216     for (iter = tr->trackpoints; iter; iter = iter->next) {
1217       gdouble gps_speed = VIK_TRACKPOINT(iter->data)->speed;
1218       if (isnan(gps_speed))
1219         continue;
1220       switch (speed_units) {
1221       case VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
1222         gps_speed = VIK_MPS_TO_KPH(gps_speed);
1223         break;
1224       case VIK_UNITS_SPEED_MILES_PER_HOUR:
1225         gps_speed = VIK_MPS_TO_MPH(gps_speed);
1226         break;
1227       case VIK_UNITS_SPEED_KNOTS:
1228         gps_speed = VIK_MPS_TO_KNOTS(gps_speed);
1229         break;
1230       default:
1231         // VIK_UNITS_SPEED_METRES_PER_SECOND:
1232         // No need to convert as already in m/s
1233         break;
1234       }
1235       int x = MARGIN + widgets->profile_width * (VIK_TRACKPOINT(iter->data)->timestamp - beg_time) / dur;
1236       int y = widgets->profile_height - widgets->profile_height*(gps_speed - mins)/(chunkss[widgets->cis]*LINES);
1237       gdk_draw_rectangle(GDK_DRAWABLE(pix), gps_speed_gc, TRUE, x-2, y-2, 4, 4);
1238     }
1239   }
1240
1241   /* draw border */
1242   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->black_gc, FALSE, MARGIN, 0, widgets->profile_width-1, widgets->profile_height-1);
1243
1244   g_object_unref ( G_OBJECT(pix) );
1245   g_object_unref ( G_OBJECT(gps_speed_gc) );
1246
1247 }
1248
1249 /**
1250  * Draw just the distance/time image
1251  */
1252 static void draw_dt ( GtkWidget *image, VikTrack *tr, PropWidgets *widgets )
1253 {
1254   GtkWidget *window;
1255   GdkPixmap *pix;
1256   gdouble maxd;
1257   guint i;
1258
1259   // Free previous allocation
1260   if ( widgets->distances )
1261     g_free ( widgets->distances );
1262
1263   widgets->distances = vik_track_make_distance_map ( tr, widgets->profile_width );
1264   if ( widgets->distances == NULL )
1265     return;
1266
1267   // Convert into appropriate units
1268   vik_units_distance_t dist_units = a_vik_get_units_distance ();
1269   if ( dist_units == VIK_UNITS_DISTANCE_MILES ) {
1270     for ( i = 0; i < widgets->profile_width; i++ ) {
1271       widgets->distances[i] = VIK_METERS_TO_MILES(widgets->distances[i]);
1272     }
1273   }
1274   else {
1275     // Metres - but want in kms
1276     for ( i = 0; i < widgets->profile_width; i++ ) {
1277       widgets->distances[i] = widgets->distances[i]/1000.0;
1278     }
1279   }
1280
1281   window = gtk_widget_get_toplevel (widgets->dist_box);
1282
1283   pix = gdk_pixmap_new( window->window, widgets->profile_width + MARGIN, widgets->profile_height, -1 );
1284
1285   gtk_image_set_from_pixmap ( GTK_IMAGE(image), pix, NULL );
1286
1287   // easy to work out min / max of distance!
1288   // Assign locally
1289   // mind = 0.0; - Thus not used
1290   if ( dist_units == VIK_UNITS_DISTANCE_MILES )
1291     maxd = VIK_METERS_TO_MILES(vik_track_get_length_including_gaps (tr));
1292   else
1293     maxd = vik_track_get_length_including_gaps (tr) / 1000.0;
1294
1295   /* Find suitable chunk index */
1296   gdouble dummy = 0.0; // expect this to remain the same! (not that it's used)
1297   get_new_min_and_chunk_index (0, maxd, chunksd, sizeof(chunksd)/sizeof(chunksd[0]), &dummy, &widgets->cid);
1298
1299   /* clear the image */
1300   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->bg_gc[0],
1301                      TRUE, 0, 0, MARGIN, widgets->profile_height);
1302   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->mid_gc[0],
1303                      TRUE, MARGIN, 0, widgets->profile_width, widgets->profile_height);
1304
1305   /* draw grid */
1306   for (i=0; i<=LINES; i++) {
1307     PangoFontDescription *pfd;
1308     PangoLayout *pl = gtk_widget_create_pango_layout (GTK_WIDGET(image), NULL);
1309     gchar s[32];
1310     int w, h;
1311
1312     pango_layout_set_alignment (pl, PANGO_ALIGN_RIGHT);
1313     pfd = pango_font_description_from_string (PROPWIN_LABEL_FONT);
1314     pango_layout_set_font_description (pl, pfd);
1315     pango_font_description_free (pfd);
1316     if ( dist_units == VIK_UNITS_DISTANCE_MILES )
1317       sprintf(s, _("%.1f miles"), ((LINES-i)*chunksd[widgets->cid]));
1318     else
1319       sprintf(s, _("%.1f km"), ((LINES-i)*chunksd[widgets->cid]));
1320
1321     pango_layout_set_text(pl, s, -1);
1322     pango_layout_get_pixel_size (pl, &w, &h);
1323     gdk_draw_layout(GDK_DRAWABLE(pix), window->style->fg_gc[0], MARGIN-w-3,
1324                     CLAMP((int)i*widgets->profile_height/LINES - h/2, 0, widgets->profile_height-h), pl);
1325
1326     gdk_draw_line (GDK_DRAWABLE(pix), window->style->dark_gc[0],
1327                    MARGIN, widgets->profile_height/LINES * i, MARGIN + widgets->profile_width, widgets->profile_height/LINES * i);
1328     g_object_unref ( G_OBJECT ( pl ) );
1329     pl = NULL;
1330   }
1331   
1332   /* draw distance */
1333   for ( i = 0; i < widgets->profile_width; i++ )
1334       gdk_draw_line ( GDK_DRAWABLE(pix), window->style->dark_gc[3],
1335                       i + MARGIN, widgets->profile_height, i + MARGIN, widgets->profile_height-widgets->profile_height*(widgets->distances[i])/(chunksd[widgets->cid]*LINES) );
1336
1337   // Show speed indicator
1338   if ( gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widgets->w_show_dist_speed)) ) {
1339     GdkGC *dist_speed_gc = gdk_gc_new ( window->window );
1340     GdkColor color;
1341     gdk_color_parse ( "red", &color );
1342     gdk_gc_set_rgb_fg_color ( dist_speed_gc, &color);
1343
1344     gdouble max_speed = 0;
1345     max_speed = widgets->max_speed * 110 / 100;
1346
1347     // This is just an indicator - no actual values can be inferred by user
1348     gint i;
1349     for ( i = 0; i < widgets->profile_width; i++ ) {
1350       int y_speed = widgets->profile_height - (widgets->profile_height * widgets->speeds[i])/max_speed;
1351       gdk_draw_rectangle(GDK_DRAWABLE(pix), dist_speed_gc, TRUE, i+MARGIN-2, y_speed-2, 4, 4);
1352     }
1353     g_object_unref ( G_OBJECT(dist_speed_gc) );
1354   }
1355
1356   /* draw border */
1357   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->black_gc, FALSE, MARGIN, 0, widgets->profile_width-1, widgets->profile_height-1);
1358
1359   g_object_unref ( G_OBJECT(pix) );
1360
1361 }
1362
1363 /**
1364  * Draw just the elevation/time image
1365  */
1366 static void draw_et ( GtkWidget *image, VikTrack *tr, PropWidgets *widgets )
1367 {
1368   GtkWidget *window;
1369   GdkPixmap *pix;
1370   gdouble mina,maxa;
1371   guint i;
1372
1373   // Free previous allocation
1374   if ( widgets->ats )
1375     g_free ( widgets->ats );
1376
1377   widgets->ats = vik_track_make_elevation_time_map ( tr, widgets->profile_width );
1378
1379   if ( widgets->ats == NULL )
1380     return;
1381
1382   // Convert into appropriate units
1383   vik_units_height_t height_units = a_vik_get_units_height ();
1384   if ( height_units == VIK_UNITS_HEIGHT_FEET ) {
1385     // Convert altitudes into feet units
1386     for ( i = 0; i < widgets->profile_width; i++ ) {
1387       widgets->ats[i] = VIK_METERS_TO_FEET(widgets->ats[i]);
1388     }
1389   }
1390   // Otherwise leave in metres
1391
1392   minmax_array(widgets->ats, &widgets->min_altitude, &widgets->max_altitude, TRUE, widgets->profile_width);
1393
1394   get_new_min_and_chunk_index_altitude (widgets->min_altitude, widgets->max_altitude, &widgets->draw_min_altitude, &widgets->cia);
1395
1396   // Assign locally
1397   mina = widgets->draw_min_altitude;
1398   maxa = widgets->max_altitude;
1399
1400   window = gtk_widget_get_toplevel (widgets->elev_time_box);
1401
1402   pix = gdk_pixmap_new( window->window, widgets->profile_width + MARGIN, widgets->profile_height, -1 );
1403
1404   gtk_image_set_from_pixmap ( GTK_IMAGE(image), pix, NULL );
1405
1406   /* clear the image */
1407   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->bg_gc[0],
1408                      TRUE, 0, 0, MARGIN, widgets->profile_height);
1409   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->mid_gc[0],
1410                      TRUE, MARGIN, 0, widgets->profile_width, widgets->profile_height);
1411
1412   /* draw grid */
1413   for (i=0; i<=LINES; i++) {
1414     PangoFontDescription *pfd;
1415     PangoLayout *pl = gtk_widget_create_pango_layout (GTK_WIDGET(image), NULL);
1416     gchar s[32];
1417     int w, h;
1418
1419     pango_layout_set_alignment (pl, PANGO_ALIGN_RIGHT);
1420     pfd = pango_font_description_from_string (PROPWIN_LABEL_FONT);
1421     pango_layout_set_font_description (pl, pfd);
1422     pango_font_description_free (pfd);
1423     switch (height_units) {
1424     case VIK_UNITS_HEIGHT_METRES:
1425       sprintf(s, "%8dm", (int)(mina + (LINES-i)*chunksa[widgets->cia]));
1426       break;
1427     case VIK_UNITS_HEIGHT_FEET:
1428       // NB values already converted into feet
1429       sprintf(s, "%8dft", (int)(mina + (LINES-i)*chunksa[widgets->cia]));
1430       break;
1431     default:
1432       sprintf(s, "--");
1433       g_critical("Houston, we've had a problem. height=%d", height_units);
1434     }
1435     pango_layout_set_text(pl, s, -1);
1436     pango_layout_get_pixel_size (pl, &w, &h);
1437     gdk_draw_layout(GDK_DRAWABLE(pix), window->style->fg_gc[0], MARGIN-w-3,
1438                     CLAMP((int)i*widgets->profile_height/LINES - h/2, 0, widgets->profile_height-h), pl);
1439
1440     gdk_draw_line (GDK_DRAWABLE(pix), window->style->dark_gc[0],
1441                    MARGIN, widgets->profile_height/LINES * i, MARGIN + widgets->profile_width, widgets->profile_height/LINES * i);
1442     g_object_unref ( G_OBJECT ( pl ) );
1443     pl = NULL;
1444   }
1445
1446   /* draw elevations */
1447   for ( i = 0; i < widgets->profile_width; i++ )
1448       gdk_draw_line ( GDK_DRAWABLE(pix), window->style->dark_gc[3],
1449                       i + MARGIN, widgets->profile_height, i + MARGIN, widgets->profile_height-widgets->profile_height*(widgets->ats[i]-mina)/(chunksa[widgets->cia]*LINES) );
1450
1451   // Show speed indicator
1452   if ( gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widgets->w_show_elev_speed)) ) {
1453     GdkGC *elev_speed_gc = gdk_gc_new ( window->window );
1454     GdkColor color;
1455     gdk_color_parse ( "red", &color );
1456     gdk_gc_set_rgb_fg_color ( elev_speed_gc, &color);
1457
1458     gdouble max_speed = 0;
1459     max_speed = widgets->max_speed * 110 / 100;
1460
1461     // This is just an indicator - no actual values can be inferred by user
1462     gint i;
1463     for ( i = 0; i < widgets->profile_width; i++ ) {
1464       int y_speed = widgets->profile_height - (widgets->profile_height * widgets->speeds[i])/max_speed;
1465       gdk_draw_rectangle(GDK_DRAWABLE(pix), elev_speed_gc, TRUE, i+MARGIN-2, y_speed-2, 4, 4);
1466     }
1467     g_object_unref ( G_OBJECT(elev_speed_gc) );
1468   }
1469
1470   /* draw border */
1471   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->black_gc, FALSE, MARGIN, 0, widgets->profile_width-1, widgets->profile_height-1);
1472
1473   g_object_unref ( G_OBJECT(pix) );
1474
1475 }
1476 #undef LINES
1477
1478 /**
1479  * Draw all graphs
1480  */
1481 static void draw_all_graphs ( GtkWidget *widget, gpointer *pass_along, gboolean resized )
1482 {
1483   VikTrack *tr = pass_along[0];
1484   PropWidgets *widgets = pass_along[3];
1485
1486   // Draw graphs even if they are not visible
1487
1488   GList *child = NULL;
1489   GtkWidget *image = NULL;
1490   GtkWidget *window = gtk_widget_get_toplevel(widget);
1491   gdouble pc = NAN;
1492   gdouble pc_blob = NAN;
1493
1494   // Draw elevations
1495   if (widgets->elev_box != NULL) {
1496
1497     // Saved image no longer any good as we've resized, so we remove it here
1498     if (resized && widgets->elev_graph_saved_img.img) {
1499       g_object_unref(widgets->elev_graph_saved_img.img);
1500       widgets->elev_graph_saved_img.img = NULL;
1501       widgets->elev_graph_saved_img.saved = FALSE;
1502     }
1503
1504     child = gtk_container_get_children(GTK_CONTAINER(widgets->elev_box));
1505     draw_elevations (GTK_WIDGET(child->data), tr, widgets );
1506
1507     image = GTK_WIDGET(child->data);
1508     g_list_free(child);
1509
1510     // Ensure marker or blob are redrawn if necessary
1511     if (widgets->is_marker_drawn || widgets->is_blob_drawn) {
1512
1513       pc = tp_percentage_by_distance ( tr, widgets->marker_tp, widgets->track_length );
1514       gdouble x_blob = -MARGIN - 1.0; // i.e. Don't draw unless we get a valid value
1515       gint y_blob = 0;
1516       if (widgets->is_blob_drawn) {
1517         pc_blob = tp_percentage_by_distance ( tr, widgets->blob_tp, widgets->track_length );
1518         if (!isnan(pc_blob)) {
1519           x_blob = (pc_blob * widgets->profile_width);
1520         }
1521         y_blob = blobby_altitude (x_blob, widgets);
1522       }
1523
1524       gdouble marker_x = -1.0; // i.e. Don't draw unless we get a valid value
1525       if (!isnan(pc)) {
1526         marker_x = (pc * widgets->profile_width) + MARGIN;
1527       }
1528
1529       save_image_and_draw_graph_marks (image,
1530                                        marker_x,
1531                                        window->style->black_gc,
1532                                        x_blob+MARGIN,
1533                                        y_blob,
1534                                        &widgets->elev_graph_saved_img,
1535                                        widgets->profile_width,
1536                                        widgets->profile_height,
1537                                        &widgets->is_marker_drawn,
1538                                        &widgets->is_blob_drawn);
1539     }
1540   }
1541
1542   // Draw speeds
1543   if (widgets->speed_box != NULL) {
1544
1545     // Saved image no longer any good as we've resized
1546     if (resized && widgets->speed_graph_saved_img.img) {
1547       g_object_unref(widgets->speed_graph_saved_img.img);
1548       widgets->speed_graph_saved_img.img = NULL;
1549       widgets->speed_graph_saved_img.saved = FALSE;
1550     }
1551
1552     child = gtk_container_get_children(GTK_CONTAINER(widgets->speed_box));
1553     draw_vt (GTK_WIDGET(child->data), tr, widgets );
1554
1555     image = GTK_WIDGET(child->data);
1556     g_list_free(child);
1557
1558     // Ensure marker or blob are redrawn if necessary
1559     if (widgets->is_marker_drawn || widgets->is_blob_drawn) {
1560
1561       pc = tp_percentage_by_time ( tr, widgets->marker_tp );
1562
1563       gdouble x_blob = -MARGIN - 1.0; // i.e. Don't draw unless we get a valid value
1564       gint    y_blob = 0;
1565       if (widgets->is_blob_drawn) {
1566         pc_blob = tp_percentage_by_time ( tr, widgets->blob_tp );
1567         if (!isnan(pc_blob)) {
1568           x_blob = (pc_blob * widgets->profile_width);
1569         }
1570          
1571         y_blob = blobby_speed (x_blob, widgets);
1572       }
1573
1574       gdouble marker_x = -1.0; // i.e. Don't draw unless we get a valid value
1575       if (!isnan(pc)) {
1576         marker_x = (pc * widgets->profile_width) + MARGIN;
1577       }
1578
1579       save_image_and_draw_graph_marks (image,
1580                                        marker_x,
1581                                        window->style->black_gc,
1582                                        x_blob+MARGIN,
1583                                        y_blob,
1584                                        &widgets->speed_graph_saved_img,
1585                                        widgets->profile_width,
1586                                        widgets->profile_height,
1587                                        &widgets->is_marker_drawn,
1588                                        &widgets->is_blob_drawn);
1589     }
1590   }
1591
1592   // Draw Distances
1593   if (widgets->dist_box != NULL) {
1594
1595     // Saved image no longer any good as we've resized
1596     if (resized && widgets->dist_graph_saved_img.img) {
1597       g_object_unref(widgets->dist_graph_saved_img.img);
1598       widgets->dist_graph_saved_img.img = NULL;
1599       widgets->dist_graph_saved_img.saved = FALSE;
1600     }
1601
1602     child = gtk_container_get_children(GTK_CONTAINER(widgets->dist_box));
1603     draw_dt (GTK_WIDGET(child->data), tr, widgets );
1604
1605     image = GTK_WIDGET(child->data);
1606     g_list_free(child);
1607
1608     // Ensure marker or blob are redrawn if necessary
1609     if (widgets->is_marker_drawn || widgets->is_blob_drawn) {
1610
1611       pc = tp_percentage_by_time ( tr, widgets->marker_tp );
1612
1613       gdouble x_blob = -MARGIN - 1.0; // i.e. Don't draw unless we get a valid value
1614       gint    y_blob = 0;
1615       if (widgets->is_blob_drawn) {
1616         pc_blob = tp_percentage_by_time ( tr, widgets->blob_tp );
1617         if (!isnan(pc_blob)) {
1618           x_blob = (pc_blob * widgets->profile_width);
1619         }
1620          
1621         y_blob = blobby_distance (x_blob, widgets);
1622       }
1623
1624       gdouble marker_x = -1.0; // i.e. Don't draw unless we get a valid value
1625       if (!isnan(pc)) {
1626         marker_x = (pc * widgets->profile_width) + MARGIN;
1627       }
1628
1629       save_image_and_draw_graph_marks (image,
1630                                        marker_x,
1631                                        window->style->black_gc,
1632                                        x_blob+MARGIN,
1633                                        y_blob,
1634                                        &widgets->dist_graph_saved_img,
1635                                        widgets->profile_width,
1636                                        widgets->profile_height,
1637                                        &widgets->is_marker_drawn,
1638                                        &widgets->is_blob_drawn);
1639     }
1640   }
1641
1642   // Draw Elevations in timely manner
1643   if (widgets->elev_time_box != NULL) {
1644
1645     // Saved image no longer any good as we've resized
1646     if (resized && widgets->elev_time_graph_saved_img.img) {
1647       g_object_unref(widgets->elev_time_graph_saved_img.img);
1648       widgets->elev_time_graph_saved_img.img = NULL;
1649       widgets->elev_time_graph_saved_img.saved = FALSE;
1650     }
1651
1652     child = gtk_container_get_children(GTK_CONTAINER(widgets->elev_time_box));
1653     draw_et (GTK_WIDGET(child->data), tr, widgets );
1654
1655     image = GTK_WIDGET(child->data);
1656     g_list_free(child);
1657
1658     // Ensure marker or blob are redrawn if necessary
1659     if (widgets->is_marker_drawn || widgets->is_blob_drawn) {
1660
1661       pc = tp_percentage_by_time ( tr, widgets->marker_tp );
1662
1663       gdouble x_blob = -MARGIN - 1.0; // i.e. Don't draw unless we get a valid value
1664       gint    y_blob = 0;
1665       if (widgets->is_blob_drawn) {
1666         pc_blob = tp_percentage_by_time ( tr, widgets->blob_tp );
1667         if (!isnan(pc_blob)) {
1668           x_blob = (pc_blob * widgets->profile_width);
1669         }
1670         y_blob = blobby_altitude_time (x_blob, widgets);
1671       }
1672
1673       gdouble marker_x = -1.0; // i.e. Don't draw unless we get a valid value
1674       if (!isnan(pc)) {
1675         marker_x = (pc * widgets->profile_width) + MARGIN;
1676       }
1677
1678       save_image_and_draw_graph_marks (image,
1679                                        marker_x,
1680                                        window->style->black_gc,
1681                                        x_blob+MARGIN,
1682                                        y_blob,
1683                                        &widgets->elev_time_graph_saved_img,
1684                                        widgets->profile_width,
1685                                        widgets->profile_height,
1686                                        &widgets->is_marker_drawn,
1687                                        &widgets->is_blob_drawn);
1688     }
1689   }
1690
1691 }
1692
1693 /**
1694  * Configure/Resize the profile & speed/time images
1695  */
1696 static gboolean configure_event ( GtkWidget *widget, GdkEventConfigure *event, gpointer *pass_along )
1697 {
1698   PropWidgets *widgets = pass_along[3];
1699
1700   if (widgets->configure_dialog) {
1701     // Determine size offsets between dialog size and size for images
1702     // Only on the initialisation of the dialog
1703     widgets->profile_width_offset = event->width - widgets->profile_width;
1704     widgets->profile_height_offset = event->height - widgets->profile_height;
1705     widgets->configure_dialog = FALSE;
1706
1707     // Without this the settting, the dialog will only grow in vertical size - one can not then make it smaller!
1708     gtk_widget_set_size_request ( widget, widgets->profile_width+widgets->profile_width_offset, widgets->profile_height );
1709     // In fact this allows one to compress it a bit more vertically as I don't add on the height offset
1710   }
1711   else {
1712     widgets->profile_width_old = widgets->profile_width;
1713     widgets->profile_height_old = widgets->profile_height;
1714   }
1715
1716   // Now adjust From Dialog size to get image size
1717   widgets->profile_width = event->width - widgets->profile_width_offset;
1718   widgets->profile_height = event->height - widgets->profile_height_offset;
1719
1720   // ATM we receive configure_events when the dialog is moved and so no further action is necessary
1721   if ( !widgets->configure_dialog &&
1722        (widgets->profile_width_old == widgets->profile_width) && (widgets->profile_height_old == widgets->profile_height) )
1723     return FALSE;
1724
1725   // Draw stuff
1726   draw_all_graphs ( widget, pass_along, TRUE );
1727
1728   return FALSE;
1729 }
1730
1731 /**
1732  * Create height profile widgets including the image and callbacks
1733  */
1734 GtkWidget *vik_trw_layer_create_profile ( GtkWidget *window, VikTrack *tr, gpointer vlp, VikViewport *vvp, PropWidgets *widgets, gdouble *min_alt, gdouble *max_alt)
1735 {
1736   GdkPixmap *pix;
1737   GtkWidget *image;
1738   GtkWidget *eventbox;
1739   gpointer *pass_along;
1740
1741   // First allocation
1742   widgets->altitudes = vik_track_make_elevation_map ( tr, widgets->profile_width );
1743
1744   if ( widgets->altitudes == NULL ) {
1745     *min_alt = *max_alt = VIK_DEFAULT_ALTITUDE;
1746     return NULL;
1747   }
1748
1749   minmax_array(widgets->altitudes, min_alt, max_alt, TRUE, widgets->profile_width);
1750   
1751   pix = gdk_pixmap_new( window->window, widgets->profile_width + MARGIN, widgets->profile_height, -1 );
1752   image = gtk_image_new_from_pixmap ( pix, NULL );
1753
1754   g_object_unref ( G_OBJECT(pix) );
1755
1756   pass_along = g_malloc ( sizeof(gpointer) * 4 ); /* FIXME: mem leak -- never be freed */
1757   pass_along[0] = tr;
1758   pass_along[1] = vlp;
1759   pass_along[2] = vvp;
1760   pass_along[3] = widgets;
1761
1762   eventbox = gtk_event_box_new ();
1763   g_signal_connect ( G_OBJECT(eventbox), "button_press_event", G_CALLBACK(track_profile_click), pass_along );
1764   g_signal_connect ( G_OBJECT(eventbox), "motion_notify_event", G_CALLBACK(track_profile_move), pass_along );
1765   g_signal_connect_swapped ( G_OBJECT(eventbox), "destroy", G_CALLBACK(g_free), pass_along );
1766   gtk_container_add ( GTK_CONTAINER(eventbox), image );
1767   gtk_widget_set_events (eventbox, GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_STRUCTURE_MASK);
1768
1769   return eventbox;
1770 }
1771
1772 /**
1773  * Create speed/time widgets including the image and callbacks
1774  */
1775 GtkWidget *vik_trw_layer_create_vtdiag ( GtkWidget *window, VikTrack *tr, gpointer vlp, VikViewport *vvp, PropWidgets *widgets)
1776 {
1777   GdkPixmap *pix;
1778   GtkWidget *image;
1779   GtkWidget *eventbox;
1780   gpointer *pass_along;
1781
1782   // First allocation
1783   widgets->speeds = vik_track_make_speed_map ( tr, widgets->profile_width );
1784   if ( widgets->speeds == NULL )
1785     return NULL;
1786
1787   pass_along = g_malloc ( sizeof(gpointer) * 4 ); /* FIXME: mem leak -- never be freed */
1788   pass_along[0] = tr;
1789   pass_along[1] = vlp;
1790   pass_along[2] = vvp;
1791   pass_along[3] = widgets;
1792
1793   pix = gdk_pixmap_new( window->window, widgets->profile_width + MARGIN, widgets->profile_height, -1 );
1794   image = gtk_image_new_from_pixmap ( pix, NULL );
1795
1796 #if 0
1797   /* XXX this can go out, it's just a helpful dev tool */
1798   {
1799     int j;
1800     GdkGC **colors[8] = { window->style->bg_gc,
1801                           window->style->fg_gc,
1802                           window->style->light_gc,
1803                           window->style->dark_gc,
1804                           window->style->mid_gc,
1805                           window->style->text_gc,
1806                           window->style->base_gc,
1807                           window->style->text_aa_gc };
1808     for (i=0; i<5; i++) {
1809       for (j=0; j<8; j++) {
1810         gdk_draw_rectangle(GDK_DRAWABLE(pix), colors[j][i],
1811                            TRUE, i*20, j*20, 20, 20);
1812         gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->black_gc,
1813                            FALSE, i*20, j*20, 20, 20);
1814       }
1815     }
1816   }
1817 #endif
1818
1819   g_object_unref ( G_OBJECT(pix) );
1820
1821   eventbox = gtk_event_box_new ();
1822   g_signal_connect ( G_OBJECT(eventbox), "button_press_event", G_CALLBACK(track_vt_click), pass_along );
1823   g_signal_connect ( G_OBJECT(eventbox), "motion_notify_event", G_CALLBACK(track_vt_move), pass_along );
1824   g_signal_connect_swapped ( G_OBJECT(eventbox), "destroy", G_CALLBACK(g_free), pass_along );
1825   gtk_container_add ( GTK_CONTAINER(eventbox), image );
1826   gtk_widget_set_events (eventbox, GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK);
1827
1828   return eventbox;
1829 }
1830
1831 /**
1832  * Create distance / time widgets including the image and callbacks
1833  */
1834 GtkWidget *vik_trw_layer_create_dtdiag ( GtkWidget *window, VikTrack *tr, gpointer vlp, VikViewport *vvp, PropWidgets *widgets)
1835 {
1836   GdkPixmap *pix;
1837   GtkWidget *image;
1838   GtkWidget *eventbox;
1839   gpointer *pass_along;
1840
1841   // First allocation
1842   widgets->distances = vik_track_make_distance_map ( tr, widgets->profile_width );
1843   if ( widgets->distances == NULL )
1844     return NULL;
1845
1846   pass_along = g_malloc ( sizeof(gpointer) * 4 ); /* FIXME: mem leak -- never be freed */
1847   pass_along[0] = tr;
1848   pass_along[1] = vlp;
1849   pass_along[2] = vvp;
1850   pass_along[3] = widgets;
1851
1852   pix = gdk_pixmap_new( window->window, widgets->profile_width + MARGIN, widgets->profile_height, -1 );
1853   image = gtk_image_new_from_pixmap ( pix, NULL );
1854
1855   g_object_unref ( G_OBJECT(pix) );
1856
1857   eventbox = gtk_event_box_new ();
1858   g_signal_connect ( G_OBJECT(eventbox), "button_press_event", G_CALLBACK(track_dt_click), pass_along );
1859   g_signal_connect ( G_OBJECT(eventbox), "motion_notify_event", G_CALLBACK(track_dt_move), pass_along );
1860   g_signal_connect_swapped ( G_OBJECT(eventbox), "destroy", G_CALLBACK(g_free), pass_along );
1861   gtk_container_add ( GTK_CONTAINER(eventbox), image );
1862   gtk_widget_set_events (eventbox, GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK);
1863
1864   return eventbox;
1865 }
1866
1867 /**
1868  * Create elevation / time widgets including the image and callbacks
1869  */
1870 GtkWidget *vik_trw_layer_create_etdiag ( GtkWidget *window, VikTrack *tr, gpointer vlp, VikViewport *vvp, PropWidgets *widgets)
1871 {
1872   GdkPixmap *pix;
1873   GtkWidget *image;
1874   GtkWidget *eventbox;
1875   gpointer *pass_along;
1876
1877   // First allocation
1878   widgets->ats = vik_track_make_elevation_time_map ( tr, widgets->profile_width );
1879   if ( widgets->ats == NULL )
1880     return NULL;
1881
1882   pass_along = g_malloc ( sizeof(gpointer) * 4 ); /* FIXME: mem leak -- never be freed */
1883   pass_along[0] = tr;
1884   pass_along[1] = vlp;
1885   pass_along[2] = vvp;
1886   pass_along[3] = widgets;
1887
1888   pix = gdk_pixmap_new( window->window, widgets->profile_width + MARGIN, widgets->profile_height, -1 );
1889   image = gtk_image_new_from_pixmap ( pix, NULL );
1890
1891   g_object_unref ( G_OBJECT(pix) );
1892
1893   eventbox = gtk_event_box_new ();
1894   g_signal_connect ( G_OBJECT(eventbox), "button_press_event", G_CALLBACK(track_et_click), pass_along );
1895   g_signal_connect ( G_OBJECT(eventbox), "motion_notify_event", G_CALLBACK(track_et_move), pass_along );
1896   g_signal_connect_swapped ( G_OBJECT(eventbox), "destroy", G_CALLBACK(g_free), pass_along );
1897   gtk_container_add ( GTK_CONTAINER(eventbox), image );
1898   gtk_widget_set_events (eventbox, GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK);
1899
1900   return eventbox;
1901 }
1902 #undef MARGIN
1903
1904 static void propwin_response_cb( GtkDialog *dialog, gint resp, PropWidgets *widgets)
1905 {
1906   VikTrack *tr = widgets->tr;
1907   VikTrwLayer *vtl = widgets->vtl;
1908   gboolean keep_dialog = FALSE;
1909
1910   /* FIXME: check and make sure the track still exists before doing anything to it */
1911   /* Note: destroying diaglog (eg, parent window exit) won't give "response" */
1912   switch (resp) {
1913     case GTK_RESPONSE_DELETE_EVENT: /* received delete event (not from buttons) */
1914     case GTK_RESPONSE_REJECT:
1915       break;
1916     case GTK_RESPONSE_ACCEPT:
1917       vik_track_set_comment(tr, gtk_entry_get_text(GTK_ENTRY(widgets->w_comment)));
1918       break;
1919     case VIK_TRW_LAYER_PROPWIN_REVERSE:
1920       vik_track_reverse(tr);
1921       vik_layer_emit_update ( VIK_LAYER(vtl) );
1922       break;
1923     case VIK_TRW_LAYER_PROPWIN_DEL_DUP:
1924       vik_track_remove_dup_points(tr);
1925       /* above operation could have deleted current_tp or last_tp */
1926       trw_layer_cancel_tps_of_track ( vtl, widgets->track_name );
1927       vik_layer_emit_update ( VIK_LAYER(vtl) );
1928       break;
1929     case VIK_TRW_LAYER_PROPWIN_SPLIT:
1930       {
1931         /* get new tracks, add them, resolve naming conflicts (free if cancel), and delete old. old can still exist on clipboard. */
1932         guint ntracks;
1933         VikTrack **tracks = vik_track_split_into_segments(tr, &ntracks);
1934         gchar *new_tr_name;
1935         guint i;
1936         for ( i = 0; i < ntracks; i++ )
1937         {
1938           g_assert ( tracks[i] );
1939           new_tr_name = g_strdup_printf("%s #%d", widgets->track_name, i+1);
1940           /* if ( (wp_exists) && (! overwrite) ) */
1941           /* don't need to upper case new_tr_name because old tr name was uppercase */
1942           if ( vik_trw_layer_get_track(vtl, new_tr_name ) && 
1943              ( ! a_dialog_yes_or_no ( VIK_GTK_WINDOW_FROM_LAYER(vtl), "The track \"%s\" exists, do you wish to overwrite it?", new_tr_name ) ) )
1944           {
1945             gchar *new_new_tr_name = a_dialog_new_track ( VIK_GTK_WINDOW_FROM_LAYER(vtl), vik_trw_layer_get_tracks(vtl), NULL );
1946             g_free ( new_tr_name );
1947             if (new_new_tr_name)
1948               new_tr_name = new_new_tr_name;
1949             else
1950             {
1951               new_tr_name = NULL;
1952               vik_track_free ( tracks[i] );
1953             }
1954           }
1955           if ( new_tr_name )
1956             vik_trw_layer_add_track ( vtl, new_tr_name, tracks[i] );
1957         }
1958         if ( tracks )
1959         {
1960           g_free ( tracks );
1961           /* Don't let track destroy this dialog */
1962           vik_track_clear_property_dialog(tr);
1963           vik_trw_layer_delete_track ( vtl, widgets->track_name );
1964           vik_layer_emit_update ( VIK_LAYER(vtl) ); /* chase thru the hoops */
1965         }
1966       }
1967       break;
1968     case VIK_TRW_LAYER_PROPWIN_SPLIT_MARKER:
1969       {
1970         GList *iter = tr->trackpoints;
1971         while ((iter = iter->next)) {
1972           if (widgets->marker_tp == VIK_TRACKPOINT(iter->data))
1973             break;
1974         }
1975         if (iter == NULL) {
1976           a_dialog_msg(VIK_GTK_WINDOW_FROM_LAYER(vtl), GTK_MESSAGE_ERROR,
1977                   _("Failed spliting track. Track unchanged"), NULL);
1978           keep_dialog = TRUE;
1979           break;
1980         }
1981
1982         gchar *r_name = g_strdup_printf("%s #R", widgets->track_name);
1983         if (vik_trw_layer_get_track(vtl, r_name ) && 
1984              ( ! a_dialog_yes_or_no( VIK_GTK_WINDOW_FROM_LAYER(vtl),
1985               "The track \"%s\" exists, do you wish to overwrite it?", r_name)))
1986         {
1987           gchar *new_r_name = a_dialog_new_track( VIK_GTK_WINDOW_FROM_LAYER(vtl), vik_trw_layer_get_tracks(vtl), NULL );
1988             if (new_r_name) {
1989               g_free( r_name );
1990               r_name = new_r_name;
1991             }
1992             else {
1993               a_dialog_msg(VIK_GTK_WINDOW_FROM_LAYER(vtl), GTK_MESSAGE_WARNING,
1994                   _("Operation Aborted. Track unchanged"), NULL);
1995               keep_dialog = TRUE;
1996               break;
1997             }
1998         }
1999         iter->prev->next = NULL;
2000         iter->prev = NULL;
2001         VikTrack *tr_right = vik_track_new();
2002         if ( tr->comment )
2003           vik_track_set_comment ( tr_right, tr->comment );
2004         tr_right->visible = tr->visible;
2005         tr_right->trackpoints = iter;
2006
2007         vik_trw_layer_add_track(vtl, r_name, tr_right);
2008         vik_layer_emit_update ( VIK_LAYER(vtl) );
2009       }
2010       break;
2011     default:
2012       fprintf(stderr, "DEBUG: unknown response\n");
2013       return;
2014   }
2015
2016   /* Keep same behaviour for now: destroy dialog if click on any button */
2017   if (!keep_dialog) {
2018     prop_widgets_free(widgets);
2019     vik_track_clear_property_dialog(tr);
2020     gtk_widget_destroy ( GTK_WIDGET(dialog) );
2021   }
2022 }
2023
2024 /**
2025  * Force a redraw when checkbutton has been toggled to show/hide that information
2026  */
2027 static void checkbutton_toggle_cb ( GtkToggleButton *togglebutton, gpointer *pass_along, gpointer dummy)
2028 {
2029   PropWidgets *widgets = pass_along[3];
2030   // Even though not resized, we'll pretend it is -
2031   //  as this invalidates the saved images (since the image may have changed)
2032   draw_all_graphs ( widgets->dialog, pass_along, TRUE);
2033 }
2034
2035 /**
2036  *  Create the widgets for the given graph tab
2037  */
2038 static GtkWidget *create_graph_page ( GtkWidget *graph,
2039                                       const gchar *markup,
2040                                       GtkWidget *value,
2041                                       const gchar *markup2,
2042                                       GtkWidget *value2,
2043                                       GtkWidget *checkbutton1,
2044                                       gboolean checkbutton1_default,
2045                                       GtkWidget *checkbutton2,
2046                                       gboolean checkbutton2_default )
2047 {
2048   GtkWidget *hbox = gtk_hbox_new ( FALSE, 10 );
2049   GtkWidget *vbox = gtk_vbox_new ( FALSE, 10 );
2050   GtkWidget *label = gtk_label_new (NULL);
2051   GtkWidget *label2 = gtk_label_new (NULL);
2052   gtk_box_pack_start (GTK_BOX(vbox), graph, FALSE, FALSE, 0);
2053   gtk_label_set_markup ( GTK_LABEL(label), markup );
2054   gtk_label_set_markup ( GTK_LABEL(label2), markup2 );
2055   gtk_box_pack_start (GTK_BOX(hbox), label, FALSE, FALSE, 0);
2056   gtk_box_pack_start (GTK_BOX(hbox), value, FALSE, FALSE, 0);
2057   gtk_box_pack_start (GTK_BOX(hbox), label2, FALSE, FALSE, 0);
2058   gtk_box_pack_start (GTK_BOX(hbox), value2, FALSE, FALSE, 0);
2059   if (checkbutton2) {
2060     gtk_box_pack_end (GTK_BOX(hbox), checkbutton2, FALSE, FALSE, 0);
2061     gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON(checkbutton2), checkbutton2_default);
2062   }
2063   if (checkbutton1) {
2064     gtk_box_pack_end (GTK_BOX(hbox), checkbutton1, FALSE, FALSE, 0);
2065     gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON(checkbutton1), checkbutton1_default);
2066   }
2067   gtk_box_pack_start (GTK_BOX(vbox), hbox, FALSE, FALSE, 0);
2068
2069   return vbox;
2070 }
2071
2072 void vik_trw_layer_propwin_run ( GtkWindow *parent, VikTrwLayer *vtl, VikTrack *tr, gpointer vlp, gchar *track_name, VikViewport *vvp )
2073 {
2074   /* FIXME: free widgets when destroy signal received */
2075   PropWidgets *widgets = prop_widgets_new();
2076   widgets->vtl = vtl;
2077   widgets->tr = tr;
2078   widgets->profile_width  = PROPWIN_PROFILE_WIDTH;
2079   widgets->profile_height = PROPWIN_PROFILE_HEIGHT;
2080   widgets->track_name = track_name;
2081   gchar *title = g_strdup_printf(_("%s - Track Properties"), track_name);
2082   GtkWidget *dialog = gtk_dialog_new_with_buttons (title,
2083                          parent,
2084                          GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_NO_SEPARATOR,
2085                          GTK_STOCK_CANCEL, GTK_RESPONSE_REJECT,
2086                          _("Split at _Marker"), VIK_TRW_LAYER_PROPWIN_SPLIT_MARKER,
2087                          _("Split _Segments"), VIK_TRW_LAYER_PROPWIN_SPLIT,
2088                          _("_Reverse"),        VIK_TRW_LAYER_PROPWIN_REVERSE,
2089                          _("_Delete Dupl."),   VIK_TRW_LAYER_PROPWIN_DEL_DUP,
2090                          GTK_STOCK_OK,     GTK_RESPONSE_ACCEPT,
2091                          NULL);
2092   widgets->dialog = dialog;
2093   g_free(title);
2094   g_signal_connect(dialog, "response", G_CALLBACK(propwin_response_cb), widgets);
2095   GtkTable *table;
2096   gdouble tr_len;
2097   guint32 tp_count, seg_count;
2098
2099   gdouble min_alt, max_alt;
2100   widgets->elev_box = vik_trw_layer_create_profile(GTK_WIDGET(parent), tr, vlp, vvp, widgets, &min_alt, &max_alt);
2101   widgets->speed_box = vik_trw_layer_create_vtdiag(GTK_WIDGET(parent), tr, vlp, vvp, widgets);
2102   widgets->dist_box = vik_trw_layer_create_dtdiag(GTK_WIDGET(parent), tr, vlp, vvp, widgets);
2103   widgets->elev_time_box = vik_trw_layer_create_etdiag(GTK_WIDGET(parent), tr, vlp, vvp, widgets);
2104   GtkWidget *graphs = gtk_notebook_new();
2105
2106   GtkWidget *content[20];
2107   int cnt;
2108   int i;
2109
2110   static gchar *label_texts[] = { N_("<b>Comment:</b>"), N_("<b>Track Length:</b>"), N_("<b>Trackpoints:</b>"), N_("<b>Segments:</b>"), N_("<b>Duplicate Points:</b>"), N_("<b>Max Speed:</b>"), N_("<b>Avg. Speed:</b>"), N_("<b>Avg. Dist. Between TPs:</b>"), N_("<b>Elevation Range:</b>"), N_("<b>Total Elevation Gain/Loss:</b>"), N_("<b>Start:</b>"), N_("<b>End:</b>"), N_("<b>Duration:</b>") };
2111   static gchar tmp_buf[50];
2112   gdouble tmp_speed;
2113
2114   cnt = 0;
2115   widgets->w_comment = gtk_entry_new ();
2116   if ( tr->comment )
2117     gtk_entry_set_text ( GTK_ENTRY(widgets->w_comment), tr->comment );
2118   g_signal_connect_swapped ( widgets->w_comment, "activate", G_CALLBACK(a_dialog_response_accept), GTK_DIALOG(dialog) );
2119   content[cnt++] = widgets->w_comment;
2120
2121   vik_units_distance_t dist_units = a_vik_get_units_distance ();
2122
2123   tr_len = widgets->track_length = vik_track_get_length(tr);
2124   switch (dist_units) {
2125   case VIK_UNITS_DISTANCE_KILOMETRES:
2126     g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f km", tr_len/1000.0 );
2127     break;
2128   case VIK_UNITS_DISTANCE_MILES:
2129     g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f miles", VIK_METERS_TO_MILES(tr_len) );
2130     break;
2131   default:
2132     g_critical("Houston, we've had a problem. distance=%d", dist_units);
2133   }
2134   widgets->w_track_length = content[cnt++] = gtk_label_new ( tmp_buf );
2135
2136   tp_count = vik_track_get_tp_count(tr);
2137   g_snprintf(tmp_buf, sizeof(tmp_buf), "%u", tp_count );
2138   widgets->w_tp_count = content[cnt++] = gtk_label_new ( tmp_buf );
2139
2140   seg_count = vik_track_get_segment_count(tr) ;
2141   g_snprintf(tmp_buf, sizeof(tmp_buf), "%u", seg_count );
2142   widgets->w_segment_count = content[cnt++] = gtk_label_new ( tmp_buf );
2143
2144   g_snprintf(tmp_buf, sizeof(tmp_buf), "%lu", vik_track_get_dup_point_count(tr) );
2145   widgets->w_duptp_count = content[cnt++] = gtk_label_new ( tmp_buf );
2146
2147   vik_units_speed_t speed_units = a_vik_get_units_speed ();
2148   tmp_speed = vik_track_get_max_speed(tr);
2149   if ( tmp_speed == 0 )
2150     g_snprintf(tmp_buf, sizeof(tmp_buf), _("No Data"));
2151   else {
2152     switch (speed_units) {
2153     case VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
2154       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f km/h", VIK_MPS_TO_KPH(tmp_speed));
2155       break;
2156     case VIK_UNITS_SPEED_MILES_PER_HOUR:
2157       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f mph", VIK_MPS_TO_MPH(tmp_speed));
2158       break;
2159     case VIK_UNITS_SPEED_METRES_PER_SECOND:
2160       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f m/s", tmp_speed );
2161       break;
2162     case VIK_UNITS_SPEED_KNOTS:
2163       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f knots", VIK_MPS_TO_KNOTS(tmp_speed));
2164       break;
2165     default:
2166       g_snprintf (tmp_buf, sizeof(tmp_buf), "--" );
2167       g_critical("Houston, we've had a problem. speed=%d", speed_units);
2168     }
2169   }
2170   widgets->w_max_speed = content[cnt++] = gtk_label_new ( tmp_buf );
2171
2172   tmp_speed = vik_track_get_average_speed(tr);
2173   if ( tmp_speed == 0 )
2174     g_snprintf(tmp_buf, sizeof(tmp_buf), _("No Data"));
2175   else {
2176     switch (speed_units) {
2177     case VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
2178       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f km/h", VIK_MPS_TO_KPH(tmp_speed));
2179       break;
2180     case VIK_UNITS_SPEED_MILES_PER_HOUR:
2181       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f mph", VIK_MPS_TO_MPH(tmp_speed));
2182       break;
2183     case VIK_UNITS_SPEED_METRES_PER_SECOND:
2184       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f m/s", tmp_speed );
2185       break;
2186     case VIK_UNITS_SPEED_KNOTS:
2187       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f knots", VIK_MPS_TO_KNOTS(tmp_speed));
2188       break;
2189     default:
2190       g_snprintf (tmp_buf, sizeof(tmp_buf), "--" );
2191       g_critical("Houston, we've had a problem. speed=%d", speed_units);
2192     }
2193   }
2194   widgets->w_avg_speed = content[cnt++] = gtk_label_new ( tmp_buf );
2195
2196   switch (dist_units) {
2197   case VIK_UNITS_DISTANCE_KILOMETRES:
2198     // Even though kilometres, the average distance between points is going to be quite small so keep in metres
2199     g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f m", (tp_count - seg_count) == 0 ? 0 : tr_len / ( tp_count - seg_count ) );
2200     break;
2201   case VIK_UNITS_DISTANCE_MILES:
2202     g_snprintf(tmp_buf, sizeof(tmp_buf), "%.3f miles", (tp_count - seg_count) == 0 ? 0 : VIK_METERS_TO_MILES(tr_len / ( tp_count - seg_count )) );
2203     break;
2204   default:
2205     g_critical("Houston, we've had a problem. distance=%d", dist_units);
2206   }
2207   widgets->w_avg_dist = content[cnt++] = gtk_label_new ( tmp_buf );
2208
2209   vik_units_height_t height_units = a_vik_get_units_height ();
2210   if ( min_alt == VIK_DEFAULT_ALTITUDE )
2211     g_snprintf(tmp_buf, sizeof(tmp_buf), _("No Data"));
2212   else {
2213     switch (height_units) {
2214     case VIK_UNITS_HEIGHT_METRES:
2215       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.0f m - %.0f m", min_alt, max_alt );
2216       break;
2217     case VIK_UNITS_HEIGHT_FEET:
2218       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.0f feet - %.0f feet", VIK_METERS_TO_FEET(min_alt), VIK_METERS_TO_FEET(max_alt) );
2219       break;
2220     default:
2221       g_snprintf(tmp_buf, sizeof(tmp_buf), "--" );
2222       g_critical("Houston, we've had a problem. height=%d", height_units);
2223     }
2224   }
2225   widgets->w_elev_range = content[cnt++] = gtk_label_new ( tmp_buf );
2226
2227   vik_track_get_total_elevation_gain(tr, &max_alt, &min_alt );
2228   if ( min_alt == VIK_DEFAULT_ALTITUDE )
2229     g_snprintf(tmp_buf, sizeof(tmp_buf), _("No Data"));
2230   else {
2231     switch (height_units) {
2232     case VIK_UNITS_HEIGHT_METRES:
2233       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.0f m / %.0f m", max_alt, min_alt );
2234       break;
2235     case VIK_UNITS_HEIGHT_FEET:
2236       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.0f feet / %.0f feet", VIK_METERS_TO_FEET(max_alt), VIK_METERS_TO_FEET(min_alt) );
2237       break;
2238     default:
2239       g_snprintf(tmp_buf, sizeof(tmp_buf), "--" );
2240       g_critical("Houston, we've had a problem. height=%d", height_units);
2241     }
2242   }
2243   widgets->w_elev_gain = content[cnt++] = gtk_label_new ( tmp_buf );
2244
2245 #if 0
2246 #define PACK(w) gtk_box_pack_start (GTK_BOX(right_vbox), w, FALSE, FALSE, 0);
2247   gtk_box_pack_start (GTK_BOX(right_vbox), e_cmt, FALSE, FALSE, 0); 
2248   PACK(l_len);
2249   PACK(l_tps);
2250   PACK(l_segs);
2251   PACK(l_dups);
2252   PACK(l_maxs);
2253   PACK(l_avgs);
2254   PACK(l_avgd);
2255   PACK(l_elev);
2256   PACK(l_galo);
2257 #undef PACK;
2258 #endif
2259
2260   if ( tr->trackpoints && VIK_TRACKPOINT(tr->trackpoints->data)->timestamp )
2261   {
2262     time_t t1, t2;
2263     t1 = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
2264     t2 = VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->timestamp;
2265
2266     strncpy(tmp_buf, ctime(&t1), sizeof(tmp_buf));
2267     tmp_buf[sizeof(tmp_buf)-1] = 0;
2268     g_strchomp(tmp_buf);
2269     widgets->w_time_start = content[cnt++] = gtk_label_new(tmp_buf);
2270
2271     strncpy(tmp_buf, ctime(&t2), sizeof(tmp_buf));
2272     tmp_buf[sizeof(tmp_buf)-1] = 0;
2273     g_strchomp(tmp_buf);
2274     widgets->w_time_end = content[cnt++] = gtk_label_new(tmp_buf);
2275
2276     g_snprintf(tmp_buf, sizeof(tmp_buf), _("%d minutes"), (int)(t2-t1)/60);
2277     widgets->w_time_dur = content[cnt++] = gtk_label_new(tmp_buf);
2278   } else {
2279     widgets->w_time_start = content[cnt++] = gtk_label_new(_("No Data"));
2280     widgets->w_time_end = content[cnt++] = gtk_label_new(_("No Data"));
2281     widgets->w_time_dur = content[cnt++] = gtk_label_new(_("No Data"));
2282   }
2283
2284   table = GTK_TABLE(gtk_table_new (cnt, 2, FALSE));
2285   gtk_table_set_col_spacing (table, 0, 10);
2286   for (i=0; i<cnt; i++) {
2287     GtkWidget *label;
2288
2289     // Settings so the text positioning only moves around vertically when the dialog is resized
2290     // This also gives more room to see the track comment
2291     label = gtk_label_new(NULL);
2292     gtk_misc_set_alignment ( GTK_MISC(label), 1, 0.5 ); // Position text centrally in vertical plane
2293     gtk_label_set_markup ( GTK_LABEL(label), _(label_texts[i]) );
2294     gtk_table_attach ( table, label, 0, 1, i, i+1, GTK_FILL, GTK_SHRINK, 0, 0 );
2295     if (GTK_IS_MISC(content[i])) {
2296       gtk_misc_set_alignment ( GTK_MISC(content[i]), 0, 0.5 );
2297     }
2298     gtk_table_attach_defaults ( table, content[i], 1, 2, i, i+1 );
2299   }
2300
2301   gtk_notebook_append_page(GTK_NOTEBOOK(graphs), GTK_WIDGET(table), gtk_label_new(_("Statistics")));
2302
2303   gpointer *pass_along;
2304   pass_along = g_malloc ( sizeof(gpointer) * 4 ); /* FIXME: mem leak -- never be freed */
2305   pass_along[0] = tr;
2306   pass_along[1] = vlp;
2307   pass_along[2] = vvp;
2308   pass_along[3] = widgets;
2309
2310   if ( widgets->elev_box ) {
2311     GtkWidget *page = NULL;
2312     widgets->w_cur_dist = gtk_label_new(_("No Data"));
2313     widgets->w_cur_elevation = gtk_label_new(_("No Data"));
2314     widgets->w_show_dem = gtk_check_button_new_with_mnemonic(_("Show D_EM"));
2315     widgets->w_show_alt_gps_speed = gtk_check_button_new_with_mnemonic(_("Show _GPS Speed"));
2316     page = create_graph_page (widgets->elev_box,
2317                               _("<b>Track Distance:</b>"), widgets->w_cur_dist,
2318                               _("<b>Track Height:</b>"), widgets->w_cur_elevation,
2319                               widgets->w_show_dem, TRUE,
2320                               widgets->w_show_alt_gps_speed, TRUE);
2321     g_signal_connect (widgets->w_show_dem, "toggled", G_CALLBACK (checkbutton_toggle_cb), pass_along);
2322     g_signal_connect (widgets->w_show_alt_gps_speed, "toggled", G_CALLBACK (checkbutton_toggle_cb), pass_along);
2323     gtk_notebook_append_page(GTK_NOTEBOOK(graphs), page, gtk_label_new(_("Elevation-distance")));
2324   }
2325
2326   if ( widgets->speed_box ) {
2327     GtkWidget *page = NULL;
2328     widgets->w_cur_time = gtk_label_new(_("No Data"));
2329     widgets->w_cur_speed = gtk_label_new(_("No Data"));
2330     widgets->w_show_gps_speed = gtk_check_button_new_with_mnemonic(_("Show _GPS Speed"));
2331     page = create_graph_page (widgets->speed_box,
2332                               _("<b>Track Time:</b>"), widgets->w_cur_time,
2333                               _("<b>Track Speed:</b>"), widgets->w_cur_speed,
2334                               widgets->w_show_gps_speed, TRUE,
2335                               NULL, FALSE);
2336     g_signal_connect (widgets->w_show_gps_speed, "toggled", G_CALLBACK (checkbutton_toggle_cb), pass_along);
2337     gtk_notebook_append_page(GTK_NOTEBOOK(graphs), page, gtk_label_new(_("Speed-time")));
2338   }
2339
2340   if ( widgets->dist_box ) {
2341     GtkWidget *page = NULL;
2342     widgets->w_cur_dist_time = gtk_label_new(_("No Data"));
2343     widgets->w_cur_dist_dist = gtk_label_new(_("No Data"));
2344     widgets->w_show_dist_speed = gtk_check_button_new_with_mnemonic(_("Show S_peed"));
2345     page = create_graph_page (widgets->dist_box,
2346                               _("<b>Track Distance:</b>"), widgets->w_cur_dist_dist,
2347                               _("<b>Track Time:</b>"), widgets->w_cur_dist_time,
2348                               widgets->w_show_dist_speed, FALSE,
2349                               NULL, FALSE);
2350     g_signal_connect (widgets->w_show_dist_speed, "toggled", G_CALLBACK (checkbutton_toggle_cb), pass_along);
2351     gtk_notebook_append_page(GTK_NOTEBOOK(graphs), page, gtk_label_new(_("Distance-time")));
2352   }
2353
2354   if ( widgets->elev_time_box ) {
2355     GtkWidget *page = NULL;
2356     widgets->w_cur_elev_time = gtk_label_new(_("No Data"));
2357     widgets->w_cur_elev_elev = gtk_label_new(_("No Data"));
2358     widgets->w_show_elev_speed = gtk_check_button_new_with_mnemonic(_("Show S_peed"));
2359     page = create_graph_page (widgets->elev_time_box,
2360                               _("<b>Track Time:</b>"), widgets->w_cur_elev_time,
2361                               _("<b>Track Height:</b>"), widgets->w_cur_elev_elev,
2362                               widgets->w_show_elev_speed, FALSE,
2363                               NULL, FALSE);
2364     g_signal_connect (widgets->w_show_elev_speed, "toggled", G_CALLBACK (checkbutton_toggle_cb), pass_along);
2365     gtk_notebook_append_page(GTK_NOTEBOOK(graphs), page, gtk_label_new(_("Elevation-time")));
2366   }
2367
2368   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), graphs, FALSE, FALSE, 0);
2369
2370   gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog), VIK_TRW_LAYER_PROPWIN_SPLIT_MARKER, FALSE);
2371   if (seg_count <= 1)
2372     gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog), VIK_TRW_LAYER_PROPWIN_SPLIT, FALSE);
2373   if (vik_track_get_dup_point_count(tr) <= 0)
2374     gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog), VIK_TRW_LAYER_PROPWIN_DEL_DUP, FALSE);
2375
2376   // On dialog realization configure_event casues the graphs to be initially drawn
2377   widgets->configure_dialog = TRUE;
2378   g_signal_connect ( G_OBJECT(dialog), "configure-event", G_CALLBACK (configure_event), pass_along);
2379
2380   vik_track_set_property_dialog(tr, dialog);
2381   gtk_dialog_set_default_response ( GTK_DIALOG(dialog), GTK_RESPONSE_ACCEPT );
2382   gtk_widget_show_all ( dialog );
2383 }