]> git.street.me.uk Git - andy/viking.git/blame - src/vikutils.c
SF Features#120: Add Nautical Miles preference for distance units.
[andy/viking.git] / src / vikutils.c
CommitLineData
f93e0210
RN
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 */
5ab2942c
RN
22/*
23 * Dependencies in this file can be on anything.
24 * For functions with simple system dependencies put it in util.c
25 */
f93e0210 26#include <math.h>
5ab2942c 27#include <glib/gstdio.h>
f93e0210 28#include <glib/gi18n.h>
5ab2942c 29#include <gtk/gtk.h>
f93e0210 30
3f31bec4 31#include "viking.h"
f93e0210 32#include "vikutils.h"
5ab2942c
RN
33#include "globals.h"
34#include "download.h"
35#include "preferences.h"
36#include "vikmapslayer.h"
37#include "settings.h"
38#include "util.h"
74562734
RN
39#include "dir.h"
40#include "misc/kdtree.h"
f93e0210
RN
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 */
55gchar* 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;
b312b935 100 if ( isnan(trkpt->speed) && trkpt_prev ) {
f93e0210
RN
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:
b22233bd 169 case VIK_UNITS_DISTANCE_NAUTICAL_MILES:
f93e0210
RN
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': {
74562734 186 gchar *msg;
f93e0210
RN
187 if ( trkpt->has_timestamp ) {
188 // Compact date time format
74562734 189 msg = vu_get_time_string ( &(trkpt->timestamp), "%x %X", &(trkpt->coord), NULL );
f93e0210
RN
190 }
191 else
74562734
RN
192 msg = g_strdup ("--");
193 values[i] = g_strdup_printf ( _("%sTime %s"), separator, msg );
194 g_free ( msg );
f93e0210
RN
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 'D': {
211 if ( trk ) {
bb77b487 212 // Distance from start (along the track)
f93e0210
RN
213 gdouble distd = vik_track_get_length_to_trackpoint (trk, trkpt);
214 gchar *dist_units_str = NULL;
215 vik_units_distance_t dist_units = a_vik_get_units_distance ();
f93e0210
RN
216 switch (dist_units) {
217 case VIK_UNITS_DISTANCE_MILES:
218 dist_units_str = g_strdup ( _("miles") );
219 distd = VIK_METERS_TO_MILES(distd);
220 break;
b22233bd
RN
221 case VIK_UNITS_DISTANCE_NAUTICAL_MILES:
222 dist_units_str = g_strdup ( _("NM") );
223 distd = VIK_METERS_TO_NAUTICAL_MILES(distd);
224 break;
f93e0210
RN
225 default:
226 // VIK_UNITS_DISTANCE_KILOMETRES:
227 dist_units_str = g_strdup ( _("km") );
228 distd = distd / 1000.0;
229 break;
230 }
231 values[i] = g_strdup_printf ( _("%sDistance along %.2f%s"), separator, distd, dist_units_str );
232 g_free ( dist_units_str );
233 }
234 break;
235 }
236
237 case 'L': {
238 // Location (Lat/Long)
239 gchar *lat = NULL, *lon = NULL;
240 struct LatLon ll;
241 vik_coord_to_latlon (&(trkpt->coord), &ll);
242 a_coords_latlon_to_string ( &ll, &lat, &lon );
243 values[i] = g_strdup_printf ( "%s%s %s", separator, lat, lon );
244 g_free ( lat );
245 g_free ( lon );
246 break;
247 }
248
249 case 'N': // Name of track
250 values[i] = g_strdup_printf ( _("%sTrack: %s"), separator, trk->name );
251 break;
252
b45865b4
RN
253 case 'E': // Name of trackpoint if available
254 if ( trkpt->name )
255 values[i] = g_strdup_printf ( "%s%s", separator, trkpt->name );
256 else
257 values[i] = g_strdup ( "" );
258 break;
259
f93e0210
RN
260 default:
261 break;
262 }
263 }
264
265 g_free ( separator );
266 g_free ( speed_units_str );
267
bb77b487 268 gchar *msg = g_strconcat ( values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], NULL );
f93e0210
RN
269
270 for ( i = 0; i < FMT_MAX_NUMBER_CODES; i++ ) {
271 if ( values[i] != '\0' )
272 g_free ( values[i] );
273 }
274
275 return msg;
276}
5ab2942c
RN
277
278typedef struct {
279 GtkWindow *window; // Layer needed for redrawing
280 gchar *version; // Image list
281} new_version_thread_data;
282
283static gboolean new_version_available_message ( new_version_thread_data *nvtd )
284{
285 // Only a simple goto website option is offered
286 // Trying to do an installation update is platform specific
287 if ( a_dialog_yes_or_no ( nvtd->window,
288 _("There is a newer version of Viking available: %s\n\nDo you wish to go to Viking's website now?"), nvtd->version ) )
289 // NB 'VIKING_URL' redirects to the Wiki, here we want to go the main site.
290 open_url ( nvtd->window, "http://sourceforge.net/projects/viking/" );
291
292 g_free ( nvtd->version );
293 g_free ( nvtd );
294 return FALSE;
295}
296
297#define VIK_SETTINGS_VERSION_CHECKED_DATE "version_checked_date"
298
299static void latest_version_thread ( GtkWindow *window )
300{
301 // Need to allow a few redirects, as SF file is often served from different server
302 DownloadMapOptions options = { FALSE, FALSE, NULL, 5, NULL, NULL, NULL };
303 gchar *filename = a_download_uri_to_tmp_file ( "http://sourceforge.net/projects/viking/files/VERSION", &options );
304 //gchar *filename = g_strdup ( "VERSION" );
305 if ( !filename ) {
306 return;
307 }
308
309 GMappedFile *mf = g_mapped_file_new ( filename, FALSE, NULL );
310 if ( !mf )
311 return;
312
313 gchar *text = g_mapped_file_get_contents ( mf );
314
315 gint latest_version = viking_version_to_number ( text );
316 gint my_version = viking_version_to_number ( VIKING_VERSION );
317
318 g_debug ( "The lastest version is: %s", text );
319
320 if ( my_version < latest_version ) {
321 new_version_thread_data *nvtd = g_malloc ( sizeof(new_version_thread_data) );
322 nvtd->window = window;
323 nvtd->version = g_strdup ( text );
324 gdk_threads_add_idle ( (GSourceFunc) new_version_available_message, nvtd );
325 }
326 else
327 g_debug ( "Running the lastest version: %s", VIKING_VERSION );
328
329 g_mapped_file_unref ( mf );
330 if ( filename ) {
331 g_remove ( filename );
332 g_free ( filename );
333 }
334
335 // Update last checked time
336 GTimeVal time;
337 g_get_current_time ( &time );
338 a_settings_set_string ( VIK_SETTINGS_VERSION_CHECKED_DATE, g_time_val_to_iso8601(&time) );
339}
340
341#define VIK_SETTINGS_VERSION_CHECK_PERIOD "version_check_period_days"
342
343/**
344 * vu_check_latest_version:
345 * @window: Somewhere where we may need use the display to inform the user about the version status
346 *
347 * Periodically checks the released latest VERSION file on the website to compare with the running version
348 *
349 */
350void vu_check_latest_version ( GtkWindow *window )
351{
352 if ( ! a_vik_get_check_version () )
353 return;
354
355 gboolean do_check = FALSE;
356
357 gint check_period;
358 if ( ! a_settings_get_integer ( VIK_SETTINGS_VERSION_CHECK_PERIOD, &check_period ) ) {
359 check_period = 14;
360 }
361
362 // Get last checked date...
363 GDate *gdate_last = g_date_new();
364 GDate *gdate_now = g_date_new();
365 GTimeVal time_last;
366 gchar *last_checked_date = NULL;
367
368 // When no previous date available - set to do the version check
369 if ( a_settings_get_string ( VIK_SETTINGS_VERSION_CHECKED_DATE, &last_checked_date) ) {
370 if ( g_time_val_from_iso8601 ( last_checked_date, &time_last ) ) {
371 g_date_set_time_val ( gdate_last, &time_last );
372 }
373 else
374 do_check = TRUE;
375 }
376 else
377 do_check = TRUE;
378
379 GTimeVal time_now;
380 g_get_current_time ( &time_now );
381 g_date_set_time_val ( gdate_now, &time_now );
382
383 if ( ! do_check ) {
384 // Dates available so do the comparison
385 g_date_add_days ( gdate_last, check_period );
386 if ( g_date_compare ( gdate_last, gdate_now ) < 0 )
387 do_check = TRUE;
388 }
389
390 g_date_free ( gdate_last );
391 g_date_free ( gdate_now );
392
393 if ( do_check ) {
394#if GLIB_CHECK_VERSION (2, 32, 0)
395 g_thread_try_new ( "latest_version_thread", (GThreadFunc)latest_version_thread, window, NULL );
396#else
397 g_thread_create ( (GThreadFunc)latest_version_thread, window, FALSE, NULL );
398#endif
399 }
400}
401
402/**
403 * vu_set_auto_features_on_first_run:
404 *
405 * Ask the user's opinion to set some of Viking's default behaviour
406 */
407void vu_set_auto_features_on_first_run ( void )
408{
409 gboolean auto_features = FALSE;
410 if ( a_vik_very_first_run () ) {
411
412 GtkWidget *win = gtk_window_new ( GTK_WINDOW_TOPLEVEL );
413
414 if ( a_dialog_yes_or_no ( GTK_WINDOW(win),
415 _("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 ) )
416 auto_features = TRUE;
417 }
418
419 if ( auto_features ) {
420 // Set Maps to autodownload
421 // Ensure the default is true
422 maps_layer_set_autodownload_default ( TRUE );
423
424 // Simplistic repeat of preference settings
425 // Only the name & type are important for setting a preference via this 'external' way
426
427 // Enable auto add map +
428 // Enable IP lookup
429 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, }, };
430 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}, };
431
432 VikLayerParamData vlp_data;
433 vlp_data.b = TRUE;
434 a_preferences_run_setparam ( vlp_data, pref_add_map );
435
436 vlp_data.u = VIK_STARTUP_METHOD_AUTO_LOCATION;
437 a_preferences_run_setparam ( vlp_data, pref_startup_method );
438
439 // Only on Windows make checking for the latest version on by default
440 // For other systems it's expected a Package manager or similar controls the installation, so leave it off
441#ifdef WINDOWS
442 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, }, };
443 vlp_data.b = TRUE;
444 a_preferences_run_setparam ( vlp_data, pref_startup_version_check );
445#endif
446
447 // Ensure settings are saved for next time
448 a_preferences_save_to_file ();
449 }
450}
1b14d0d2
RN
451
452/**
453 * vu_get_canonical_filename:
454 *
455 * Returns: Canonical absolute filename
456 *
457 * Any time a path may contain a relative component, so need to prepend that directory it is relative to
458 * Then resolve the full path to get the normal canonical filename
459 */
460gchar *vu_get_canonical_filename ( VikLayer *vl, const gchar *filename )
461{
462 gchar *canonical = NULL;
463 if ( !filename )
464 return NULL;
465
466 if ( g_path_is_absolute ( filename ) )
467 canonical = g_strdup ( filename );
468 else {
469 const gchar *vw_filename = vik_window_get_filename ( VIK_WINDOW_FROM_WIDGET (vl->vvp) );
470 gchar *dirpath = NULL;
471 if ( vw_filename )
472 dirpath = g_path_get_dirname ( vw_filename );
473 else
474 dirpath = g_get_current_dir(); // Fallback - if here then probably can't create the correct path
475
476 gchar *full = NULL;
477 if ( g_path_is_absolute ( dirpath ) )
478 full = g_strconcat ( dirpath, G_DIR_SEPARATOR_S, filename, NULL );
479 else
480 full = g_strconcat ( g_get_current_dir(), G_DIR_SEPARATOR_S, dirpath, G_DIR_SEPARATOR_S, filename, NULL );
481
482 canonical = file_realpath_dup ( full ); // resolved
483 g_free ( full );
484 g_free ( dirpath );
485 }
486
487 return canonical;
488}
8ada46de 489
74562734
RN
490static struct kdtree *kd = NULL;
491
492static void load_ll_tz_dir ( const gchar *dir )
493{
494 gchar *lltz = g_build_filename ( dir, "latlontz.txt", NULL );
495 if ( g_access(lltz, R_OK) == 0 ) {
496 gchar buffer[4096];
497 long line_num = 0;
498 FILE *ff = g_fopen ( lltz, "r" );
499
500 while ( fgets ( buffer, 4096, ff ) ) {
501 line_num++;
502 gchar **components = g_strsplit (buffer, " ", 3);
503 guint nn = g_strv_length ( components );
504 if ( nn == 3 ) {
505 double pt[2] = { g_ascii_strtod (components[0], NULL), g_ascii_strtod (components[1], NULL) };
506 gchar *timezone = g_strchomp ( components[2] );
507 if ( kd_insert ( kd, pt, timezone ) )
508 g_critical ( "Insertion problem of %s for line %ld of latlontz.txt", timezone, line_num );
509 // NB Don't free timezone as it's part of the kdtree data now
510 g_free ( components[0] );
511 g_free ( components[1] );
512 } else {
513 g_warning ( "Line %ld of latlontz.txt does not have 3 parts", line_num );
514 }
515 g_free ( components );
516 }
517 fclose ( ff );
518 }
519 g_free ( lltz );
520}
521
522/**
523 * vu_setup_lat_lon_tz_lookup:
524 *
525 * Can be called multiple times but only initializes the lookup once
526 */
527void vu_setup_lat_lon_tz_lookup ()
528{
529 // Only setup once
530 if ( kd )
531 return;
532
533 kd = kd_create(2);
534
535 // Look in the directories of data path
536 gchar **data_dirs = a_get_viking_data_path();
537 // Process directories in reverse order for priority
538 guint n_data_dirs = g_strv_length ( data_dirs );
539 for (; n_data_dirs > 0; n_data_dirs--) {
540 load_ll_tz_dir(data_dirs[n_data_dirs-1]);
541 }
542 g_strfreev ( data_dirs );
543}
544
545/**
546 * vu_finalize_lat_lon_tz_lookup:
547 *
548 * Clear memory used by the lookup.
549 * only call on program exit
550 */
551void vu_finalize_lat_lon_tz_lookup ()
552{
553 if ( kd ) {
554 kd_data_destructor ( kd, g_free );
555 kd_free ( kd );
556 }
557}
558
559static double dist_sq( double *a1, double *a2, int dims ) {
560 double dist_sq = 0, diff;
561 while( --dims >= 0 ) {
562 diff = (a1[dims] - a2[dims]);
563 dist_sq += diff*diff;
564 }
565 return dist_sq;
566}
567
568static gchar* time_string_adjusted ( time_t *time, gint offset_s )
569{
570 time_t *mytime = time;
571 *mytime = *mytime + offset_s;
572 gchar *str = g_malloc ( 64 );
573 // Append asterisks to indicate use of simplistic model (i.e. no TZ)
574 strftime ( str, 64, "%a %X %x **", gmtime(mytime) );
575 return str;
576}
577
578static gchar* time_string_tz ( time_t *time, const gchar *format, GTimeZone *tz )
579{
580 GDateTime *utc = g_date_time_new_from_unix_utc (*time);
581 GDateTime *local = g_date_time_to_timezone ( utc, tz );
582 if ( !local ) {
583 g_date_time_unref ( utc );
584 return NULL;
585 }
586 gchar *str = g_date_time_format ( local, format );
587
588 g_date_time_unref ( local );
589 g_date_time_unref ( utc );
590 return str;
591}
592
593#define VIK_SETTINGS_NEAREST_TZ_FACTOR "utils_nearest_tz_factor"
594/**
595 * vu_get_tz_at_location:
596 *
597 * @vc: Position for which the time zone is desired
598 *
599 * Returns: TimeZone string of the nearest known location. String may be NULL.
600 *
601 * Use the k-d tree method (http://en.wikipedia.org/wiki/Kd-tree) to quickly retreive
602 * the nearest location to the given position.
603 */
604gchar* vu_get_tz_at_location ( const VikCoord* vc )
605{
606 gchar *tz = NULL;
607 if ( !vc || !kd )
608 return tz;
609
610 struct LatLon ll;
611 vik_coord_to_latlon ( vc, &ll );
612 double pt[2] = { ll.lat, ll.lon };
613
614 gdouble nearest;
615 if ( !a_settings_get_double(VIK_SETTINGS_NEAREST_TZ_FACTOR, &nearest) )
616 nearest = 1.0;
617
618 struct kdres *presults = kd_nearest_range ( kd, pt, nearest );
619 while( !kd_res_end( presults ) ) {
620 double pos[2];
621 gchar *ans = (gchar*)kd_res_item ( presults, pos );
622 // compute the distance of the current result from the pt
623 double dist = sqrt( dist_sq( pt, pos, 2 ) );
624 if ( dist < nearest ) {
625 //printf( "NEARER node at (%.3f, %.3f, %.3f) is %.3f away is %s\n", pos[0], pos[1], pos[2], dist, ans );
626 nearest = dist;
627 tz = ans;
628 }
629 kd_res_next ( presults );
630 }
631 g_debug ( "TZ lookup found %d results - picked %s", kd_res_size(presults), tz );
632 kd_res_free ( presults );
633
634 return tz;
635}
636
8ada46de
RN
637/**
638 * vu_get_time_string:
639 *
640 * @time_t: The time of which the string is wanted
641 * @format The format of the time string - such as "%c"
642 * @vc: Position of object for the time output - maybe NULL
643 * (only applicable for VIK_TIME_REF_WORLD)
644 * @tz: TimeZone string - maybe NULL.
645 * (only applicable for VIK_TIME_REF_WORLD)
74562734 646 * Useful to pass in the cached value from vu_get_tz_at_location() to save looking it up again for the same position
8ada46de
RN
647 *
648 * Returns: A string of the time according to the time display property
649 */
650gchar* vu_get_time_string ( time_t *time, const gchar *format, const VikCoord* vc, const gchar *tz )
651{
652 if ( !format ) return NULL;
653 gchar *str = NULL;
654 switch ( a_vik_get_time_ref_frame() ) {
655 case VIK_TIME_REF_UTC:
656 str = g_malloc ( 64 );
657 strftime ( str, 64, format, gmtime(time) ); // Always 'GMT'
658 break;
659 case VIK_TIME_REF_WORLD:
74562734
RN
660 if ( vc && !tz ) {
661 // No timezone specified so work it out
662 gchar *mytz = vu_get_tz_at_location ( vc );
663 if ( mytz ) {
664 GTimeZone *gtz = g_time_zone_new ( mytz );
665 str = time_string_tz ( time, format, gtz );
666 g_time_zone_unref ( gtz );
667 }
668 else {
669 // No results (e.g. could be in the middle of a sea)
670 // Fallback to simplistic method that doesn't take into account Timezones of countries.
671 struct LatLon ll;
672 vik_coord_to_latlon ( vc, &ll );
673 str = time_string_adjusted ( time, round ( ll.lon / 15.0 ) * 3600 );
674 }
675 }
676 else {
677 // Use specified timezone
678 GTimeZone *gtz = g_time_zone_new ( tz );
679 str = time_string_tz ( time, format, gtz );
680 g_time_zone_unref ( gtz );
8ada46de
RN
681 }
682 break;
683 default: // VIK_TIME_REF_LOCALE
684 str = g_malloc ( 64 );
685 strftime ( str, 64, format, localtime(time) );
686 break;
687 }
688 return str;
689}