]> git.street.me.uk Git - andy/viking.git/blob - src/viktrwlayer_propwin.c
Track Properties internal refactor: rename function to reflect what it really does.
[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  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #endif
27
28 #ifdef HAVE_MATH_H
29 #include <math.h>
30 #endif
31
32 #include <gtk/gtk.h>
33 #include <glib/gi18n.h>
34 #include <time.h>
35 #ifdef HAVE_STRING_H
36 #include <string.h>
37 #endif
38 #include "coords.h"
39 #include "vikcoord.h"
40 #include "viktrack.h"
41 #include "viktrwlayer.h"
42 #include "viktrwlayer_propwin.h"
43 #include "vikwaypoint.h"
44 #include "dialog.h"
45 #include "globals.h"
46 #include "dems.h"
47
48 #include "vikviewport.h" /* ugh */
49 #include "viktreeview.h" /* ugh */
50 #include <gdk-pixbuf/gdk-pixdata.h>
51 #include "viklayer.h" /* ugh */
52 #include "vikaggregatelayer.h"
53 #include "viklayerspanel.h" /* ugh */
54
55 #define PROPWIN_PROFILE_WIDTH 600
56 #define PROPWIN_PROFILE_HEIGHT 300
57
58 #define PROPWIN_LABEL_FONT "Sans 7"
59
60 #define MIN_ALT_DIFF 100.0
61 #define MIN_SPEED_DIFF 5.0
62
63 typedef struct _propsaved {
64   gboolean saved;
65   gint pos;
66   GdkImage *img;
67 } PropSaved;
68
69 typedef struct _propwidgets {
70   gboolean  configure_dialog;
71   VikTrwLayer *vtl;
72   VikTrack *tr;
73   VikLayersPanel *vlp;
74   gchar *track_name;
75   gint      profile_width;
76   gint      profile_height;
77   GtkWidget *dialog;
78   GtkWidget *w_comment;
79   GtkWidget *w_track_length;
80   GtkWidget *w_tp_count;
81   GtkWidget *w_segment_count;
82   GtkWidget *w_duptp_count;
83   GtkWidget *w_max_speed;
84   GtkWidget *w_avg_speed;
85   GtkWidget *w_avg_dist;
86   GtkWidget *w_elev_range;
87   GtkWidget *w_elev_gain;
88   GtkWidget *w_time_start;
89   GtkWidget *w_time_end;
90   GtkWidget *w_time_dur;
91   GtkWidget *w_cur_dist; /*< Current distance */
92   GtkWidget *w_cur_elevation;
93   GtkWidget *w_cur_time; /*< Current time */
94   GtkWidget *w_cur_speed;
95   gdouble   track_length;
96   PropSaved elev_graph_saved_img;
97   PropSaved speed_graph_saved_img;
98   GtkWidget *elev_box;
99   GtkWidget *speed_box;
100   gdouble   *altitudes;
101   gdouble   *speeds;
102   VikTrackpoint *marker_tp;
103   gboolean  is_marker_drawn;
104 } PropWidgets;
105
106 static PropWidgets *prop_widgets_new()
107 {
108   PropWidgets *widgets = g_malloc0(sizeof(PropWidgets));
109
110   return widgets;
111 }
112
113 static void prop_widgets_free(PropWidgets *widgets)
114 {
115   if (widgets->elev_graph_saved_img.img)
116     g_object_unref(widgets->elev_graph_saved_img.img);
117   if (widgets->speed_graph_saved_img.img)
118     g_object_unref(widgets->speed_graph_saved_img.img);
119   if (widgets->altitudes)
120     g_free(widgets->altitudes);
121   if (widgets->speeds)
122     g_free(widgets->speeds);
123   g_free(widgets);
124 }
125
126 static void minmax_array(const gdouble *array, gdouble *min, gdouble *max, gboolean NO_ALT_TEST, gint PROFILE_WIDTH)
127 {
128   *max = -1000;
129   *min = 20000;
130   guint i;
131   for ( i=0; i < PROFILE_WIDTH; i++ ) {
132     if ( NO_ALT_TEST || (array[i] != VIK_DEFAULT_ALTITUDE) ) {
133       if ( array[i] > *max )
134         *max = array[i];
135       if ( array[i] < *min )
136         *min = array[i];
137     }
138   }
139 }
140
141 #define MARGIN 70
142 #define LINES 5
143 static VikTrackpoint *set_center_at_graph_position(gdouble event_x,
144                                                    gint img_width,
145                                                    VikTrwLayer *vtl,
146                                                    VikLayersPanel *vlp,
147                                                    VikViewport *vvp,
148                                                    VikTrack *tr,
149                                                    gboolean time_base,
150                                                    gint PROFILE_WIDTH)
151 {
152   VikTrackpoint *trackpoint;
153   gdouble x = event_x - img_width / 2 + PROFILE_WIDTH / 2 - MARGIN / 2;
154   if (x < 0)
155     x = 0;
156   if (x > PROFILE_WIDTH)
157     x = PROFILE_WIDTH;
158
159   if (time_base)
160     trackpoint = vik_track_get_closest_tp_by_percentage_time ( tr, (gdouble) x / PROFILE_WIDTH, NULL );
161   else
162     trackpoint = vik_track_get_closest_tp_by_percentage_dist ( tr, (gdouble) x / PROFILE_WIDTH, NULL );
163
164   if ( trackpoint ) {
165     VikCoord coord = trackpoint->coord;
166     if ( vlp ) {
167       vik_viewport_set_center_coord ( vik_layers_panel_get_viewport(vlp), &coord );
168       vik_layers_panel_emit_update ( vlp );
169     }
170     else {
171       /* since vlp not set, vvp should be valid instead! */
172       if ( vvp )
173         vik_viewport_set_center_coord ( vvp, &coord );
174       vik_layer_emit_update ( VIK_LAYER(vtl) );
175     }
176   }
177   return trackpoint;
178 }
179
180 /**
181  * Returns whether the marker was drawn or not
182  */
183 static void save_image_and_draw_graph_mark (GtkWidget *image,
184                                             gdouble event_x,
185                                             gint img_width,
186                                             GdkGC *gc,
187                                             PropSaved *saved_img,
188                                             gint PROFILE_WIDTH,
189                                             gint PROFILE_HEIGHT,
190                                             gboolean *marker_drawn)
191 {
192   GdkPixmap *pix = NULL;
193   /* the pixmap = margin + graph area */
194   gdouble x = event_x - img_width/2 + PROFILE_WIDTH/2 + MARGIN/2;
195
196   // fprintf(stderr, "event_x=%f img_width=%d x=%f\n", event_x, img_width, x);
197
198   gtk_image_get_pixmap(GTK_IMAGE(image), &pix, NULL);
199   /* Restore previously saved image */
200   if (saved_img->saved) {
201     gdk_draw_image(GDK_DRAWABLE(pix), gc, saved_img->img, 0, 0,
202         saved_img->pos, 0, -1, -1);
203     saved_img->saved = FALSE;
204     gtk_widget_queue_draw_area(image,
205         saved_img->pos + img_width/2 - PROFILE_WIDTH/2 - MARGIN/2, 0,
206         saved_img->img->width, saved_img->img->height);
207   }
208   if ((x >= MARGIN) && (x < (PROFILE_WIDTH + MARGIN))) {
209     /* Save part of the image */
210     if (saved_img->img)
211       gdk_drawable_copy_to_image(GDK_DRAWABLE(pix), saved_img->img,
212           x, 0, 0, 0, saved_img->img->width, saved_img->img->height);
213     else
214       saved_img->img = gdk_drawable_copy_to_image(GDK_DRAWABLE(pix),
215           saved_img->img, x, 0, 0, 0, 1, PROFILE_HEIGHT);
216     saved_img->pos = x;
217     saved_img->saved = TRUE;
218     gdk_draw_line (GDK_DRAWABLE(pix), gc, x, 0, x, image->allocation.height);
219     /* redraw the area which contains the line, saved_width is just convenient */
220     gtk_widget_queue_draw_area(image, event_x, 0, 1, PROFILE_HEIGHT);
221     *marker_drawn = TRUE;
222   }
223   else
224     *marker_drawn = FALSE;
225 }
226
227 /**
228  * Return the percentage of how far a trackpoint is a long a track via the time method
229  */
230 static gdouble tp_percentage_by_time ( VikTrack *tr, VikTrackpoint *trackpoint )
231 {
232   gdouble pc = NAN;
233   if (trackpoint == NULL)
234     return pc;
235   time_t t_start, t_end, t_total;
236   t_start = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
237   t_end = VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->timestamp;
238   t_total = t_end - t_start;
239   pc = (gdouble)(trackpoint->timestamp - t_start)/t_total;
240   return pc;
241 }
242
243 /**
244  * Return the percentage of how far a trackpoint is a long a track via the distance method
245  */
246 static gdouble tp_percentage_by_distance ( VikTrack *tr, VikTrackpoint *trackpoint, gdouble track_length )
247 {
248   gdouble pc = NAN;
249   if (trackpoint == NULL)
250     return pc;
251   gdouble dist = 0.0;
252   GList *iter;
253   for (iter = tr->trackpoints->next; iter != NULL; iter = iter->next) {
254     dist += vik_coord_diff(&(VIK_TRACKPOINT(iter->data)->coord),
255                            &(VIK_TRACKPOINT(iter->prev->data)->coord));
256     /* Assuming trackpoint is not a copy */
257     if (trackpoint == VIK_TRACKPOINT(iter->data))
258       break;
259   }
260   if (iter != NULL)
261     pc = dist/track_length;
262   return pc;
263 }
264
265 static void track_graph_click( GtkWidget *event_box, GdkEventButton *event, gpointer *pass_along, gboolean is_vt_graph )
266 {
267   VikTrack *tr = pass_along[0];
268   VikLayersPanel *vlp = pass_along[1];
269   VikViewport *vvp = pass_along[2];
270   PropWidgets *widgets = pass_along[3];
271   GList *child = gtk_container_get_children(GTK_CONTAINER(event_box));
272   GtkWidget *image = GTK_WIDGET(child->data);
273   GtkWidget *window = gtk_widget_get_toplevel(GTK_WIDGET(event_box));
274
275   VikTrackpoint *trackpoint = set_center_at_graph_position(event->x, event_box->allocation.width, widgets->vtl, vlp, vvp, tr, is_vt_graph, widgets->profile_width);
276   save_image_and_draw_graph_mark(image,
277                                  event->x,
278                                  event_box->allocation.width,
279                                  window->style->black_gc,
280                                  is_vt_graph ? &widgets->speed_graph_saved_img : &widgets->elev_graph_saved_img,
281                                  widgets->profile_width,
282                                  widgets->profile_height,
283                                  &widgets->is_marker_drawn);
284   g_list_free(child);
285   widgets->marker_tp = trackpoint;
286   gtk_dialog_set_response_sensitive(GTK_DIALOG(widgets->dialog), VIK_TRW_LAYER_PROPWIN_SPLIT_MARKER, widgets->is_marker_drawn);
287
288   /* draw on the other graph */
289   if (trackpoint == NULL || widgets->elev_box == NULL || widgets->speed_box == NULL)
290     /* This test assumes we have only 2 graphs */
291     return;
292
293   gdouble pc = NAN;
294   gdouble x2;
295   GList *other_child = gtk_container_get_children(GTK_CONTAINER(
296                          is_vt_graph ? widgets->elev_box : widgets->speed_box));
297   GtkWidget *other_image = GTK_WIDGET(other_child->data);
298   if (is_vt_graph) {
299     pc = tp_percentage_by_distance ( tr, trackpoint, widgets->track_length );
300   } else {
301     pc = tp_percentage_by_time ( tr, trackpoint );
302   }
303   if (!isnan(pc)) {
304     x2 = pc * widgets->profile_width + MARGIN + (event_box->allocation.width/2 - widgets->profile_width/2 - MARGIN/2);
305     save_image_and_draw_graph_mark(other_image,
306                                    x2,
307                                    event_box->allocation.width,
308                                    window->style->black_gc,
309                                    is_vt_graph ? &widgets->elev_graph_saved_img : &widgets->speed_graph_saved_img,
310                                    widgets->profile_width,
311                                    widgets->profile_height,
312                                    &widgets->is_marker_drawn);
313   }
314
315   g_list_free(other_child);
316
317 }
318
319 static gboolean track_profile_click( GtkWidget *event_box, GdkEventButton *event, gpointer *pass_along )
320 {
321   track_graph_click(event_box, event, pass_along, FALSE);
322   return TRUE;  /* don't call other (further) callbacks */
323 }
324
325 static gboolean track_vt_click( GtkWidget *event_box, GdkEventButton *event, gpointer *pass_along )
326 {
327   track_graph_click(event_box, event, pass_along, TRUE);
328   return TRUE;  /* don't call other (further) callbacks */
329 }
330
331 void track_profile_move( GtkWidget *image, GdkEventMotion *event, gpointer *pass_along )
332 {
333   VikTrack *tr = pass_along[0];
334   PropWidgets *widgets = pass_along[3];
335   int mouse_x, mouse_y;
336   GdkModifierType state;
337
338   if (event->is_hint)
339     gdk_window_get_pointer (event->window, &mouse_x, &mouse_y, &state);
340   else
341     mouse_x = event->x;
342
343   gdouble x = mouse_x - image->allocation.width / 2 + widgets->profile_width / 2 - MARGIN / 2;
344   if (x < 0)
345     x = 0;
346   if (x > widgets->profile_width)
347     x = widgets->profile_width;
348
349   gdouble meters_from_start;
350   VikTrackpoint *trackpoint = vik_track_get_closest_tp_by_percentage_dist ( tr, (gdouble) x / widgets->profile_width, &meters_from_start );
351   if (trackpoint && widgets->w_cur_dist) {
352     static gchar tmp_buf[20];
353     vik_units_distance_t dist_units = a_vik_get_units_distance ();
354     switch (dist_units) {
355     case VIK_UNITS_DISTANCE_KILOMETRES:
356       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f km", meters_from_start/1000.0);
357       break;
358     case VIK_UNITS_DISTANCE_MILES:
359       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f miles", VIK_METERS_TO_MILES(meters_from_start) );
360       break;
361     default:
362       g_critical("Houston, we've had a problem. distance=%d", dist_units);
363     }
364     gtk_label_set_text(GTK_LABEL(widgets->w_cur_dist), tmp_buf);
365   }
366
367   // Show track elevation for this position - to the nearest whole number
368   if (trackpoint && widgets->w_cur_elevation) {
369     static gchar tmp_buf[20];
370     if (a_vik_get_units_height () == VIK_UNITS_HEIGHT_FEET)
371       g_snprintf(tmp_buf, sizeof(tmp_buf), "%d ft", (int)VIK_METERS_TO_FEET(trackpoint->altitude));
372     else
373       g_snprintf(tmp_buf, sizeof(tmp_buf), "%d m", (int)trackpoint->altitude);
374     gtk_label_set_text(GTK_LABEL(widgets->w_cur_elevation), tmp_buf);
375   }
376 }
377
378 void track_vt_move( GtkWidget *image, GdkEventMotion *event, gpointer *pass_along )
379 {
380   VikTrack *tr = pass_along[0];
381   PropWidgets *widgets = pass_along[3];
382   int mouse_x, mouse_y;
383   GdkModifierType state;
384
385   if (event->is_hint)
386     gdk_window_get_pointer (event->window, &mouse_x, &mouse_y, &state);
387   else
388     mouse_x = event->x;
389
390   gdouble x = mouse_x - image->allocation.width / 2 + widgets->profile_width / 2 - MARGIN / 2;
391   if (x < 0)
392     x = 0;
393   if (x > widgets->profile_width)
394     x = widgets->profile_width;
395
396   time_t seconds_from_start;
397   VikTrackpoint *trackpoint = vik_track_get_closest_tp_by_percentage_time ( tr, (gdouble) x / widgets->profile_width, &seconds_from_start );
398   if (trackpoint && widgets->w_cur_time) {
399     static gchar tmp_buf[20];
400     guint h, m, s;
401     h = seconds_from_start/3600;
402     m = (seconds_from_start - h*3600)/60;
403     s = seconds_from_start - (3600*h) - (60*m);
404     g_snprintf(tmp_buf, sizeof(tmp_buf), "%02d:%02d:%02d", h, m, s);
405
406     gtk_label_set_text(GTK_LABEL(widgets->w_cur_time), tmp_buf);
407   }
408
409   // Show track speed for this position
410   if (trackpoint && widgets->w_cur_speed) {
411     static gchar tmp_buf[20];
412     // Even if GPS speed available (trackpoint->speed), the text will correspond to the speed map shown
413     gint ix = (gint)x;
414     // Ensure ix is inbounds
415     if (ix == widgets->profile_width)
416       ix--;
417
418     vik_units_speed_t speed_units = a_vik_get_units_speed ();
419     switch (speed_units) {
420     case VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
421       g_snprintf(tmp_buf, sizeof(tmp_buf), _("%.1f kph"), VIK_MPS_TO_KPH(widgets->speeds[ix]));
422       break;
423     case VIK_UNITS_SPEED_MILES_PER_HOUR:
424       g_snprintf(tmp_buf, sizeof(tmp_buf), _("%.1f mph"), VIK_MPS_TO_MPH(widgets->speeds[ix]));
425       break;
426     case VIK_UNITS_SPEED_KNOTS:
427       g_snprintf(tmp_buf, sizeof(tmp_buf), _("%.1f knots"), VIK_MPS_TO_KNOTS(widgets->speeds[ix]));
428       break;
429     default:
430       // VIK_UNITS_SPEED_METRES_PER_SECOND:
431       // No need to convert as already in m/s
432       g_snprintf(tmp_buf, sizeof(tmp_buf), _("%.1f m/s"), widgets->speeds[ix]);
433       break;
434     }
435     gtk_label_set_text(GTK_LABEL(widgets->w_cur_speed), tmp_buf);
436   }
437 }
438
439 static void draw_dem_alt_speed_dist(VikTrack *tr, GdkDrawable *pix, GdkGC *alt_gc, GdkGC *speed_gc, gdouble alt_offset, gdouble alt_diff, gint width, gint height, gint margin)
440 {
441   GList *iter;
442   gdouble dist = 0;
443   gdouble max_speed = 0;
444   gdouble total_length = vik_track_get_length_including_gaps(tr);
445
446   for (iter = tr->trackpoints->next; iter; iter = iter->next) {
447     if (!isnan(VIK_TRACKPOINT(iter->data)->speed))
448       max_speed = MAX(max_speed, VIK_TRACKPOINT(iter->data)->speed);
449   }
450   max_speed = max_speed * 110 / 100;
451
452   for (iter = tr->trackpoints->next; iter; iter = iter->next) {
453     int x, y_alt, y_speed;
454     gint16 elev = a_dems_get_elev_by_coord(&(VIK_TRACKPOINT(iter->data)->coord), VIK_DEM_INTERPOL_BEST);
455     elev -= alt_offset;
456     dist += vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord),
457       &(VIK_TRACKPOINT(iter->prev->data)->coord) );
458     x = (width * dist)/total_length + margin;
459     if ( elev != VIK_DEM_INVALID_ELEVATION ) {
460       y_alt = height - ((height * elev)/alt_diff);
461       gdk_draw_rectangle(GDK_DRAWABLE(pix), alt_gc, TRUE, x-2, y_alt-2, 4, 4);
462     }
463     if (!isnan(VIK_TRACKPOINT(iter->data)->speed)) {
464       y_speed = height - (height * VIK_TRACKPOINT(iter->data)->speed)/max_speed;
465       gdk_draw_rectangle(GDK_DRAWABLE(pix), speed_gc, TRUE, x-2, y_speed-2, 4, 4);
466     }
467   }
468 }
469
470 /**
471  * Draw just the height profile image
472  */
473 static void draw_elevations (GtkWidget *image, VikTrack *tr, PropWidgets *widgets )
474 {
475   GtkWidget *window;
476   GdkPixmap *pix;
477   gdouble mina, maxa;
478   guint i;
479
480   GdkGC *no_alt_info;
481   GdkGC *dem_alt_gc;
482   GdkGC *gps_speed_gc;
483
484   GdkColor color;
485
486   // Free previous allocation
487   if ( widgets->altitudes )
488     g_free ( widgets->altitudes );
489
490   widgets->altitudes = vik_track_make_elevation_map ( tr, widgets->profile_width );
491
492   if ( widgets->altitudes == NULL )
493     return;
494
495   minmax_array(widgets->altitudes, &mina, &maxa, TRUE, widgets->profile_width);
496   maxa = maxa + ((maxa - mina) * 0.25); // Make visible window a bit bigger than highest point
497
498   window = gtk_widget_get_toplevel (widgets->elev_box);
499
500   pix = gdk_pixmap_new( window->window, widgets->profile_width + MARGIN, widgets->profile_height, -1 );
501
502   gtk_image_set_from_pixmap ( GTK_IMAGE(image), pix, NULL );
503
504   no_alt_info = gdk_gc_new ( window->window );
505   gdk_color_parse ( "yellow", &color );
506   gdk_gc_set_rgb_fg_color ( no_alt_info, &color);
507
508   dem_alt_gc = gdk_gc_new ( window->window );
509   gdk_color_parse ( "green", &color );
510   gdk_gc_set_rgb_fg_color ( dem_alt_gc, &color);
511
512   gps_speed_gc = gdk_gc_new ( window->window );
513   gdk_color_parse ( "red", &color );
514   gdk_gc_set_rgb_fg_color ( gps_speed_gc, &color);
515
516   /* clear the image */
517   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->bg_gc[0], 
518                      TRUE, 0, 0, MARGIN, widgets->profile_height);
519   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->mid_gc[0], 
520                      TRUE, MARGIN, 0, widgets->profile_width, widgets->profile_height);
521   
522   /* draw grid */
523   vik_units_height_t height_units = a_vik_get_units_height ();
524   for (i=0; i<=LINES; i++) {
525     PangoFontDescription *pfd;
526     PangoLayout *pl = gtk_widget_create_pango_layout (GTK_WIDGET(image), NULL);
527     gchar s[32];
528     int w, h;
529
530     pango_layout_set_alignment (pl, PANGO_ALIGN_RIGHT);
531     pfd = pango_font_description_from_string (PROPWIN_LABEL_FONT);
532     pango_layout_set_font_description (pl, pfd);
533     pango_font_description_free (pfd);
534     switch (height_units) {
535     case VIK_UNITS_HEIGHT_METRES:
536       sprintf(s, "%8dm", (int)(mina + (LINES-i)*(maxa-mina)/LINES));
537       break;
538     case VIK_UNITS_HEIGHT_FEET:
539       sprintf(s, "%8dft", (int)VIK_METERS_TO_FEET(mina + (LINES-i)*(maxa-mina)/LINES));
540       break;
541     default:
542       sprintf(s, "--");
543       g_critical("Houston, we've had a problem. height=%d", height_units);
544     }
545     pango_layout_set_text(pl, s, -1);
546     pango_layout_get_pixel_size (pl, &w, &h);
547     gdk_draw_layout(GDK_DRAWABLE(pix), window->style->fg_gc[0], MARGIN-w-3, 
548                     CLAMP((int)i*widgets->profile_height/LINES - h/2, 0, widgets->profile_height-h), pl);
549
550     gdk_draw_line (GDK_DRAWABLE(pix), window->style->dark_gc[0], 
551                    MARGIN, widgets->profile_height/LINES * i, MARGIN + widgets->profile_width, widgets->profile_height/LINES * i);
552     g_object_unref ( G_OBJECT ( pl ) );
553     pl = NULL;
554   }
555
556   /* draw elevations */
557   for ( i = 0; i < widgets->profile_width; i++ )
558     if ( widgets->altitudes[i] == VIK_DEFAULT_ALTITUDE )
559       gdk_draw_line ( GDK_DRAWABLE(pix), no_alt_info, 
560                       i + MARGIN, 0, i + MARGIN, widgets->profile_height );
561     else 
562       gdk_draw_line ( GDK_DRAWABLE(pix), window->style->dark_gc[3], 
563                       i + MARGIN, widgets->profile_height, i + MARGIN, widgets->profile_height-widgets->profile_height*(widgets->altitudes[i]-mina)/(maxa-mina) );
564
565   draw_dem_alt_speed_dist(tr, GDK_DRAWABLE(pix), dem_alt_gc, gps_speed_gc, mina, maxa - mina, widgets->profile_width, widgets->profile_height, MARGIN);
566
567   /* draw border */
568   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->black_gc, FALSE, MARGIN, 0, widgets->profile_width-1, widgets->profile_height-1);
569
570   g_object_unref ( G_OBJECT(pix) );
571   g_object_unref ( G_OBJECT(no_alt_info) );
572   g_object_unref ( G_OBJECT(dem_alt_gc) );
573   g_object_unref ( G_OBJECT(gps_speed_gc) );
574
575 }
576
577 /**
578  * Draw just the speed (velocity)/time image
579  */
580 static void draw_vt ( GtkWidget *image, VikTrack *tr, PropWidgets *widgets)
581 {
582   GtkWidget *window;
583   GdkPixmap *pix;
584   gdouble mins, maxs;
585   guint i;
586
587   // Free previous allocation
588   if ( widgets->speeds )
589     g_free ( widgets->speeds );
590
591   widgets->speeds = vik_track_make_speed_map ( tr, widgets->profile_width );
592   if ( widgets->speeds == NULL )
593     return;
594
595   GdkGC *gps_speed_gc;
596   GdkColor color;
597
598   window = gtk_widget_get_toplevel (widgets->speed_box);
599
600   pix = gdk_pixmap_new( window->window, widgets->profile_width + MARGIN, widgets->profile_height, -1 );
601
602   gtk_image_set_from_pixmap ( GTK_IMAGE(image), pix, NULL );
603
604   gps_speed_gc = gdk_gc_new ( window->window );
605   gdk_color_parse ( "red", &color );
606   gdk_gc_set_rgb_fg_color ( gps_speed_gc, &color);
607
608   minmax_array(widgets->speeds, &mins, &maxs, FALSE, widgets->profile_width);
609   if (mins < 0.0)
610     mins = 0; /* splines sometimes give negative speeds */
611   maxs = maxs + ((maxs - mins) * 0.1);
612   if  (maxs-mins < MIN_SPEED_DIFF) {
613     maxs = mins + MIN_SPEED_DIFF;
614   }
615   
616   /* clear the image */
617   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->bg_gc[0], 
618                      TRUE, 0, 0, MARGIN, widgets->profile_height);
619   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->mid_gc[0], 
620                      TRUE, MARGIN, 0, widgets->profile_width, widgets->profile_height);
621
622   /* draw grid */
623   for (i=0; i<=LINES; i++) {
624     PangoFontDescription *pfd;
625     PangoLayout *pl = gtk_widget_create_pango_layout (GTK_WIDGET(image), NULL);
626     gchar s[32];
627     int w, h;
628
629     pango_layout_set_alignment (pl, PANGO_ALIGN_RIGHT);
630     pfd = pango_font_description_from_string (PROPWIN_LABEL_FONT);
631     pango_layout_set_font_description (pl, pfd);
632     pango_font_description_free (pfd);
633     vik_units_speed_t speed_units = a_vik_get_units_speed ();
634     switch (speed_units) {
635     case VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
636       sprintf(s, "%6.1fkm/h", VIK_MPS_TO_KPH(mins + (LINES-i)*(maxs-mins)/LINES));
637       break;
638     case VIK_UNITS_SPEED_MILES_PER_HOUR:
639       sprintf(s, "%6.1fmph", VIK_MPS_TO_MPH(mins + (LINES-i)*(maxs-mins)/LINES));
640       break;
641     case VIK_UNITS_SPEED_METRES_PER_SECOND:
642       sprintf(s, "%8dm/s", (int)(mins + (LINES-i)*(maxs-mins)/LINES));
643       break;
644     case VIK_UNITS_SPEED_KNOTS:
645       sprintf(s, "%6.1fknots", VIK_MPS_TO_KNOTS(mins + (LINES-i)*(maxs-mins)/LINES));
646       break;
647     default:
648       sprintf(s, "--");
649       g_critical("Houston, we've had a problem. speed=%d", speed_units);
650     }
651
652     pango_layout_set_text(pl, s, -1);
653     pango_layout_get_pixel_size (pl, &w, &h);
654     gdk_draw_layout(GDK_DRAWABLE(pix), window->style->fg_gc[0], MARGIN-w-3, 
655                     CLAMP((int)i*widgets->profile_height/LINES - h/2, 0, widgets->profile_height-h), pl);
656
657     gdk_draw_line (GDK_DRAWABLE(pix), window->style->dark_gc[0], 
658                    MARGIN, widgets->profile_height/LINES * i, MARGIN + widgets->profile_width, widgets->profile_height/LINES * i);
659     g_object_unref ( G_OBJECT ( pl ) );
660     pl = NULL;
661   }
662   
663
664   /* draw speeds */
665   for ( i = 0; i < widgets->profile_width; i++ )
666       gdk_draw_line ( GDK_DRAWABLE(pix), window->style->dark_gc[3], 
667                       i + MARGIN, widgets->profile_height, i + MARGIN, widgets->profile_height-widgets->profile_height*(widgets->speeds[i]-mins)/(maxs-mins) );
668
669
670   time_t beg_time = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
671   time_t dur =  VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->timestamp - beg_time;
672   GList *iter;
673   for (iter = tr->trackpoints; iter; iter = iter->next) {
674     gdouble gps_speed = VIK_TRACKPOINT(iter->data)->speed;
675     if (isnan(gps_speed))
676         continue;
677     int x = MARGIN + widgets->profile_width * (VIK_TRACKPOINT(iter->data)->timestamp - beg_time) / dur;
678     int y = widgets->profile_height - widgets->profile_height*(gps_speed - mins)/(maxs - mins);
679     gdk_draw_rectangle(GDK_DRAWABLE(pix), gps_speed_gc, TRUE, x-2, y-2, 4, 4);
680   }
681
682   /* draw border */
683   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->black_gc, FALSE, MARGIN, 0, widgets->profile_width-1, widgets->profile_height-1);
684
685   g_object_unref ( G_OBJECT(pix) );
686   g_object_unref ( G_OBJECT(gps_speed_gc) );
687
688 }
689 #undef LINES
690
691
692 /**
693  * Configure the profile & speed/time images
694  */
695 static gboolean configure_event ( GtkWidget *widget, GdkEventConfigure *event, gpointer *pass_along )
696 {
697   VikTrack *tr = pass_along[0];
698   PropWidgets *widgets = pass_along[2];
699
700   // ATM we receive configure_events when the dialog is moved and so no further action is necessary
701   if ( !widgets->configure_dialog )
702     return FALSE;
703
704   widgets->configure_dialog = FALSE;
705
706   // Draw graphs even if they are not visible
707
708   GList *child = NULL;
709   // Draw elevations
710   if (widgets->elev_box != NULL) {
711     child = gtk_container_get_children(GTK_CONTAINER(widgets->elev_box));
712     draw_elevations (GTK_WIDGET(child->data), tr, widgets );
713     g_list_free(child);
714   }
715
716   // Draw speeds
717   if (widgets->speed_box != NULL) {
718     child = gtk_container_get_children(GTK_CONTAINER(widgets->speed_box));
719     draw_vt (GTK_WIDGET(child->data), tr, widgets );
720     g_list_free(child);
721   }
722     
723   return FALSE;
724 }
725
726 /**
727  * Create height profile widgets including the image and callbacks
728  */
729 GtkWidget *vik_trw_layer_create_profile ( GtkWidget *window, VikTrack *tr, gpointer vlp, VikViewport *vvp, PropWidgets *widgets, gdouble *min_alt, gdouble *max_alt)
730 {
731   GdkPixmap *pix;
732   GtkWidget *image;
733   GtkWidget *eventbox;
734   gpointer *pass_along;
735
736   // First allocation
737   widgets->altitudes = vik_track_make_elevation_map ( tr, widgets->profile_width );
738
739   if ( widgets->altitudes == NULL ) {
740     *min_alt = *max_alt = VIK_DEFAULT_ALTITUDE;
741     return NULL;
742   }
743
744   minmax_array(widgets->altitudes, min_alt, max_alt, TRUE, widgets->profile_width);
745   
746   pix = gdk_pixmap_new( window->window, widgets->profile_width + MARGIN, widgets->profile_height, -1 );
747   image = gtk_image_new_from_pixmap ( pix, NULL );
748
749   g_object_unref ( G_OBJECT(pix) );
750
751   pass_along = g_malloc ( sizeof(gpointer) * 4 ); /* FIXME: mem leak -- never be freed */
752   pass_along[0] = tr;
753   pass_along[1] = vlp;
754   pass_along[2] = vvp;
755   pass_along[3] = widgets;
756
757   eventbox = gtk_event_box_new ();
758   g_signal_connect ( G_OBJECT(eventbox), "button_press_event", G_CALLBACK(track_profile_click), pass_along );
759   g_signal_connect ( G_OBJECT(eventbox), "motion_notify_event", G_CALLBACK(track_profile_move), pass_along );
760   g_signal_connect_swapped ( G_OBJECT(eventbox), "destroy", G_CALLBACK(g_free), pass_along );
761   gtk_container_add ( GTK_CONTAINER(eventbox), image );
762   gtk_widget_set_events (eventbox, GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_STRUCTURE_MASK);
763
764   return eventbox;
765 }
766
767 /**
768  * Create speed/time widgets including the image and callbacks
769  */
770 GtkWidget *vik_trw_layer_create_vtdiag ( GtkWidget *window, VikTrack *tr, gpointer vlp, VikViewport *vvp, PropWidgets *widgets)
771 {
772   GdkPixmap *pix;
773   GtkWidget *image;
774   GtkWidget *eventbox;
775   gpointer *pass_along;
776
777   // First allocation
778   widgets->speeds = vik_track_make_speed_map ( tr, widgets->profile_width );
779   if ( widgets->speeds == NULL )
780     return NULL;
781
782   pass_along = g_malloc ( sizeof(gpointer) * 4 ); /* FIXME: mem leak -- never be freed */
783   pass_along[0] = tr;
784   pass_along[1] = vlp;
785   pass_along[2] = vvp;
786   pass_along[3] = widgets;
787
788   pix = gdk_pixmap_new( window->window, widgets->profile_width + MARGIN, widgets->profile_height, -1 );
789   image = gtk_image_new_from_pixmap ( pix, NULL );
790
791 #if 0
792   /* XXX this can go out, it's just a helpful dev tool */
793   {
794     int j;
795     GdkGC **colors[8] = { window->style->bg_gc,
796                           window->style->fg_gc,
797                           window->style->light_gc,
798                           window->style->dark_gc,
799                           window->style->mid_gc,
800                           window->style->text_gc,
801                           window->style->base_gc,
802                           window->style->text_aa_gc };
803     for (i=0; i<5; i++) {
804       for (j=0; j<8; j++) {
805         gdk_draw_rectangle(GDK_DRAWABLE(pix), colors[j][i],
806                            TRUE, i*20, j*20, 20, 20);
807         gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->black_gc,
808                            FALSE, i*20, j*20, 20, 20);
809       }
810     }
811   }
812 #endif
813
814   g_object_unref ( G_OBJECT(pix) );
815
816   eventbox = gtk_event_box_new ();
817   g_signal_connect ( G_OBJECT(eventbox), "button_press_event", G_CALLBACK(track_vt_click), pass_along );
818   g_signal_connect ( G_OBJECT(eventbox), "motion_notify_event", G_CALLBACK(track_vt_move), pass_along );
819   g_signal_connect_swapped ( G_OBJECT(eventbox), "destroy", G_CALLBACK(g_free), pass_along );
820   gtk_container_add ( GTK_CONTAINER(eventbox), image );
821   gtk_widget_set_events (eventbox, GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK);
822
823   return eventbox;
824 }
825 #undef MARGIN
826
827 static void propwin_response_cb( GtkDialog *dialog, gint resp, PropWidgets *widgets)
828 {
829   VikTrack *tr = widgets->tr;
830   VikTrwLayer *vtl = widgets->vtl;
831   gboolean keep_dialog = FALSE;
832
833   /* FIXME: check and make sure the track still exists before doing anything to it */
834   /* Note: destroying diaglog (eg, parent window exit) won't give "response" */
835   switch (resp) {
836     case GTK_RESPONSE_DELETE_EVENT: /* received delete event (not from buttons) */
837     case GTK_RESPONSE_REJECT:
838       break;
839     case GTK_RESPONSE_ACCEPT:
840       vik_track_set_comment(tr, gtk_entry_get_text(GTK_ENTRY(widgets->w_comment)));
841       break;
842     case VIK_TRW_LAYER_PROPWIN_REVERSE:
843       vik_track_reverse(tr);
844       vik_layer_emit_update ( VIK_LAYER(vtl) );
845       break;
846     case VIK_TRW_LAYER_PROPWIN_DEL_DUP:
847       vik_track_remove_dup_points(tr);
848       /* above operation could have deleted current_tp or last_tp */
849       trw_layer_cancel_tps_of_track ( vtl, widgets->track_name );
850       vik_layer_emit_update ( VIK_LAYER(vtl) );
851       break;
852     case VIK_TRW_LAYER_PROPWIN_SPLIT:
853       {
854         /* get new tracks, add them, resolve naming conflicts (free if cancel), and delete old. old can still exist on clipboard. */
855         guint ntracks;
856         VikTrack **tracks = vik_track_split_into_segments(tr, &ntracks);
857         gchar *new_tr_name;
858         guint i;
859         for ( i = 0; i < ntracks; i++ )
860         {
861           g_assert ( tracks[i] );
862           new_tr_name = g_strdup_printf("%s #%d", widgets->track_name, i+1);
863           /* if ( (wp_exists) && (! overwrite) ) */
864           /* don't need to upper case new_tr_name because old tr name was uppercase */
865           if ( vik_trw_layer_get_track(vtl, new_tr_name ) && 
866              ( ! a_dialog_yes_or_no ( VIK_GTK_WINDOW_FROM_LAYER(vtl), "The track \"%s\" exists, do you wish to overwrite it?", new_tr_name ) ) )
867           {
868             gchar *new_new_tr_name = a_dialog_new_track ( VIK_GTK_WINDOW_FROM_LAYER(vtl), vik_trw_layer_get_tracks(vtl), NULL );
869             g_free ( new_tr_name );
870             if (new_new_tr_name)
871               new_tr_name = new_new_tr_name;
872             else
873             {
874               new_tr_name = NULL;
875               vik_track_free ( tracks[i] );
876             }
877           }
878           if ( new_tr_name )
879             vik_trw_layer_add_track ( vtl, new_tr_name, tracks[i] );
880         }
881         if ( tracks )
882         {
883           g_free ( tracks );
884           /* Don't let track destroy this dialog */
885           vik_track_clear_property_dialog(tr);
886           vik_trw_layer_delete_track ( vtl, widgets->track_name );
887           vik_layer_emit_update ( VIK_LAYER(vtl) ); /* chase thru the hoops */
888         }
889       }
890       break;
891     case VIK_TRW_LAYER_PROPWIN_SPLIT_MARKER:
892       {
893         GList *iter = tr->trackpoints;
894         while ((iter = iter->next)) {
895           if (widgets->marker_tp == VIK_TRACKPOINT(iter->data))
896             break;
897         }
898         if (iter == NULL) {
899           a_dialog_msg(VIK_GTK_WINDOW_FROM_LAYER(vtl), GTK_MESSAGE_ERROR,
900                   _("Failed spliting track. Track unchanged"), NULL);
901           keep_dialog = TRUE;
902           break;
903         }
904
905         gchar *r_name = g_strdup_printf("%s #R", widgets->track_name);
906         if (vik_trw_layer_get_track(vtl, r_name ) && 
907              ( ! a_dialog_yes_or_no( VIK_GTK_WINDOW_FROM_LAYER(vtl),
908               "The track \"%s\" exists, do you wish to overwrite it?", r_name)))
909         {
910           gchar *new_r_name = a_dialog_new_track( VIK_GTK_WINDOW_FROM_LAYER(vtl), vik_trw_layer_get_tracks(vtl), NULL );
911             if (new_r_name) {
912               g_free( r_name );
913               r_name = new_r_name;
914             }
915             else {
916               a_dialog_msg(VIK_GTK_WINDOW_FROM_LAYER(vtl), GTK_MESSAGE_WARNING,
917                   _("Operation Aborted. Track unchanged"), NULL);
918               keep_dialog = TRUE;
919               break;
920             }
921         }
922         iter->prev->next = NULL;
923         iter->prev = NULL;
924         VikTrack *tr_right = vik_track_new();
925         if ( tr->comment )
926           vik_track_set_comment ( tr_right, tr->comment );
927         tr_right->visible = tr->visible;
928         tr_right->trackpoints = iter;
929
930         vik_trw_layer_add_track(vtl, r_name, tr_right);
931         vik_layer_emit_update ( VIK_LAYER(vtl) );
932       }
933       break;
934     default:
935       fprintf(stderr, "DEBUG: unknown response\n");
936       return;
937   }
938
939   /* Keep same behaviour for now: destroy dialog if click on any button */
940   if (!keep_dialog) {
941     prop_widgets_free(widgets);
942     vik_track_clear_property_dialog(tr);
943     gtk_widget_destroy ( GTK_WIDGET(dialog) );
944   }
945 }
946
947 /**
948  *  Create the widgets for the given graph tab
949  */
950 static GtkWidget *create_graph_page ( GtkWidget *graph,
951                                       const gchar *markup,
952                                       GtkWidget *value,
953                                       const gchar *markup2,
954                                       GtkWidget *value2)
955 {
956   GtkWidget *hbox = gtk_hbox_new ( FALSE, 10 );
957   GtkWidget *vbox = gtk_vbox_new ( FALSE, 10 );
958   GtkWidget *label = gtk_label_new (NULL);
959   GtkWidget *label2 = gtk_label_new (NULL);
960   gtk_box_pack_start (GTK_BOX(vbox), graph, FALSE, FALSE, 0);
961   gtk_label_set_markup ( GTK_LABEL(label), markup );
962   gtk_label_set_markup ( GTK_LABEL(label2), markup2 );
963   gtk_box_pack_start (GTK_BOX(hbox), label, FALSE, FALSE, 0);
964   gtk_box_pack_start (GTK_BOX(hbox), value, FALSE, FALSE, 0);
965   gtk_box_pack_start (GTK_BOX(hbox), label2, FALSE, FALSE, 0);
966   gtk_box_pack_start (GTK_BOX(hbox), value2, FALSE, FALSE, 0);
967   gtk_box_pack_start (GTK_BOX(vbox), hbox, FALSE, FALSE, 0);
968   
969   return vbox;
970 }
971
972 void vik_trw_layer_propwin_run ( GtkWindow *parent, VikTrwLayer *vtl, VikTrack *tr, gpointer vlp, gchar *track_name, VikViewport *vvp )
973 {
974   /* FIXME: free widgets when destroy signal received */
975   PropWidgets *widgets = prop_widgets_new();
976   widgets->vtl = vtl;
977   widgets->tr = tr;
978   widgets->vlp = vlp;
979   widgets->profile_width  = PROPWIN_PROFILE_WIDTH;
980   widgets->profile_height = PROPWIN_PROFILE_HEIGHT;
981   widgets->track_name = track_name;
982   gchar *title = g_strdup_printf(_("%s - Track Properties"), track_name);
983   GtkWidget *dialog = gtk_dialog_new_with_buttons (title,
984                          parent,
985                          GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_NO_SEPARATOR,
986                          GTK_STOCK_CANCEL, GTK_RESPONSE_REJECT,
987                          _("Split at Marker"), VIK_TRW_LAYER_PROPWIN_SPLIT_MARKER,
988                          _("Split Segments"), VIK_TRW_LAYER_PROPWIN_SPLIT,
989                          _("Reverse"),        VIK_TRW_LAYER_PROPWIN_REVERSE,
990                          _("Delete Dupl."),   VIK_TRW_LAYER_PROPWIN_DEL_DUP,
991                          GTK_STOCK_OK,     GTK_RESPONSE_ACCEPT,
992                          NULL);
993   widgets->dialog = dialog;
994   g_free(title);
995   g_signal_connect(dialog, "response", G_CALLBACK(propwin_response_cb), widgets);
996   GtkTable *table;
997   gdouble tr_len;
998   guint32 tp_count, seg_count;
999
1000   gdouble min_alt, max_alt;
1001   widgets->elev_box = vik_trw_layer_create_profile(GTK_WIDGET(parent), tr, vlp, vvp, widgets, &min_alt, &max_alt);
1002   widgets->speed_box = vik_trw_layer_create_vtdiag(GTK_WIDGET(parent), tr, vlp, vvp, widgets);
1003   GtkWidget *graphs = gtk_notebook_new();
1004
1005   GtkWidget *content[20];
1006   int cnt;
1007   int i;
1008
1009   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>") };
1010   static gchar tmp_buf[50];
1011   gdouble tmp_speed;
1012
1013   cnt = 0;
1014   widgets->w_comment = gtk_entry_new ();
1015   if ( tr->comment )
1016     gtk_entry_set_text ( GTK_ENTRY(widgets->w_comment), tr->comment );
1017   g_signal_connect_swapped ( widgets->w_comment, "activate", G_CALLBACK(a_dialog_response_accept), GTK_DIALOG(dialog) );
1018   content[cnt++] = widgets->w_comment;
1019
1020   vik_units_distance_t dist_units = a_vik_get_units_distance ();
1021
1022   tr_len = widgets->track_length = vik_track_get_length(tr);
1023   switch (dist_units) {
1024   case VIK_UNITS_DISTANCE_KILOMETRES:
1025     g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f km", tr_len/1000.0 );
1026     break;
1027   case VIK_UNITS_DISTANCE_MILES:
1028     g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f miles", VIK_METERS_TO_MILES(tr_len) );
1029     break;
1030   default:
1031     g_critical("Houston, we've had a problem. distance=%d", dist_units);
1032   }
1033   widgets->w_track_length = content[cnt++] = gtk_label_new ( tmp_buf );
1034
1035   tp_count = vik_track_get_tp_count(tr);
1036   g_snprintf(tmp_buf, sizeof(tmp_buf), "%u", tp_count );
1037   widgets->w_tp_count = content[cnt++] = gtk_label_new ( tmp_buf );
1038
1039   seg_count = vik_track_get_segment_count(tr) ;
1040   g_snprintf(tmp_buf, sizeof(tmp_buf), "%u", seg_count );
1041   widgets->w_segment_count = content[cnt++] = gtk_label_new ( tmp_buf );
1042
1043   g_snprintf(tmp_buf, sizeof(tmp_buf), "%lu", vik_track_get_dup_point_count(tr) );
1044   widgets->w_duptp_count = content[cnt++] = gtk_label_new ( tmp_buf );
1045
1046   vik_units_speed_t speed_units = a_vik_get_units_speed ();
1047   tmp_speed = vik_track_get_max_speed(tr);
1048   if ( tmp_speed == 0 )
1049     g_snprintf(tmp_buf, sizeof(tmp_buf), _("No Data"));
1050   else {
1051     switch (speed_units) {
1052     case VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
1053       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f km/h", VIK_MPS_TO_KPH(tmp_speed));
1054       break;
1055     case VIK_UNITS_SPEED_MILES_PER_HOUR:
1056       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f mph", VIK_MPS_TO_MPH(tmp_speed));
1057       break;
1058     case VIK_UNITS_SPEED_METRES_PER_SECOND:
1059       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f m/s", tmp_speed );
1060       break;
1061     case VIK_UNITS_SPEED_KNOTS:
1062       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f knots", VIK_MPS_TO_KNOTS(tmp_speed));
1063       break;
1064     default:
1065       g_snprintf (tmp_buf, sizeof(tmp_buf), "--" );
1066       g_critical("Houston, we've had a problem. speed=%d", speed_units);
1067     }
1068   }
1069   widgets->w_max_speed = content[cnt++] = gtk_label_new ( tmp_buf );
1070
1071   tmp_speed = vik_track_get_average_speed(tr);
1072   if ( tmp_speed == 0 )
1073     g_snprintf(tmp_buf, sizeof(tmp_buf), _("No Data"));
1074   else {
1075     switch (speed_units) {
1076     case VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
1077       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f km/h", VIK_MPS_TO_KPH(tmp_speed));
1078       break;
1079     case VIK_UNITS_SPEED_MILES_PER_HOUR:
1080       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f mph", VIK_MPS_TO_MPH(tmp_speed));
1081       break;
1082     case VIK_UNITS_SPEED_METRES_PER_SECOND:
1083       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f m/s", tmp_speed );
1084       break;
1085     case VIK_UNITS_SPEED_KNOTS:
1086       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f knots", VIK_MPS_TO_KNOTS(tmp_speed));
1087       break;
1088     default:
1089       g_snprintf (tmp_buf, sizeof(tmp_buf), "--" );
1090       g_critical("Houston, we've had a problem. speed=%d", speed_units);
1091     }
1092   }
1093   widgets->w_avg_speed = content[cnt++] = gtk_label_new ( tmp_buf );
1094
1095   switch (dist_units) {
1096   case VIK_UNITS_DISTANCE_KILOMETRES:
1097     // Even though kilometres, the average distance between points is going to be quite small so keep in metres
1098     g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f m", (tp_count - seg_count) == 0 ? 0 : tr_len / ( tp_count - seg_count ) );
1099     break;
1100   case VIK_UNITS_DISTANCE_MILES:
1101     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 )) );
1102     break;
1103   default:
1104     g_critical("Houston, we've had a problem. distance=%d", dist_units);
1105   }
1106   widgets->w_avg_dist = content[cnt++] = gtk_label_new ( tmp_buf );
1107
1108   vik_units_height_t height_units = a_vik_get_units_height ();
1109   if ( min_alt == VIK_DEFAULT_ALTITUDE )
1110     g_snprintf(tmp_buf, sizeof(tmp_buf), _("No Data"));
1111   else {
1112     switch (height_units) {
1113     case VIK_UNITS_HEIGHT_METRES:
1114       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.0f m - %.0f m", min_alt, max_alt );
1115       break;
1116     case VIK_UNITS_HEIGHT_FEET:
1117       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.0f feet - %.0f feet", VIK_METERS_TO_FEET(min_alt), VIK_METERS_TO_FEET(max_alt) );
1118       break;
1119     default:
1120       g_snprintf(tmp_buf, sizeof(tmp_buf), "--" );
1121       g_critical("Houston, we've had a problem. height=%d", height_units);
1122     }
1123   }
1124   widgets->w_elev_range = content[cnt++] = gtk_label_new ( tmp_buf );
1125
1126   vik_track_get_total_elevation_gain(tr, &max_alt, &min_alt );
1127   if ( min_alt == VIK_DEFAULT_ALTITUDE )
1128     g_snprintf(tmp_buf, sizeof(tmp_buf), _("No Data"));
1129   else {
1130     switch (height_units) {
1131     case VIK_UNITS_HEIGHT_METRES:
1132       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.0f m / %.0f m", max_alt, min_alt );
1133       break;
1134     case VIK_UNITS_HEIGHT_FEET:
1135       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.0f feet / %.0f feet", VIK_METERS_TO_FEET(max_alt), VIK_METERS_TO_FEET(min_alt) );
1136       break;
1137     default:
1138       g_snprintf(tmp_buf, sizeof(tmp_buf), "--" );
1139       g_critical("Houston, we've had a problem. height=%d", height_units);
1140     }
1141   }
1142   widgets->w_elev_gain = content[cnt++] = gtk_label_new ( tmp_buf );
1143
1144 #if 0
1145 #define PACK(w) gtk_box_pack_start (GTK_BOX(right_vbox), w, FALSE, FALSE, 0);
1146   gtk_box_pack_start (GTK_BOX(right_vbox), e_cmt, FALSE, FALSE, 0); 
1147   PACK(l_len);
1148   PACK(l_tps);
1149   PACK(l_segs);
1150   PACK(l_dups);
1151   PACK(l_maxs);
1152   PACK(l_avgs);
1153   PACK(l_avgd);
1154   PACK(l_elev);
1155   PACK(l_galo);
1156 #undef PACK;
1157 #endif
1158
1159   if ( tr->trackpoints && VIK_TRACKPOINT(tr->trackpoints->data)->timestamp )
1160   {
1161     time_t t1, t2;
1162     t1 = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
1163     t2 = VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->timestamp;
1164
1165     strncpy(tmp_buf, ctime(&t1), sizeof(tmp_buf));
1166     tmp_buf[sizeof(tmp_buf)-1] = 0;
1167     g_strchomp(tmp_buf);
1168     widgets->w_time_start = content[cnt++] = gtk_label_new(tmp_buf);
1169
1170     strncpy(tmp_buf, ctime(&t2), sizeof(tmp_buf));
1171     tmp_buf[sizeof(tmp_buf)-1] = 0;
1172     g_strchomp(tmp_buf);
1173     widgets->w_time_end = content[cnt++] = gtk_label_new(tmp_buf);
1174
1175     g_snprintf(tmp_buf, sizeof(tmp_buf), _("%d minutes"), (int)(t2-t1)/60);
1176     widgets->w_time_dur = content[cnt++] = gtk_label_new(tmp_buf);
1177   } else {
1178     widgets->w_time_start = content[cnt++] = gtk_label_new(_("No Data"));
1179     widgets->w_time_end = content[cnt++] = gtk_label_new(_("No Data"));
1180     widgets->w_time_dur = content[cnt++] = gtk_label_new(_("No Data"));
1181   }
1182
1183   table = GTK_TABLE(gtk_table_new (cnt, 2, FALSE));
1184   gtk_table_set_col_spacing (table, 0, 10);
1185   for (i=0; i<cnt; i++) {
1186     GtkWidget *label;
1187
1188     label = gtk_label_new(NULL);
1189     gtk_misc_set_alignment ( GTK_MISC(label), 1, 0 );
1190     gtk_label_set_markup ( GTK_LABEL(label), _(label_texts[i]) );
1191     gtk_table_attach_defaults ( table, label, 0, 1, i, i+1 );
1192     if (GTK_IS_MISC(content[i])) {
1193       gtk_misc_set_alignment ( GTK_MISC(content[i]), 0, 0 );
1194     }
1195     gtk_table_attach_defaults ( table, content[i], 1, 2, i, i+1 );
1196   }
1197
1198   gtk_notebook_append_page(GTK_NOTEBOOK(graphs), GTK_WIDGET(table), gtk_label_new(_("Statistics")));
1199
1200   if ( widgets->elev_box ) {
1201     GtkWidget *page = NULL;
1202     widgets->w_cur_dist = gtk_label_new(_("No Data"));
1203     widgets->w_cur_elevation = gtk_label_new(_("No Data"));
1204     page = create_graph_page (widgets->elev_box,
1205                               _("<b>Track Distance:</b>"), widgets->w_cur_dist,
1206                               _("<b>Track Height:</b>"), widgets->w_cur_elevation);
1207     gtk_notebook_append_page(GTK_NOTEBOOK(graphs), page, gtk_label_new(_("Elevation-distance")));
1208   }
1209
1210   if ( widgets->speed_box ) {
1211     GtkWidget *page = NULL;
1212     widgets->w_cur_time = gtk_label_new(_("No Data"));
1213     widgets->w_cur_speed = gtk_label_new(_("No Data"));
1214     page = create_graph_page (widgets->speed_box,
1215                               _("<b>Track Time:</b>"), widgets->w_cur_time,
1216                               _("<b>Track Speed:</b>"), widgets->w_cur_speed);
1217     gtk_notebook_append_page(GTK_NOTEBOOK(graphs), page, gtk_label_new(_("Speed-time")));
1218   }
1219
1220   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), graphs, FALSE, FALSE, 0);
1221
1222   gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog), VIK_TRW_LAYER_PROPWIN_SPLIT_MARKER, FALSE);
1223   if (seg_count <= 1)
1224     gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog), VIK_TRW_LAYER_PROPWIN_SPLIT, FALSE);
1225   if (vik_track_get_dup_point_count(tr) <= 0)
1226     gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog), VIK_TRW_LAYER_PROPWIN_DEL_DUP, FALSE);
1227
1228   gpointer *pass_along;
1229   pass_along = g_malloc ( sizeof(gpointer) * 3 ); /* FIXME: mem leak -- never be freed */
1230   pass_along[0] = tr;
1231   pass_along[1] = vlp;
1232   pass_along[2] = widgets;
1233
1234   // On dialog realization configure_event casues the graphs to be initially drawn
1235   widgets->configure_dialog = TRUE;
1236   g_signal_connect ( G_OBJECT(dialog), "configure-event", G_CALLBACK (configure_event), pass_along);
1237
1238   vik_track_set_property_dialog(tr, dialog);
1239   gtk_dialog_set_default_response ( GTK_DIALOG(dialog), GTK_RESPONSE_ACCEPT );
1240   gtk_widget_show_all ( dialog );
1241 }