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