]> git.street.me.uk Git - andy/viking.git/blob - src/babel.c
SF Bugs#113: Fix waypoints can be accidentally moved on (re)selection by the select...
[andy/viking.git] / src / babel.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) 2006, Quy Tonthat <qtonthat@gmail.com>
6  * Copyright (C) 2013, Guilhem Bonnefille <guilhem.bonnefille@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 /**
25  * SECTION:babel
26  * @short_description: running external programs and redirecting to TRWLayers.
27  *
28  * GPSBabel may not be necessary for everything -- for instance,
29  *   use a_babel_convert_from_shellcommand() with input_file_type == %NULL
30  *   for an external program that outputs GPX.
31  */
32
33 #ifdef HAVE_CONFIG_H
34 #include "config.h"
35 #endif
36
37 #include "viking.h"
38 #include "gpx.h"
39 #include "babel.h"
40 #include "preferences.h"
41 #include <stdio.h>
42 #ifdef HAVE_UNISTD_H
43 #include <unistd.h>
44 #endif
45 #include <string.h>
46 #include <glib.h>
47 #include <glib/gstdio.h>
48 #include <glib/gi18n.h>
49
50 /* TODO in the future we could have support for other shells (change command strings), or not use a shell at all */
51 #define BASH_LOCATION "/bin/bash"
52
53 /**
54  * List of supported protocols.
55  */
56 const gchar *PROTOS[] = { "http://", "https://", "ftp://", NULL };
57
58 /**
59  * Path to gpsbabel
60  */
61 static gchar *gpsbabel_loc = NULL;
62
63 /**
64  * Path to unbuffer
65  */
66 static gchar *unbuffer_loc = NULL;
67
68 /**
69  * List of file formats supported by gpsbabel.
70  */
71 GList *a_babel_file_list;
72
73 /**
74  * List of device supported by gpsbabel.
75  */
76 GList *a_babel_device_list;
77
78 /**
79  * Run a function on all file formats supporting a given mode.
80  */
81 void a_babel_foreach_file_with_mode (BabelMode mode, GFunc func, gpointer user_data)
82 {
83   GList *current;
84   for ( current = g_list_first (a_babel_file_list) ;
85         current != NULL ;
86         current = g_list_next (current) )
87   {
88     BabelFile *currentFile = current->data;
89     /* Check compatibility of modes */
90     gboolean compat = TRUE;
91     if (mode.waypointsRead  && ! currentFile->mode.waypointsRead)  compat = FALSE;
92     if (mode.waypointsWrite && ! currentFile->mode.waypointsWrite) compat = FALSE;
93     if (mode.tracksRead     && ! currentFile->mode.tracksRead)     compat = FALSE;
94     if (mode.tracksWrite    && ! currentFile->mode.tracksWrite)    compat = FALSE;
95     if (mode.routesRead     && ! currentFile->mode.routesRead)     compat = FALSE;
96     if (mode.routesWrite    && ! currentFile->mode.routesWrite)    compat = FALSE;
97     /* Do call */
98     if (compat)
99       func (currentFile, user_data);
100   }
101 }
102
103 /**
104  * a_babel_foreach_file_read_any:
105  * @func:      The function to be called on any file format with a read method
106  * @user_data: Data passed into the function
107  *
108  * Run a function on all file formats with any kind of read method
109  *  (which is almost all but not quite - e.g. with GPSBabel v1.4.4 - PalmDoc is write only waypoints)
110  */
111 void a_babel_foreach_file_read_any (GFunc func, gpointer user_data)
112 {
113   GList *current;
114   for ( current = g_list_first (a_babel_file_list) ;
115         current != NULL ;
116         current = g_list_next (current) )
117   {
118     BabelFile *currentFile = current->data;
119     // Call function when any read mode found
120     if ( currentFile->mode.waypointsRead ||
121          currentFile->mode.tracksRead ||
122          currentFile->mode.routesRead)
123       func (currentFile, user_data);
124   }
125 }
126
127 /**
128  * a_babel_convert:
129  * @vt:        The TRW layer to modify. All data will be deleted, and replaced by what gpsbabel outputs.
130  * @babelargs: A string containing gpsbabel command line filter options. No file types or names should
131  *             be specified.
132  * @cb:        A callback function.
133  * @user_data: passed along to cb
134  * @not_used:  Must use NULL
135  *
136  * This function modifies data in a trw layer using gpsbabel filters.  This routine is synchronous;
137  * that is, it will block the calling program until the conversion is done. To avoid blocking, call
138  * this routine from a worker thread.
139  *
140  * Returns: %TRUE on success
141  */
142 gboolean a_babel_convert( VikTrwLayer *vt, const char *babelargs, BabelStatusFunc cb, gpointer user_data, gpointer not_used )
143 {
144   gboolean ret = FALSE;
145   gchar *bargs = g_strconcat(babelargs, " -i gpx", NULL);
146   gchar *name_src = a_gpx_write_tmp_file ( vt, NULL );
147
148   if ( name_src ) {
149     ret = a_babel_convert_from ( vt, bargs, name_src, cb, user_data, not_used );
150     g_remove(name_src);
151     g_free(name_src);
152   }
153
154   g_free(bargs);
155   return ret;
156 }
157
158 /**
159  * Perform any cleanup actions once GPSBabel has completed running
160  */
161 static void babel_watch ( GPid pid,
162                           gint status,
163                           gpointer user_data )
164 {
165   g_spawn_close_pid ( pid );
166 }
167
168 /**
169  * babel_general_convert:
170  * @args: The command line arguments passed to GPSBabel
171  * @cb: callback that is run for each line of GPSBabel output and at completion of the run
172  *      callback may be NULL
173  * @user_data: passed along to cb
174  *
175  * The function to actually invoke the GPSBabel external command
176  *
177  * Returns: %TRUE on successful invocation of GPSBabel command
178  */
179 static gboolean babel_general_convert( BabelStatusFunc cb, gchar **args, gpointer user_data )
180 {
181   gboolean ret = FALSE;
182   GPid pid;
183   GError *error = NULL;
184   gint babel_stdout;
185
186   if (!g_spawn_async_with_pipes (NULL, args, NULL, G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL, &pid, NULL, &babel_stdout, NULL, &error)) {
187     g_warning ("Async command failed: %s", error->message);
188     g_error_free(error);
189     ret = FALSE;
190   } else {
191
192     gchar line[512];
193     FILE *diag;
194     diag = fdopen(babel_stdout, "r");
195     setvbuf(diag, NULL, _IONBF, 0);
196
197     while (fgets(line, sizeof(line), diag)) {
198       if ( cb )
199         cb(BABEL_DIAG_OUTPUT, line, user_data);
200     }
201     if ( cb )
202       cb(BABEL_DONE, NULL, user_data);
203     fclose(diag);
204     diag = NULL;
205
206     g_child_watch_add ( pid, (GChildWatchFunc) babel_watch, NULL );
207
208     ret = TRUE;
209   }
210     
211   return ret;
212 }
213
214 /**
215  * babel_general_convert_from:
216  * @vtl: The TrackWaypoint Layer to save the data into
217  *   If it is null it signifies that no data is to be processed,
218  *    however the gpsbabel command is still ran as it can be for non-data related options eg:
219  *    for use with the power off command - 'command_off'
220  * @cb: callback that is run upon new data from STDOUT (?)
221  *     (TODO: STDERR would be nice since we usually redirect STDOUT)
222  * @user_data: passed along to cb
223  *
224  * Runs args[0] with the arguments and uses the GPX module
225  * to import the GPX data into layer vt. Assumes that upon
226  * running the command, the data will appear in the (usually
227  * temporary) file name_dst.
228  *
229  * Returns: %TRUE on success
230  */
231 static gboolean babel_general_convert_from( VikTrwLayer *vt, BabelStatusFunc cb, gchar **args, const gchar *name_dst, gpointer user_data )
232 {
233   gboolean ret = FALSE;
234   FILE *f = NULL;
235     
236   if (babel_general_convert(cb, args, user_data)) {
237
238     /* No data actually required but still need to have run gpsbabel anyway
239        - eg using the device power command_off */
240     if ( vt == NULL )
241       return TRUE;
242
243     f = g_fopen(name_dst, "r");
244     if (f) {
245       ret = a_gpx_read_file ( vt, f );
246       fclose(f);
247       f = NULL;
248     }
249   }
250     
251   return ret;
252 }
253
254 /**
255  * a_babel_convert_from_filter:
256  * @vt:           The TRW layer to place data into. Duplicate items will be overwritten.
257  * @babelargs:    A string containing gpsbabel command line options. This string
258  *                must include the input file type (-i) option.
259  * @from          the file name to convert from
260  * @babelfilters: A string containing gpsbabel filter command line options 
261  * @cb:           Optional callback function. Same usage as in a_babel_convert().
262  * @user_data:    passed along to cb
263  * @not_used:     Must use NULL
264  *
265  * Loads data into a trw layer from a file, using gpsbabel.  This routine is synchronous;
266  * that is, it will block the calling program until the conversion is done. To avoid blocking, call
267  * this routine from a worker thread.
268  *
269  * Returns: %TRUE on success
270  */
271 gboolean a_babel_convert_from_filter( VikTrwLayer *vt, const char *babelargs, const char *from, const char *babelfilters, BabelStatusFunc cb, gpointer user_data, gpointer not_used )
272 {
273   int i,j;
274   int fd_dst;
275   gchar *name_dst = NULL;
276   gboolean ret = FALSE;
277   gchar *args[64];
278
279   if ((fd_dst = g_file_open_tmp("tmp-viking.XXXXXX", &name_dst, NULL)) >= 0) {
280     g_debug ("%s: temporary file: %s", __FUNCTION__, name_dst);
281     close(fd_dst);
282
283     if (gpsbabel_loc ) {
284       gchar **sub_args = g_strsplit(babelargs, " ", 0);
285       gchar **sub_filters = NULL;
286
287       i = 0;
288       if (unbuffer_loc)
289         args[i++] = unbuffer_loc;
290       args[i++] = gpsbabel_loc;
291       for (j = 0; sub_args[j]; j++) {
292         /* some version of gpsbabel can not take extra blank arg */
293         if (sub_args[j][0] != '\0')
294           args[i++] = sub_args[j];
295       }
296       args[i++] = "-f";
297       args[i++] = (char *)from;
298       if (babelfilters) {
299         sub_filters = g_strsplit(babelfilters, " ", 0);
300         for (j = 0; sub_filters[j]; j++) {
301           /* some version of gpsbabel can not take extra blank arg */
302           if (sub_filters[j][0] != '\0')
303             args[i++] = sub_filters[j];
304         }
305       }
306       args[i++] = "-o";
307       args[i++] = "gpx";
308       args[i++] = "-F";
309       args[i++] = name_dst;
310       args[i] = NULL;
311
312       ret = babel_general_convert_from ( vt, cb, args, name_dst, user_data );
313
314       g_strfreev(sub_args);
315       if (sub_filters)
316           g_strfreev(sub_filters);
317     } else
318       g_critical("gpsbabel not found in PATH");
319     g_remove(name_dst);
320     g_free(name_dst);
321   }
322
323   return ret;
324 }
325
326 /**
327  * a_babel_convert_from:
328  * @vt:        The TRW layer to place data into. Duplicate items will be overwritten.
329  * @babelargs: A string containing gpsbabel command line options.  This string
330  *             must include the input file type (-i) option.
331  * @from:      The file name to convert from
332  * @cb:        Optional callback function. Same usage as in a_babel_convert().
333  * @user_data: passed along to cb
334  * @not_used:  Must use NULL
335  *
336  * Loads data into a trw layer from a file, using gpsbabel.  This routine is synchronous;
337  * that is, it will block the calling program until the conversion is done. To avoid blocking, call
338  * this routine from a worker thread.
339  *
340  * Returns: %TRUE on success
341  */
342 gboolean a_babel_convert_from( VikTrwLayer *vt, const char *babelargs, const char *from, BabelStatusFunc cb, gpointer user_data, gpointer not_used )
343 {
344   return a_babel_convert_from_filter ( vt, babelargs, from, NULL, cb, user_data, not_used ); 
345 }
346 /**
347  * a_babel_convert_from_shellcommand:
348  * @vt: The #VikTrwLayer where to insert the collected data
349  * @input_cmd: the command to run
350  * @cb:        Optional callback function. Same usage as in a_babel_convert().
351  * @user_data: passed along to cb
352  * @not_used:  Must use NULL
353  *
354  * Runs the input command in a shell (bash) and optionally uses GPSBabel to convert from input_file_type.
355  * If input_file_type is %NULL, doesn't use GPSBabel. Input must be GPX (or Geocaching *.loc)
356  *
357  * Uses babel_general_convert_from() to actually run the command. This function
358  * prepares the command and temporary file, and sets up the arguments for bash.
359  */
360 gboolean a_babel_convert_from_shellcommand ( VikTrwLayer *vt, const char *input_cmd, const char *input_file_type, BabelStatusFunc cb, gpointer user_data, gpointer not_used )
361 {
362   int fd_dst;
363   gchar *name_dst = NULL;
364   gboolean ret = FALSE;
365   gchar **args;  
366
367   if ((fd_dst = g_file_open_tmp("tmp-viking.XXXXXX", &name_dst, NULL)) >= 0) {
368     g_debug ("%s: temporary file: %s", __FUNCTION__, name_dst);
369     gchar *shell_command;
370     if ( input_file_type )
371       shell_command = g_strdup_printf("%s | %s -i %s -f - -o gpx -F %s",
372         input_cmd, gpsbabel_loc, input_file_type, name_dst);
373     else
374       shell_command = g_strdup_printf("%s > %s", input_cmd, name_dst);
375
376     g_debug("%s: %s", __FUNCTION__, shell_command);
377     close(fd_dst);
378
379     args = g_malloc(sizeof(gchar *)*4);
380     args[0] = BASH_LOCATION;
381     args[1] = "-c";
382     args[2] = shell_command;
383     args[3] = NULL;
384
385     ret = babel_general_convert_from ( vt, cb, args, name_dst, user_data );
386     g_free ( args );
387     g_free ( shell_command );
388     g_remove(name_dst);
389     g_free(name_dst);
390   }
391
392   return ret;
393 }
394
395 /**
396  * a_babel_convert_from_url:
397  * @vt: The #VikTrwLayer where to insert the collected data
398  * @url: the URL to fetch
399  * @babelfilters: the filter arguments to pass to gpsbabel
400  * @cb:        Optional callback function. Same usage as in a_babel_convert().
401  * @user_data: passed along to cb
402  * @options:   download options. Maybe NULL.
403  *
404  * Download the file pointed by the URL and optionally uses GPSBabel to convert from input_file_type.
405  * If input_file_type is %NULL, input must be GPX.
406  * If input_file_type and babelfilters are %NULL, gpsbabel is not used.
407  *
408  * Returns: %TRUE on successful invocation of GPSBabel or read of the GPX
409  *
410  */
411 gboolean a_babel_convert_from_url_filter ( VikTrwLayer *vt, const char *url, const char *input_type, const char *babelfilters, BabelStatusFunc cb, gpointer user_data, DownloadMapOptions *options )
412 {
413   // If no download options specified, use defaults:
414   DownloadMapOptions myoptions = { FALSE, FALSE, NULL, 2, NULL, NULL, NULL };
415   if ( options )
416     myoptions = *options;
417   gint fd_src;
418   int fetch_ret;
419   gboolean ret = FALSE;
420   gchar *name_src = NULL;
421   gchar *babelargs = NULL;
422
423   g_debug("%s: input_type=%s url=%s", __FUNCTION__, input_type, url);
424
425   if ((fd_src = g_file_open_tmp("tmp-viking.XXXXXX", &name_src, NULL)) >= 0) {
426     g_debug ("%s: temporary file: %s", __FUNCTION__, name_src);
427     close(fd_src);
428     g_remove(name_src);
429
430     fetch_ret = a_http_download_get_url(url, "", name_src, &myoptions, NULL);
431     if (fetch_ret == DOWNLOAD_SUCCESS) {
432       if (input_type != NULL || babelfilters != NULL) {
433         babelargs = (input_type) ? g_strdup_printf(" -i %s", input_type) : g_strdup("");
434         ret = a_babel_convert_from_filter( vt, babelargs, name_src, babelfilters, NULL, NULL, NULL );
435       } else {
436         /* Process directly the retrieved file */
437         g_debug("%s: directly read GPX file %s", __FUNCTION__, name_src);
438         FILE *f = g_fopen(name_src, "r");
439         if (f) {
440           ret = a_gpx_read_file ( vt, f );
441           fclose(f);
442           f = NULL;
443         }
444       }
445     }
446     util_remove(name_src);
447     g_free(babelargs);
448     g_free(name_src);
449   }
450
451   return ret;
452 }
453
454 /**
455  * a_babel_convert_from_url:
456  * @vt: The #VikTrwLayer where to insert the collected data
457  * @url: the URL to fetch
458  * @cb:        Optional callback function. Same usage as in a_babel_convert().
459  * @user_data: passed along to cb
460  * @options:   download options. Maybe NULL.
461  *
462  * Download the file pointed by the URL and optionally uses GPSBabel to convert from input_file_type.
463  * If input_file_type is %NULL, doesn't use GPSBabel. Input must be GPX.
464  *
465  * Returns: %TRUE on successful invocation of GPSBabel or read of the GPX
466  *
467  */
468 gboolean a_babel_convert_from_url ( VikTrwLayer *vt, const char *url, const char *input_type, BabelStatusFunc cb, gpointer user_data, DownloadMapOptions *options )
469 {
470   return a_babel_convert_from_url_filter ( vt, url, input_type, NULL, cb, user_data, options );
471 }
472
473 /**
474  * a_babel_convert_from_url_or_shell:
475  * @vt: The #VikTrwLayer where to insert the collected data
476  * @url: the URL to fetch
477  * @cb:        Optional callback function. Same usage as in a_babel_convert().
478  * @user_data: passed along to cb
479  * @options:   download options. Maybe NULL.
480  *
481  * Download the file pointed by the URL and optionally uses GPSBabel to convert from input_file_type.
482  * If input_file_type is %NULL, doesn't use GPSBabel. Input must be GPX.
483  *
484  * Returns: %TRUE on successful invocation of GPSBabel or read of the GPX
485  *
486  */
487 gboolean a_babel_convert_from_url_or_shell ( VikTrwLayer *vt, const char *input, const char *input_type, BabelStatusFunc cb, gpointer user_data, DownloadMapOptions *options )
488 {
489   
490   /* Check nature of input */
491   gboolean isUrl = FALSE;
492   int i = 0;
493   for (i = 0 ; PROTOS[i] != NULL ; i++)
494   {
495     const gchar *proto = PROTOS[i];
496     if (strncmp (input, proto, strlen(proto)) == 0)
497     {
498       /* Procotol matches: save result */
499       isUrl = TRUE;
500     }
501   }
502   
503   /* Do the job */
504   if (isUrl)
505     return a_babel_convert_from_url (vt, input, input_type, cb, user_data, options);
506   else
507     return a_babel_convert_from_shellcommand (vt, input, input_type, cb, user_data, options);
508 }
509
510 static gboolean babel_general_convert_to( VikTrwLayer *vt, VikTrack *trk, BabelStatusFunc cb, gchar **args, const gchar *name_src, gpointer user_data )
511 {
512   // Now strips out invisible tracks and waypoints
513   if (!a_file_export(vt, name_src, FILE_TYPE_GPX, trk, FALSE)) {
514     g_critical("Error exporting to %s", name_src);
515     return FALSE;
516   }
517        
518   return babel_general_convert (cb, args, user_data);
519 }
520
521 /**
522  * a_babel_convert_to:
523  * @vt:             The TRW layer from which data is taken.
524  * @track:          Operate on the individual track if specified. Use NULL when operating on a TRW layer
525  * @babelargs:      A string containing gpsbabel command line options.  In addition to any filters, this string
526  *                 must include the input file type (-i) option.
527  * @to:             Filename or device the data is written to.
528  * @cb:            Optional callback function. Same usage as in a_babel_convert.
529  * @user_data: passed along to cb
530  *
531  * Exports data using gpsbabel.  This routine is synchronous;
532  * that is, it will block the calling program until the conversion is done. To avoid blocking, call
533  * this routine from a worker thread.
534  *
535  * Returns: %TRUE on successful invocation of GPSBabel command
536  */
537 gboolean a_babel_convert_to( VikTrwLayer *vt, VikTrack *track, const char *babelargs, const char *to, BabelStatusFunc cb, gpointer user_data )
538 {
539   int i,j;
540   int fd_src;
541   gchar *name_src = NULL;
542   gboolean ret = FALSE;
543   gchar *args[64];  
544
545   if ((fd_src = g_file_open_tmp("tmp-viking.XXXXXX", &name_src, NULL)) >= 0) {
546     g_debug ("%s: temporary file: %s", __FUNCTION__, name_src);
547     close(fd_src);
548
549     if (gpsbabel_loc ) {
550       gchar **sub_args = g_strsplit(babelargs, " ", 0);
551
552       i = 0;
553       if (unbuffer_loc)
554         args[i++] = unbuffer_loc;
555       args[i++] = gpsbabel_loc;
556       args[i++] = "-i";
557       args[i++] = "gpx";
558       for (j = 0; sub_args[j]; j++)
559         /* some version of gpsbabel can not take extra blank arg */
560         if (sub_args[j][0] != '\0')
561           args[i++] = sub_args[j];
562       args[i++] = "-f";
563       args[i++] = name_src;
564       args[i++] = "-F";
565       args[i++] = (char *)to;
566       args[i] = NULL;
567
568       ret = babel_general_convert_to ( vt, track, cb, args, name_src, user_data );
569
570       g_strfreev(sub_args);
571     } else
572       g_critical("gpsbabel not found in PATH");
573     g_remove(name_src);
574     g_free(name_src);
575   }
576
577   return ret;
578 }
579
580 static void set_mode(BabelMode *mode, gchar *smode)
581 {
582   mode->waypointsRead  = smode[0] == 'r';
583   mode->waypointsWrite = smode[1] == 'w';
584   mode->tracksRead     = smode[2] == 'r';
585   mode->tracksWrite    = smode[3] == 'w';
586   mode->routesRead     = smode[4] == 'r';
587   mode->routesWrite    = smode[5] == 'w';
588 }
589
590 /**
591  * load_feature_parse_line:
592  * 
593  * Load a single feature stored in the given line.
594  */
595 static void load_feature_parse_line (gchar *line)
596 {
597   gchar **tokens = g_strsplit ( line, "\t", 0 );
598   if ( tokens != NULL
599        && tokens[0] != NULL ) {
600     if ( strcmp("serial", tokens[0]) == 0 ) {
601       if ( tokens[1] != NULL
602            && tokens[2] != NULL
603            && tokens[3] != NULL
604            && tokens[4] != NULL ) {
605         BabelDevice *device = g_malloc ( sizeof (BabelDevice) );
606         set_mode (&(device->mode), tokens[1]);
607         device->name = g_strdup (tokens[2]);
608         device->label = g_strndup (tokens[4], 50); // Limit really long label text
609         a_babel_device_list = g_list_append (a_babel_device_list, device);
610         g_debug ("New gpsbabel device: %s, %d%d%d%d%d%d(%s)",
611                         device->name,
612                         device->mode.waypointsRead, device->mode.waypointsWrite,
613                         device->mode.tracksRead, device->mode.tracksWrite,
614                         device->mode.routesRead, device->mode.routesWrite,
615                                 tokens[1]);
616       } else {
617         g_warning ( "Unexpected gpsbabel format string: %s", line);
618       }
619     } else if ( strcmp("file", tokens[0]) == 0 ) {
620       if ( tokens[1] != NULL
621            && tokens[2] != NULL
622            && tokens[3] != NULL
623            && tokens[4] != NULL ) {
624         BabelFile *file = g_malloc ( sizeof (BabelFile) );
625         set_mode (&(file->mode), tokens[1]);
626         file->name = g_strdup (tokens[2]);
627         file->ext = g_strdup (tokens[3]);
628         file->label = g_strdup (tokens[4]);
629         a_babel_file_list = g_list_append (a_babel_file_list, file);
630         g_debug ("New gpsbabel file: %s, %d%d%d%d%d%d(%s)",
631                         file->name,
632                         file->mode.waypointsRead, file->mode.waypointsWrite,
633                         file->mode.tracksRead, file->mode.tracksWrite,
634                         file->mode.routesRead, file->mode.routesWrite,
635                         tokens[1]);
636       } else {
637         g_warning ( "Unexpected gpsbabel format string: %s", line);
638       }
639     } /* else: ignore */
640   } else {
641     g_warning ( "Unexpected gpsbabel format string: %s", line);
642   }
643   g_strfreev ( tokens );
644 }
645
646 static void load_feature_cb (BabelProgressCode code, gpointer line, gpointer user_data)
647 {
648   if (line != NULL)
649     load_feature_parse_line (line);
650 }
651
652 static gboolean load_feature ()
653 {
654   int i;
655   gboolean ret = FALSE;
656   gchar *args[4];  
657
658   if ( gpsbabel_loc ) {
659     i = 0;
660     if ( unbuffer_loc )
661       args[i++] = unbuffer_loc;
662     args[i++] = gpsbabel_loc;
663     args[i++] = "-^3";
664     args[i] = NULL;
665
666     ret = babel_general_convert (load_feature_cb, args, NULL);
667   } else
668     g_critical("gpsbabel not found in PATH");
669
670   return ret;
671 }
672
673 static VikLayerParam prefs[] = {
674   { VIK_LAYER_NUM_TYPES, VIKING_PREFERENCES_IO_NAMESPACE "gpsbabel", VIK_LAYER_PARAM_STRING, VIK_LAYER_GROUP_NONE, N_("GPSBabel:"), VIK_LAYER_WIDGET_FILEENTRY, NULL, NULL,
675       N_("Allow setting the specific instance of GPSBabel. You must restart Viking for this value to take effect."), NULL, NULL, NULL },
676 };
677
678 /**
679  * a_babel_init:
680  * 
681  * Initialises babel module.
682  * Mainly check existence of gpsbabel progam
683  * and load all features available in that version.
684  */
685 void a_babel_init ()
686 {
687   // Set the defaults
688   VikLayerParamData vlpd;
689 #ifdef WINDOWS
690   // Basic guesses - could use %ProgramFiles% but this is simpler:
691   if ( g_file_test ( "C:\\Program Files (x86)\\GPSBabel\\gpsbabel.exe", G_FILE_TEST_EXISTS ) )
692     // 32 bit location on a 64 bit system
693     vlpd.s = "C:\\Program Files (x86)\\GPSBabel\gpsbabel.exe";
694   else
695     vlpd.s = "C:\\Program Files\\GPSBabel\\gpsbabel.exe";
696 #else
697   vlpd.s = "gpsbabel";
698 #endif
699   a_preferences_register(&prefs[0], vlpd, VIKING_PREFERENCES_IO_GROUP_KEY);
700
701   // Read the current preference
702   const gchar *gpsbabel = a_preferences_get(VIKING_PREFERENCES_IO_NAMESPACE "gpsbabel")->s;
703   // If setting is still the UNIX default then lookup in the path - otherwise attempt to use the specified value directly.
704   if ( g_strcmp0 ( gpsbabel, "gpsbabel" ) == 0 ) {
705     gpsbabel_loc = g_find_program_in_path( "gpsbabel" );
706     if ( !gpsbabel_loc )
707       g_critical( "gpsbabel not found in PATH" );
708   }
709   else
710     gpsbabel_loc = (gchar*)gpsbabel;
711
712   // Unlikely to package unbuffer on Windows so ATM don't even bother trying
713   // Highly unlikely unbuffer is available on a Windows system otherwise
714 #ifndef WINDOWS
715   unbuffer_loc = g_find_program_in_path( "unbuffer" );
716   if ( !unbuffer_loc )
717     g_warning( "unbuffer not found in PATH" );
718 #endif
719
720   load_feature ();
721 }
722
723 /**
724  * a_babel_uninit:
725  * 
726  * Free resources acquired by a_babel_init.
727  */
728 void a_babel_uninit ()
729 {
730   g_free ( gpsbabel_loc );
731   g_free ( unbuffer_loc );
732
733   if ( a_babel_file_list ) {
734     GList *gl;
735     for (gl = a_babel_file_list; gl != NULL; gl = g_list_next(gl)) {
736       BabelFile *file = gl->data;
737       g_free ( file->name );
738       g_free ( file->ext );
739       g_free ( file->label );
740       g_free ( gl->data );
741     }
742     g_list_free ( a_babel_file_list );
743   }
744
745   if ( a_babel_device_list ) {
746     GList *gl;
747     for (gl = a_babel_device_list; gl != NULL; gl = g_list_next(gl)) {
748       BabelDevice *device = gl->data;
749       g_free ( device->name );
750       g_free ( device->label );
751       g_free ( gl->data );
752     }
753     g_list_free ( a_babel_device_list );
754   }
755
756 }
757
758 /**
759  * a_babel_available:
760  *
761  * Indicates if babel is available or not.
762  *
763  * Returns: true if babel available
764  */
765 gboolean a_babel_available ()
766 {
767   return a_babel_device_list != NULL;
768 }