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