]> git.street.me.uk Git - andy/viking.git/blob - src/vikutils.c
Add trackpoint message output option value of the distance to the end of the track.
[andy/viking.git] / src / vikutils.c
1 /* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
2 /*
3  * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
4  *
5  * Copyright (C) 2013, Rob Norris <rw_norris@hotmail.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  */
22 /*
23  * Dependencies in this file can be on anything.
24  * For functions with simple system dependencies put it in util.c
25  */
26 #include <math.h>
27 #include <glib/gstdio.h>
28 #include <glib/gi18n.h>
29 #include <gtk/gtk.h>
30
31 #include "viking.h"
32 #include "vikutils.h"
33 #include "globals.h"
34 #include "download.h"
35 #include "preferences.h"
36 #include "vikmapslayer.h"
37 #include "settings.h"
38 #include "util.h"
39 #include "dir.h"
40 #include "misc/kdtree.h"
41
42 #define FMT_MAX_NUMBER_CODES 9
43
44 /**
45  * vu_trackpoint_formatted_message:
46  * @format_code:  String describing the message to generate
47  * @trkpt:        The trackpoint for which the message is generated about
48  * @trkpt_prev:   A trackpoint (presumed previous) for interpolating values with the other trackpoint (such as speed)
49  * @trk:          The track in which the trackpoints reside
50  *
51  *  TODO: One day replace this cryptic format code with some kind of tokenizer parsing
52  *    thus would make it more user friendly and maybe even GUI controlable.
53  * However for now at least there is some semblance of user control
54  */
55 gchar* vu_trackpoint_formatted_message ( gchar *format_code, VikTrackpoint *trkpt, VikTrackpoint *trkpt_prev, VikTrack *trk )
56 {
57         if ( !trkpt )
58                 return NULL;
59
60         gint len = 0;
61         if ( format_code )
62                 len = strlen ( format_code );
63         if ( len > FMT_MAX_NUMBER_CODES )
64                 len = FMT_MAX_NUMBER_CODES;
65
66         gchar* values[FMT_MAX_NUMBER_CODES];
67         int i;
68         for ( i = 0; i < FMT_MAX_NUMBER_CODES; i++ ) {
69                 values[i] = '\0';
70         }
71
72         gchar *speed_units_str = NULL;
73         vik_units_speed_t speed_units = a_vik_get_units_speed ();
74         switch (speed_units) {
75         case VIK_UNITS_SPEED_MILES_PER_HOUR:
76                 speed_units_str = g_strdup ( _("mph") );
77                 break;
78         case VIK_UNITS_SPEED_METRES_PER_SECOND:
79                 speed_units_str = g_strdup ( _("m/s") );
80                 break;
81         case VIK_UNITS_SPEED_KNOTS:
82                 speed_units_str = g_strdup ( _("knots") );
83                 break;
84         default:
85                 // VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
86                 speed_units_str = g_strdup ( _("km/h") );
87                 break;
88         }
89
90         gchar *separator = g_strdup ( " | " );
91
92         for ( i = 0; i < len; i++ ) {
93                 switch ( g_ascii_toupper ( format_code[i] ) ) {
94                 case 'G': values[i] = g_strdup ( _("GPSD") ); break; // GPS Preamble
95                 case 'K': values[i] = g_strdup ( _("Trkpt") ); break; // Trkpt Preamble
96
97                 case 'S': {
98                         gdouble speed = 0.0;
99                         gchar *speedtype = NULL;
100                         if ( isnan(trkpt->speed) && trkpt_prev ) {
101                                 if ( trkpt->has_timestamp && trkpt_prev->has_timestamp ) {
102                                         if ( trkpt->timestamp == trkpt_prev->timestamp ) {
103
104                                                 // Work out from previous trackpoint location and time difference
105                                                 speed = vik_coord_diff(&(trkpt->coord), &(trkpt_prev->coord)) / ABS(trkpt->timestamp - trkpt_prev->timestamp);
106
107                                                 switch (speed_units) {
108                                                 case VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
109                                                         speed = VIK_MPS_TO_KPH(speed);
110                                                         break;
111                                                 case VIK_UNITS_SPEED_MILES_PER_HOUR:
112                                                         speed = VIK_MPS_TO_MPH(speed);
113                                                         break;
114                                                 case VIK_UNITS_SPEED_KNOTS:
115                                                         speed = VIK_MPS_TO_KNOTS(speed);
116                                                         break;
117                                                 default:
118                                                         // VIK_UNITS_SPEED_METRES_PER_SECOND:
119                                                         // Already in m/s so nothing to do
120                                                         break;
121                                                 }
122                                                 speedtype = g_strdup ( "*" ); // Interpolated
123                                         }
124                                         else
125                                                 speedtype = g_strdup ( "**" );
126                                 }
127                                 else
128                                         speedtype = g_strdup ( "**" );
129                         }
130                         else {
131                                 speed = trkpt->speed;
132                                 speedtype = g_strdup ( "" );
133                         }
134
135                         values[i] = g_strdup_printf ( _("%sSpeed%s %.1f%s"), separator, speedtype, speed, speed_units_str );
136                         g_free ( speedtype );
137                         break;
138                 }
139
140                 case 'A': {
141                         vik_units_height_t height_units = a_vik_get_units_height ();
142                         switch (height_units) {
143                         case VIK_UNITS_HEIGHT_FEET:
144                                 values[i] = g_strdup_printf ( _("%sAlt %dfeet"), separator, (int)round(VIK_METERS_TO_FEET(trkpt->altitude)) );
145                                 break;
146                         default:
147                                 //VIK_UNITS_HEIGHT_METRES:
148                                 values[i] = g_strdup_printf ( _("%sAlt %dm"), separator, (int)round(trkpt->altitude) );
149                                 break;
150                         }
151                         break;
152                 }
153
154                 case 'C': {
155                         gint heading = isnan(trkpt->course) ? 0 : (gint)round(trkpt->course);
156                         values[i] = g_strdup_printf ( _("%sCourse %03d\302\260" ), separator, heading );
157                         break;
158                 }
159
160                 case 'P': {
161                         if ( trkpt_prev ) {
162                                 gint diff = (gint) round ( vik_coord_diff ( &(trkpt->coord), &(trkpt_prev->coord) ) );
163
164                                 gchar *dist_units_str = NULL;
165                                 vik_units_distance_t dist_units = a_vik_get_units_distance ();
166                                 // expect the difference between track points to be small hence use metres or yards
167                                 switch (dist_units) {
168                                 case VIK_UNITS_DISTANCE_MILES:
169                                 case VIK_UNITS_DISTANCE_NAUTICAL_MILES:
170                                         dist_units_str = g_strdup ( _("yards") );
171                                         break;
172                                 default:
173                                         // VIK_UNITS_DISTANCE_KILOMETRES:
174                                         dist_units_str = g_strdup ( _("m") );
175                                         break;
176                                 }
177
178                                 values[i] = g_strdup_printf ( _("%sDistance diff %d%s"), separator, diff, dist_units_str );
179
180                                 g_free ( dist_units_str );
181                         }
182                         break;
183                 }
184
185                 case 'T': {
186                         gchar *msg;
187                         if ( trkpt->has_timestamp ) {
188                                 // Compact date time format
189                                 msg = vu_get_time_string ( &(trkpt->timestamp), "%x %X", &(trkpt->coord), NULL );
190                         }
191                         else
192                                 msg = g_strdup ("--");
193                         values[i] = g_strdup_printf ( _("%sTime %s"), separator, msg );
194                         g_free ( msg );
195                         break;
196                 }
197
198                 case 'M': {
199                         if ( trkpt_prev ) {
200                                 if ( trkpt->has_timestamp && trkpt_prev->has_timestamp ) {
201                                         time_t t_diff = trkpt->timestamp - trkpt_prev->timestamp;
202                                         values[i] = g_strdup_printf ( _("%sTime diff %lds"), separator, t_diff );
203                                 }
204                         }
205                         break;
206                 }
207
208                 case 'X': values[i] = g_strdup_printf ( _("%sNo. of Sats %d"), separator, trkpt->nsats ); break;
209
210                 case 'F': {
211                         if ( trk ) {
212                                 // Distance to the end 'Finish' (along the track)
213                                 gdouble distd = vik_track_get_length_to_trackpoint (trk, trkpt);
214                                 gdouble diste = vik_track_get_length_including_gaps ( trk );
215                                 gdouble dist = diste - distd;
216                                 gchar *dist_units_str = NULL;
217                                 vik_units_distance_t dist_units = a_vik_get_units_distance ();
218                                 switch (dist_units) {
219                                 case VIK_UNITS_DISTANCE_MILES:
220                                         dist_units_str = g_strdup ( _("miles") );
221                                         dist = VIK_METERS_TO_MILES(dist);
222                                         break;
223                                 case VIK_UNITS_DISTANCE_NAUTICAL_MILES:
224                                         dist_units_str = g_strdup ( _("NM") );
225                                         dist = VIK_METERS_TO_NAUTICAL_MILES(dist);
226                                         break;
227                                 default:
228                                         // VIK_UNITS_DISTANCE_KILOMETRES:
229                                         dist_units_str = g_strdup ( _("km") );
230                                         dist = dist / 1000.0;
231                                         break;
232                                 }
233                                 values[i] = g_strdup_printf ( _("%sTo End %.2f%s"), separator, dist, dist_units_str );
234                                 g_free ( dist_units_str );
235                         }
236                         break;
237                 }
238
239                 case 'D': {
240                         if ( trk ) {
241                                 // Distance from start (along the track)
242                                 gdouble distd = vik_track_get_length_to_trackpoint (trk, trkpt);
243                                 gchar *dist_units_str = NULL;
244                                 vik_units_distance_t dist_units = a_vik_get_units_distance ();
245                                 switch (dist_units) {
246                                 case VIK_UNITS_DISTANCE_MILES:
247                                         dist_units_str = g_strdup ( _("miles") );
248                                         distd = VIK_METERS_TO_MILES(distd);
249                                         break;
250                                 case VIK_UNITS_DISTANCE_NAUTICAL_MILES:
251                                         dist_units_str = g_strdup ( _("NM") );
252                                         distd = VIK_METERS_TO_NAUTICAL_MILES(distd);
253                                         break;
254                                 default:
255                                         // VIK_UNITS_DISTANCE_KILOMETRES:
256                                         dist_units_str = g_strdup ( _("km") );
257                                         distd = distd / 1000.0;
258                                         break;
259                                 }
260                                 values[i] = g_strdup_printf ( _("%sDistance along %.2f%s"), separator, distd, dist_units_str );
261                                 g_free ( dist_units_str );
262                         }
263                         break;
264                 }
265
266                 case 'L': {
267                         // Location (Lat/Long)
268                         gchar *lat = NULL, *lon = NULL;
269                         struct LatLon ll;
270                         vik_coord_to_latlon (&(trkpt->coord), &ll);
271                         a_coords_latlon_to_string ( &ll, &lat, &lon );
272                         values[i] = g_strdup_printf ( "%s%s %s", separator, lat, lon );
273                         g_free ( lat );
274                         g_free ( lon );
275                         break;
276                 }
277
278                 case 'N': // Name of track
279                         values[i] = g_strdup_printf ( _("%sTrack: %s"), separator, trk->name );
280                         break;
281
282                 case 'E': // Name of trackpoint if available
283                         if ( trkpt->name )
284                                 values[i] = g_strdup_printf ( "%s%s", separator, trkpt->name );
285                         else
286                                 values[i] = g_strdup ( "" );
287                         break;
288
289                 default:
290                         break;
291                 }
292         }
293
294         g_free ( separator );
295         g_free ( speed_units_str );
296
297         gchar *msg = g_strconcat ( values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], NULL );
298
299         for ( i = 0; i < FMT_MAX_NUMBER_CODES; i++ ) {
300                 if ( values[i] != '\0' )
301                         g_free ( values[i] );
302         }
303         
304         return msg;
305 }
306
307 typedef struct {
308         GtkWindow *window; // Layer needed for redrawing
309         gchar *version;    // Image list
310 } new_version_thread_data;
311
312 static gboolean new_version_available_message ( new_version_thread_data *nvtd )
313 {
314         // Only a simple goto website option is offered
315         // Trying to do an installation update is platform specific
316         if ( a_dialog_yes_or_no ( nvtd->window,
317                                 _("There is a newer version of Viking available: %s\n\nDo you wish to go to Viking's website now?"), nvtd->version ) )
318                 // NB 'VIKING_URL' redirects to the Wiki, here we want to go the main site.
319                 open_url ( nvtd->window, "http://sourceforge.net/projects/viking/" );
320
321         g_free ( nvtd->version );
322         g_free ( nvtd );
323         return FALSE;
324 }
325
326 #define VIK_SETTINGS_VERSION_CHECKED_DATE "version_checked_date"
327
328 static void latest_version_thread ( GtkWindow *window )
329 {
330         // Need to allow a few redirects, as SF file is often served from different server
331         DownloadMapOptions options = { FALSE, FALSE, NULL, 5, NULL, NULL, NULL };
332         gchar *filename = a_download_uri_to_tmp_file ( "http://sourceforge.net/projects/viking/files/VERSION", &options );
333         //gchar *filename = g_strdup ( "VERSION" );
334         if ( !filename ) {
335                 return;
336         }
337
338         GMappedFile *mf = g_mapped_file_new ( filename, FALSE, NULL );
339         if ( !mf )
340                 return;
341
342         gchar *text = g_mapped_file_get_contents ( mf );
343
344         gint latest_version = viking_version_to_number ( text );
345         gint my_version = viking_version_to_number ( VIKING_VERSION );
346
347         g_debug ( "The lastest version is: %s", text );
348
349         if ( my_version < latest_version ) {
350                 new_version_thread_data *nvtd = g_malloc ( sizeof(new_version_thread_data) );
351                 nvtd->window = window;
352                 nvtd->version = g_strdup ( text );
353                 gdk_threads_add_idle ( (GSourceFunc) new_version_available_message, nvtd );
354         }
355         else
356                 g_debug ( "Running the lastest version: %s", VIKING_VERSION );
357
358         g_mapped_file_unref ( mf );
359         if ( filename ) {
360                 g_remove ( filename );
361                 g_free ( filename );
362         }
363
364         // Update last checked time
365         GTimeVal time;
366         g_get_current_time ( &time );
367         a_settings_set_string ( VIK_SETTINGS_VERSION_CHECKED_DATE, g_time_val_to_iso8601(&time) );
368 }
369
370 #define VIK_SETTINGS_VERSION_CHECK_PERIOD "version_check_period_days"
371
372 /**
373  * vu_check_latest_version:
374  * @window: Somewhere where we may need use the display to inform the user about the version status
375  *
376  * Periodically checks the released latest VERSION file on the website to compare with the running version
377  *
378  */
379 void vu_check_latest_version ( GtkWindow *window )
380 {
381         if ( ! a_vik_get_check_version () )
382                 return;
383
384         gboolean do_check = FALSE;
385
386         gint check_period;
387         if ( ! a_settings_get_integer ( VIK_SETTINGS_VERSION_CHECK_PERIOD, &check_period ) ) {
388                 check_period = 14;
389         }
390
391         // Get last checked date...
392         GDate *gdate_last = g_date_new();
393         GDate *gdate_now = g_date_new();
394         GTimeVal time_last;
395         gchar *last_checked_date = NULL;
396
397         // When no previous date available - set to do the version check
398         if ( a_settings_get_string ( VIK_SETTINGS_VERSION_CHECKED_DATE, &last_checked_date) ) {
399                 if ( g_time_val_from_iso8601 ( last_checked_date, &time_last ) ) {
400                         g_date_set_time_val ( gdate_last, &time_last );
401                 }
402                 else
403                         do_check = TRUE;
404         }
405         else
406                 do_check = TRUE;
407
408         GTimeVal time_now;
409         g_get_current_time ( &time_now );
410         g_date_set_time_val ( gdate_now, &time_now );
411
412         if ( ! do_check ) {
413                 // Dates available so do the comparison
414                 g_date_add_days ( gdate_last, check_period );
415                 if ( g_date_compare ( gdate_last, gdate_now ) < 0 )
416                         do_check = TRUE;
417         }
418
419         g_date_free ( gdate_last );
420         g_date_free ( gdate_now );
421
422         if ( do_check ) {
423 #if GLIB_CHECK_VERSION (2, 32, 0)
424                 g_thread_try_new ( "latest_version_thread", (GThreadFunc)latest_version_thread, window, NULL );
425 #else
426                 g_thread_create ( (GThreadFunc)latest_version_thread, window, FALSE, NULL );
427 #endif
428         }
429 }
430
431 /**
432  * vu_set_auto_features_on_first_run:
433  *
434  *  Ask the user's opinion to set some of Viking's default behaviour
435  */
436 void vu_set_auto_features_on_first_run ( void )
437 {
438         gboolean auto_features = FALSE;
439         if ( a_vik_very_first_run () ) {
440
441                 GtkWidget *win = gtk_window_new ( GTK_WINDOW_TOPLEVEL );
442
443                 if ( a_dialog_yes_or_no ( GTK_WINDOW(win),
444                                           _("This appears to be Viking's very first run.\n\nDo you wish to enable automatic internet features?\n\nIndividual settings can be controlled in the Preferences."), NULL ) )
445                         auto_features = TRUE;
446         }
447
448         if ( auto_features ) {
449                 // Set Maps to autodownload
450                 // Ensure the default is true
451                 maps_layer_set_autodownload_default ( TRUE );
452
453                 // Simplistic repeat of preference settings
454                 //  Only the name & type are important for setting a preference via this 'external' way
455
456                 // Enable auto add map +
457                 // Enable IP lookup
458                 VikLayerParam pref_add_map[] = { { VIK_LAYER_NUM_TYPES, VIKING_PREFERENCES_STARTUP_NAMESPACE "add_default_map_layer", VIK_LAYER_PARAM_BOOLEAN, VIK_LAYER_GROUP_NONE, NULL, VIK_LAYER_WIDGET_CHECKBUTTON, NULL, NULL, NULL, NULL, NULL, NULL, }, };
459                 VikLayerParam pref_startup_method[] = { { VIK_LAYER_NUM_TYPES, VIKING_PREFERENCES_STARTUP_NAMESPACE "startup_method", VIK_LAYER_PARAM_UINT, VIK_LAYER_GROUP_NONE, NULL, VIK_LAYER_WIDGET_COMBOBOX, NULL, NULL, NULL, NULL, NULL, NULL}, };
460
461                 VikLayerParamData vlp_data;
462                 vlp_data.b = TRUE;
463                 a_preferences_run_setparam ( vlp_data, pref_add_map );
464
465                 vlp_data.u = VIK_STARTUP_METHOD_AUTO_LOCATION;
466                 a_preferences_run_setparam ( vlp_data, pref_startup_method );
467
468                 // Only on Windows make checking for the latest version on by default
469                 // For other systems it's expected a Package manager or similar controls the installation, so leave it off
470 #ifdef WINDOWS
471                 VikLayerParam pref_startup_version_check[] = { { VIK_LAYER_NUM_TYPES, VIKING_PREFERENCES_STARTUP_NAMESPACE "check_version", VIK_LAYER_PARAM_BOOLEAN, VIK_LAYER_GROUP_NONE, NULL, VIK_LAYER_WIDGET_CHECKBUTTON, NULL, NULL, NULL, NULL, }, };
472                 vlp_data.b = TRUE;
473                 a_preferences_run_setparam ( vlp_data, pref_startup_version_check );
474 #endif
475
476                 // Ensure settings are saved for next time
477                 a_preferences_save_to_file ();
478         }
479 }
480
481 /**
482  * vu_get_canonical_filename:
483  *
484  * Returns: Canonical absolute filename
485  *
486  * Any time a path may contain a relative component, so need to prepend that directory it is relative to
487  * Then resolve the full path to get the normal canonical filename
488  */
489 gchar *vu_get_canonical_filename ( VikLayer *vl, const gchar *filename )
490 {
491   gchar *canonical = NULL;
492   if ( !filename )
493     return NULL;
494
495   if ( g_path_is_absolute ( filename ) )
496     canonical = g_strdup ( filename );
497   else {
498     const gchar *vw_filename = vik_window_get_filename ( VIK_WINDOW_FROM_WIDGET (vl->vvp) );
499     gchar *dirpath = NULL;
500     if ( vw_filename )
501       dirpath = g_path_get_dirname ( vw_filename );
502     else
503       dirpath = g_get_current_dir(); // Fallback - if here then probably can't create the correct path
504
505     gchar *full = NULL;
506     if ( g_path_is_absolute ( dirpath ) )
507       full = g_strconcat ( dirpath, G_DIR_SEPARATOR_S, filename, NULL );
508     else
509       full = g_strconcat ( g_get_current_dir(), G_DIR_SEPARATOR_S, dirpath, G_DIR_SEPARATOR_S, filename, NULL );
510
511     canonical = file_realpath_dup ( full ); // resolved
512     g_free ( full );
513     g_free ( dirpath );
514   }
515
516   return canonical;
517 }
518
519 static struct kdtree *kd = NULL;
520
521 static void load_ll_tz_dir ( const gchar *dir )
522 {
523         gchar *lltz = g_build_filename ( dir, "latlontz.txt", NULL );
524         if ( g_access(lltz, R_OK) == 0 ) {
525                 gchar buffer[4096];
526                 long line_num = 0;
527                 FILE *ff = g_fopen ( lltz, "r" );
528
529                 while ( fgets ( buffer, 4096, ff ) ) {
530                         line_num++;
531                         gchar **components = g_strsplit (buffer, " ", 3);
532                         guint nn = g_strv_length ( components );
533                         if ( nn == 3 ) {
534                                 double pt[2] = { g_ascii_strtod (components[0], NULL), g_ascii_strtod (components[1], NULL) };
535                                 gchar *timezone = g_strchomp ( components[2] );
536                                 if ( kd_insert ( kd, pt, timezone ) )
537                                         g_critical ( "Insertion problem of %s for line %ld of latlontz.txt", timezone, line_num );
538                                 // NB Don't free timezone as it's part of the kdtree data now
539                                 g_free ( components[0] );
540                                 g_free ( components[1] );
541                         } else {
542                                 g_warning ( "Line %ld of latlontz.txt does not have 3 parts", line_num );
543                         }
544                         g_free ( components );
545                 }
546                 fclose ( ff );
547         }
548         g_free ( lltz );
549 }
550
551 /**
552  * vu_setup_lat_lon_tz_lookup:
553  *
554  * Can be called multiple times but only initializes the lookup once
555  */
556 void vu_setup_lat_lon_tz_lookup ()
557 {
558         // Only setup once
559         if ( kd )
560                 return;
561
562         kd = kd_create(2);
563
564         // Look in the directories of data path
565         gchar **data_dirs = a_get_viking_data_path();
566         // Process directories in reverse order for priority
567         guint n_data_dirs = g_strv_length ( data_dirs );
568         for (; n_data_dirs > 0; n_data_dirs--) {
569                 load_ll_tz_dir(data_dirs[n_data_dirs-1]);
570         }
571         g_strfreev ( data_dirs );
572 }
573
574 /**
575  * vu_finalize_lat_lon_tz_lookup:
576  *
577  * Clear memory used by the lookup.
578  *  only call on program exit
579  */
580 void vu_finalize_lat_lon_tz_lookup ()
581 {
582         if ( kd ) {
583                 kd_data_destructor ( kd, g_free );
584                 kd_free ( kd );
585         }
586 }
587
588 static double dist_sq( double *a1, double *a2, int dims ) {
589   double dist_sq = 0, diff;
590   while( --dims >= 0 ) {
591     diff = (a1[dims] - a2[dims]);
592     dist_sq += diff*diff;
593   }
594   return dist_sq;
595 }
596
597 static gchar* time_string_adjusted ( time_t *time, gint offset_s )
598 {
599         time_t *mytime = time;
600         *mytime = *mytime + offset_s;
601         gchar *str = g_malloc ( 64 );
602         // Append asterisks to indicate use of simplistic model (i.e. no TZ)
603         strftime ( str, 64, "%a %X %x **", gmtime(mytime) );
604         return str;
605 }
606
607 static gchar* time_string_tz ( time_t *time, const gchar *format, GTimeZone *tz )
608 {
609         GDateTime *utc = g_date_time_new_from_unix_utc (*time);
610         GDateTime *local = g_date_time_to_timezone ( utc, tz );
611         if ( !local ) {
612                 g_date_time_unref ( utc );
613                 return NULL;
614         }
615         gchar *str = g_date_time_format ( local, format );
616
617         g_date_time_unref ( local );
618         g_date_time_unref ( utc );
619         return str;
620 }
621
622 #define VIK_SETTINGS_NEAREST_TZ_FACTOR "utils_nearest_tz_factor"
623 /**
624  * vu_get_tz_at_location:
625  *
626  * @vc:     Position for which the time zone is desired
627  *
628  * Returns: TimeZone string of the nearest known location. String may be NULL.
629  *
630  * Use the k-d tree method (http://en.wikipedia.org/wiki/Kd-tree) to quickly retreive
631  *  the nearest location to the given position.
632  */
633 gchar* vu_get_tz_at_location ( const VikCoord* vc )
634 {
635         gchar *tz = NULL;
636         if ( !vc || !kd )
637                 return tz;
638
639         struct LatLon ll;
640         vik_coord_to_latlon ( vc, &ll );
641         double pt[2] = { ll.lat, ll.lon };
642
643         gdouble nearest;
644         if ( !a_settings_get_double(VIK_SETTINGS_NEAREST_TZ_FACTOR, &nearest) )
645                 nearest = 1.0;
646
647         struct kdres *presults = kd_nearest_range ( kd, pt, nearest );
648         while( !kd_res_end( presults ) ) {
649                 double pos[2];
650                 gchar *ans = (gchar*)kd_res_item ( presults, pos );
651                 // compute the distance of the current result from the pt
652                 double dist = sqrt( dist_sq( pt, pos, 2 ) );
653                 if ( dist < nearest ) {
654                         //printf( "NEARER node at (%.3f, %.3f, %.3f) is %.3f away is %s\n", pos[0], pos[1], pos[2], dist, ans );
655                         nearest = dist;
656                         tz = ans;
657                 }
658                 kd_res_next ( presults );
659         }
660         g_debug ( "TZ lookup found %d results - picked %s", kd_res_size(presults), tz );
661         kd_res_free ( presults );
662
663         return tz;
664 }
665
666 /**
667  * vu_get_time_string:
668  *
669  * @time_t: The time of which the string is wanted
670  * @format  The format of the time string - such as "%c"
671  * @vc:     Position of object for the time output - maybe NULL
672  *          (only applicable for VIK_TIME_REF_WORLD)
673  * @tz:     TimeZone string - maybe NULL.
674  *          (only applicable for VIK_TIME_REF_WORLD)
675  *          Useful to pass in the cached value from vu_get_tz_at_location() to save looking it up again for the same position
676  *
677  * Returns: A string of the time according to the time display property
678  */
679 gchar* vu_get_time_string ( time_t *time, const gchar *format, const VikCoord* vc, const gchar *tz )
680 {
681         if ( !format ) return NULL;
682         gchar *str = NULL;
683         switch ( a_vik_get_time_ref_frame() ) {
684                 case VIK_TIME_REF_UTC:
685                         str = g_malloc ( 64 );
686                         strftime ( str, 64, format, gmtime(time) ); // Always 'GMT'
687                         break;
688                 case VIK_TIME_REF_WORLD:
689                         if ( vc && !tz ) {
690                                 // No timezone specified so work it out
691                                 gchar *mytz = vu_get_tz_at_location ( vc );
692                                 if ( mytz ) {
693                                         GTimeZone *gtz = g_time_zone_new ( mytz );
694                                         str = time_string_tz ( time, format, gtz );
695                                         g_time_zone_unref ( gtz );
696                                 }
697                                 else {
698                                         // No results (e.g. could be in the middle of a sea)
699                                         // Fallback to simplistic method that doesn't take into account Timezones of countries.
700                                         struct LatLon ll;
701                                         vik_coord_to_latlon ( vc, &ll );
702                                         str = time_string_adjusted ( time, round ( ll.lon / 15.0 ) * 3600 );
703                                 }
704                         }
705                         else {
706                                 // Use specified timezone
707                                 GTimeZone *gtz = g_time_zone_new ( tz );
708                                 str = time_string_tz ( time, format, gtz );
709                                 g_time_zone_unref ( gtz );
710                         }
711                         break;
712                 default: // VIK_TIME_REF_LOCALE
713                         str = g_malloc ( 64 );
714                         strftime ( str, 64, format, localtime(time) );
715                         break;
716         }
717         return str;
718 }