]> git.street.me.uk Git - andy/viking.git/blob - src/babel.c
[QA] Remove unneeded include statement.
[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  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  */
22
23 /**
24  * SECTION:babel
25  * @short_description: running external programs and redirecting to TRWLayers.
26  *
27  * GPSBabel may not be necessary for everything -- for instance,
28  *   use a_babel_convert_from_shellcommand() with input_file_type == %NULL
29  *   for an external program that outputs GPX.
30  */
31
32 #ifdef HAVE_CONFIG_H
33 #include "config.h"
34 #endif
35
36 #include "viking.h"
37 #include "gpx.h"
38 #include "babel.h"
39 #include <stdio.h>
40 #ifdef HAVE_SYS_WAIT_H
41 #include <sys/wait.h>
42 #endif
43 #ifdef HAVE_UNISTD_H
44 #include <unistd.h>
45 #endif
46 #include <string.h>
47 #include <glib.h>
48 #include <glib/gstdio.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  * a_babel_convert:
75  * @vt:        The TRW layer to modify. All data will be deleted, and replaced by what gpsbabel outputs.
76  * @babelargs: A string containing gpsbabel command line filter options. No file types or names should
77  *             be specified.
78  * @cb:        A callback function.
79  *
80  * This function modifies data in a trw layer using gpsbabel filters.  This routine is synchronous;
81  * that is, it will block the calling program until the conversion is done. To avoid blocking, call
82  * this routine from a worker thread.
83  *
84  * Returns: %TRUE on success
85  */
86 gboolean a_babel_convert( VikTrwLayer *vt, const char *babelargs, BabelStatusFunc cb, gpointer user_data )
87 {
88   int fd_src;
89   FILE *f;
90   gchar *name_src = NULL;
91   gboolean ret = FALSE;
92   gchar *bargs = g_strconcat(babelargs, " -i gpx", NULL);
93
94   if ((fd_src = g_file_open_tmp("tmp-viking.XXXXXX", &name_src, NULL)) >= 0) {
95     g_debug ("%s: temporary file: %s", __FUNCTION__, name_src);
96     f = fdopen(fd_src, "w");
97     a_gpx_write_file(vt, f, NULL);
98     fclose(f);
99     f = NULL;
100     ret = a_babel_convert_from ( vt, bargs, name_src, cb, user_data );
101     g_remove(name_src);
102     g_free(name_src);
103   }
104
105   g_free(bargs);
106   return ret;
107 }
108
109 /**
110  * Perform any cleanup actions once GPSBabel has completed running
111  */
112 static void babel_watch ( GPid pid,
113                           gint status,
114                           gpointer user_data )
115 {
116   g_spawn_close_pid ( pid );
117 }
118
119 /**
120  * babel_general_convert:
121  * @args: The command line arguments passed to GPSBabel
122  * @cb: callback that is run for each line of GPSBabel output and at completion of the run
123  *      callback may be NULL
124  * @user_data: passed along to cb
125  *
126  * The function to actually invoke the GPSBabel external command
127  *
128  * Returns: %TRUE on successful invocation of GPSBabel command
129  */
130 static gboolean babel_general_convert( BabelStatusFunc cb, gchar **args, gpointer user_data )
131 {
132   gboolean ret = FALSE;
133   GPid pid;
134   GError *error = NULL;
135   gint babel_stdout;
136
137   if (!g_spawn_async_with_pipes (NULL, args, NULL, G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL, &pid, NULL, &babel_stdout, NULL, &error)) {
138     g_error("Async command failed: %s", error->message);
139     g_error_free(error);
140     ret = FALSE;
141   } else {
142
143     gchar line[512];
144     FILE *diag;
145     diag = fdopen(babel_stdout, "r");
146     setvbuf(diag, NULL, _IONBF, 0);
147
148     while (fgets(line, sizeof(line), diag)) {
149       if ( cb )
150         cb(BABEL_DIAG_OUTPUT, line, user_data);
151     }
152     if ( cb )
153       cb(BABEL_DONE, NULL, user_data);
154     fclose(diag);
155     diag = NULL;
156
157     g_child_watch_add ( pid, (GChildWatchFunc) babel_watch, NULL );
158
159     ret = TRUE;
160   }
161     
162   return ret;
163 }
164
165 /**
166  * babel_general_convert_from:
167  * @vtl: The TrackWaypoint Layer to save the data into
168  *   If it is null it signifies that no data is to be processed,
169  *    however the gpsbabel command is still ran as it can be for non-data related options eg:
170  *    for use with the power off command - 'command_off'
171  * @cb: callback that is run upon new data from STDOUT (?)
172  *     (TODO: STDERR would be nice since we usually redirect STDOUT)
173  * @user_data: passed along to cb
174  *
175  * Runs args[0] with the arguments and uses the GPX module
176  * to import the GPX data into layer vt. Assumes that upon
177  * running the command, the data will appear in the (usually
178  * temporary) file name_dst.
179  *
180  * Returns: %TRUE on success
181  */
182 static gboolean babel_general_convert_from( VikTrwLayer *vt, BabelStatusFunc cb, gchar **args, const gchar *name_dst, gpointer user_data )
183 {
184   gboolean ret = FALSE;
185   FILE *f = NULL;
186     
187   if (babel_general_convert(cb, args, user_data)) {
188
189     /* No data actually required but still need to have run gpsbabel anyway
190        - eg using the device power command_off */
191     if ( vt == NULL )
192       return TRUE;
193
194     f = g_fopen(name_dst, "r");
195     if (f) {
196       ret = a_gpx_read_file ( vt, f );
197       fclose(f);
198       f = NULL;
199     }
200   }
201     
202   return ret;
203 }
204
205 /**
206  * a_babel_convert_from:
207  * @vt:        The TRW layer to place data into. Duplicate items will be overwritten.
208  * @babelargs: A string containing gpsbabel command line options. In addition to any filters, this string
209  *             must include the input file type (-i) option.
210  * @cb:        Optional callback function. Same usage as in a_babel_convert().
211  * @user_data: passed along to cb
212  *
213  * Loads data into a trw layer from a file, using gpsbabel.  This routine is synchronous;
214  * that is, it will block the calling program until the conversion is done. To avoid blocking, call
215  * this routine from a worker thread.
216  *
217  * Returns: %TRUE on success
218  */
219 gboolean a_babel_convert_from( VikTrwLayer *vt, const char *babelargs, const char *from, BabelStatusFunc cb, gpointer user_data )
220 {
221   int i,j;
222   int fd_dst;
223   gchar *name_dst = NULL;
224   gboolean ret = FALSE;
225   gchar *args[64];
226
227   if ((fd_dst = g_file_open_tmp("tmp-viking.XXXXXX", &name_dst, NULL)) >= 0) {
228     g_debug ("%s: temporary file: %s", __FUNCTION__, name_dst);
229     close(fd_dst);
230
231     if (gpsbabel_loc ) {
232       gchar **sub_args = g_strsplit(babelargs, " ", 0);
233
234       i = 0;
235       if (unbuffer_loc)
236         args[i++] = unbuffer_loc;
237       args[i++] = gpsbabel_loc;
238       for (j = 0; sub_args[j]; j++) {
239         /* some version of gpsbabel can not take extra blank arg */
240         if (sub_args[j][0] != '\0')
241           args[i++] = sub_args[j];
242       }
243       args[i++] = "-o";
244       args[i++] = "gpx";
245       args[i++] = "-f";
246       args[i++] = (char *)from;
247       args[i++] = "-F";
248       args[i++] = name_dst;
249       args[i] = NULL;
250
251       ret = babel_general_convert_from ( vt, cb, args, name_dst, user_data );
252
253       g_strfreev(sub_args);
254     } else
255       g_critical("gpsbabel not found in PATH");
256     g_remove(name_dst);
257     g_free(name_dst);
258   }
259
260   return ret;
261 }
262
263 /**
264  * a_babel_convert_from_shellcommand:
265  * @vt: The #VikTrwLayer where to insert the collected data
266  * @input_cmd: the command to run
267  * @cb:        Optional callback function. Same usage as in a_babel_convert().
268  * @user_data: passed along to cb
269  *
270  * Runs the input command in a shell (bash) and optionally uses GPSBabel to convert from input_file_type.
271  * If input_file_type is %NULL, doesn't use GPSBabel. Input must be GPX (or Geocaching *.loc)
272  *
273  * Uses babel_general_convert_from() to actually run the command. This function
274  * prepares the command and temporary file, and sets up the arguments for bash.
275  */
276 gboolean a_babel_convert_from_shellcommand ( VikTrwLayer *vt, const char *input_cmd, const char *input_file_type, BabelStatusFunc cb, gpointer user_data )
277 {
278   int fd_dst;
279   gchar *name_dst = NULL;
280   gboolean ret = FALSE;
281   gchar **args;  
282
283   if ((fd_dst = g_file_open_tmp("tmp-viking.XXXXXX", &name_dst, NULL)) >= 0) {
284     g_debug ("%s: temporary file: %s", __FUNCTION__, name_dst);
285     gchar *shell_command;
286     if ( input_file_type )
287       shell_command = g_strdup_printf("%s | %s -i %s -f - -o gpx -F %s",
288         input_cmd, gpsbabel_loc, input_file_type, name_dst);
289     else
290       shell_command = g_strdup_printf("%s > %s", input_cmd, name_dst);
291
292     g_debug("%s: %s", __FUNCTION__, shell_command);
293     close(fd_dst);
294
295     args = g_malloc(sizeof(gchar *)*4);
296     args[0] = BASH_LOCATION;
297     args[1] = "-c";
298     args[2] = shell_command;
299     args[3] = NULL;
300
301     ret = babel_general_convert_from ( vt, cb, args, name_dst, user_data );
302     g_free ( args );
303     g_free ( shell_command );
304     g_remove(name_dst);
305     g_free(name_dst);
306   }
307
308   return ret;
309 }
310
311 /**
312  * a_babel_convert_from_url:
313  * @vt: The #VikTrwLayer where to insert the collected data
314  * @url: the URL to fetch
315  * @cb:        Optional callback function. Same usage as in a_babel_convert().
316  * @user_data: passed along to cb
317  *
318  * Download the file pointed by the URL and optionally uses GPSBabel to convert from input_file_type.
319  * If input_file_type is %NULL, doesn't use GPSBabel. Input must be GPX.
320  */
321 gboolean a_babel_convert_from_url ( VikTrwLayer *vt, const char *url, const char *input_type, BabelStatusFunc cb, gpointer user_data )
322 {
323   static DownloadMapOptions options = { FALSE, FALSE, NULL, 0, NULL};
324   gint fd_src;
325   int fetch_ret;
326   gboolean ret = FALSE;
327   gchar *name_src = NULL;
328   gchar *babelargs = NULL;
329
330   g_debug("%s: input_type=%s url=%s", __FUNCTION__, input_type, url);
331
332   if ((fd_src = g_file_open_tmp("tmp-viking.XXXXXX", &name_src, NULL)) >= 0) {
333     g_debug ("%s: temporary file: %s", __FUNCTION__, name_src);
334     close(fd_src);
335     g_remove(name_src);
336
337     fetch_ret = a_http_download_get_url(url, "", name_src, &options, NULL);
338     if (fetch_ret == 0) {
339       if (input_type != NULL) {
340         babelargs = g_strdup_printf(" -i %s", input_type);
341         ret = a_babel_convert_from( vt, babelargs, name_src, NULL, NULL);
342       } else {
343         /* Process directly the retrieved file */
344         g_debug("%s: directly read GPX file %s", __FUNCTION__, name_src);
345         FILE *f = g_fopen(name_src, "r");
346         if (f) {
347           ret = a_gpx_read_file ( vt, f );
348           fclose(f);
349           f = NULL;
350         }
351       }
352     }
353     g_remove(name_src);
354     g_free(babelargs);
355     g_free(name_src);
356   }
357
358   return ret;
359 }
360
361 static gboolean babel_general_convert_to( VikTrwLayer *vt, VikTrack *trk, BabelStatusFunc cb, gchar **args, const gchar *name_src, gpointer user_data )
362 {
363   // Now strips out invisible tracks and waypoints
364   if (!a_file_export(vt, name_src, FILE_TYPE_GPX, trk, FALSE)) {
365     g_critical("Error exporting to %s", name_src);
366     return FALSE;
367   }
368        
369   return babel_general_convert (cb, args, user_data);
370 }
371
372 /**
373  * a_babel_convert_to:
374  * @vt:             The TRW layer from which data is taken.
375  * @track:          Operate on the individual track if specified. Use NULL when operating on a TRW layer
376  * @babelargs:      A string containing gpsbabel command line options.  In addition to any filters, this string
377  *                 must include the input file type (-i) option.
378  * @to:             Filename or device the data is written to.
379  * @cb:            Optional callback function. Same usage as in a_babel_convert.
380  * @user_data: passed along to cb
381  *
382  * Exports data using gpsbabel.  This routine is synchronous;
383  * that is, it will block the calling program until the conversion is done. To avoid blocking, call
384  * this routine from a worker thread.
385  *
386  * Returns: %TRUE on successful invocation of GPSBabel command
387  */
388 gboolean a_babel_convert_to( VikTrwLayer *vt, VikTrack *track, const char *babelargs, const char *to, BabelStatusFunc cb, gpointer user_data )
389 {
390   int i,j;
391   int fd_src;
392   gchar *name_src = NULL;
393   gboolean ret = FALSE;
394   gchar *args[64];  
395
396   if ((fd_src = g_file_open_tmp("tmp-viking.XXXXXX", &name_src, NULL)) >= 0) {
397     g_debug ("%s: temporary file: %s", __FUNCTION__, name_src);
398     close(fd_src);
399
400     if (gpsbabel_loc ) {
401       gchar **sub_args = g_strsplit(babelargs, " ", 0);
402
403       i = 0;
404       if (unbuffer_loc)
405         args[i++] = unbuffer_loc;
406       args[i++] = gpsbabel_loc;
407       args[i++] = "-i";
408       args[i++] = "gpx";
409       for (j = 0; sub_args[j]; j++)
410         /* some version of gpsbabel can not take extra blank arg */
411         if (sub_args[j][0] != '\0')
412           args[i++] = sub_args[j];
413       args[i++] = "-f";
414       args[i++] = name_src;
415       args[i++] = "-F";
416       args[i++] = (char *)to;
417       args[i] = NULL;
418
419       ret = babel_general_convert_to ( vt, track, cb, args, name_src, user_data );
420
421       g_strfreev(sub_args);
422     } else
423       g_critical("gpsbabel not found in PATH");
424     g_remove(name_src);
425     g_free(name_src);
426   }
427
428   return ret;
429 }
430
431 static void set_mode(BabelMode mode, gchar *smode)
432 {
433   mode.waypointsRead  = smode[0] == 'r';
434   mode.waypointsWrite = smode[1] == 'w';
435   mode.tracksRead     = smode[2] == 'r';
436   mode.tracksWrite    = smode[3] == 'w';
437   mode.routesRead     = smode[4] == 'r';
438   mode.routesWrite    = smode[5] == 'w';
439 }
440
441 /**
442  * load_feature_parse_line:
443  * 
444  * Load a single feature stored in the given line.
445  */
446 static void load_feature_parse_line (gchar *line)
447 {
448   gchar **tokens = g_strsplit ( line, "\t", 0 );
449   if ( tokens != NULL
450        && tokens[0] != NULL ) {
451     if ( strcmp("serial", tokens[0]) == 0 ) {
452       if ( tokens[1] != NULL
453            && tokens[2] != NULL
454            && tokens[3] != NULL
455            && tokens[4] != NULL ) {
456         BabelDevice *device = g_malloc ( sizeof (BabelDevice) );
457         set_mode (device->mode, tokens[1]);
458         device->name = g_strdup (tokens[2]);
459         device->label = g_strndup (tokens[4], 50); // Limit really long label text
460         a_babel_device_list = g_list_append (a_babel_device_list, device);
461         g_debug ("New gpsbabel device: %s", device->name);
462       } else {
463         g_warning ( "Unexpected gpsbabel format string: %s", line);
464       }
465     } else if ( strcmp("file", tokens[0]) == 0 ) {
466       if ( tokens[1] != NULL
467            && tokens[2] != NULL
468            && tokens[3] != NULL
469            && tokens[4] != NULL ) {
470         BabelFile *file = g_malloc ( sizeof (BabelFile) );
471         set_mode (file->mode, tokens[1]);
472         file->name = g_strdup (tokens[2]);
473         file->ext = g_strdup (tokens[3]);
474         file->label = g_strdup (tokens[4]);
475         a_babel_file_list = g_list_append (a_babel_file_list, file);
476         g_debug ("New gpsbabel file: %s", file->name);
477       } else {
478         g_warning ( "Unexpected gpsbabel format string: %s", line);
479       }
480     } /* else: ignore */
481   } else {
482     g_warning ( "Unexpected gpsbabel format string: %s", line);
483   }
484   g_strfreev ( tokens );
485 }
486
487 static void load_feature_cb (BabelProgressCode code, gpointer line, gpointer user_data)
488 {
489   if (line != NULL)
490     load_feature_parse_line (line);
491 }
492
493 static gboolean load_feature ()
494 {
495   int i;
496   gboolean ret = FALSE;
497   gchar *args[4];  
498
499   if ( gpsbabel_loc ) {
500     i = 0;
501     if ( unbuffer_loc )
502       args[i++] = unbuffer_loc;
503     args[i++] = gpsbabel_loc;
504     args[i++] = "-^3";
505     args[i] = NULL;
506
507     ret = babel_general_convert (load_feature_cb, args, NULL);
508   } else
509     g_critical("gpsbabel not found in PATH");
510
511   return ret;
512 }
513
514 /**
515  * a_babel_init:
516  * 
517  * Initialises babel module.
518  * Mainly check existence of gpsbabel progam
519  * and load all features available in ths version.
520  */
521 void a_babel_init ()
522 {
523   /* TODO allow to set gpsbabel path via command line */
524   gpsbabel_loc = g_find_program_in_path( "gpsbabel" );
525   if ( !gpsbabel_loc )
526     g_critical( "gpsbabel not found in PATH" );
527   unbuffer_loc = g_find_program_in_path( "unbuffer" );
528   if ( !unbuffer_loc )
529     g_warning( "unbuffer not found in PATH" );
530
531   load_feature ();
532 }
533
534 /**
535  * a_babel_uninit:
536  * 
537  * Free resources acquired by a_babel_init.
538  */
539 void a_babel_uninit ()
540 {
541   g_free ( gpsbabel_loc );
542   g_free ( unbuffer_loc );
543
544   if ( a_babel_file_list ) {
545     GList *gl;
546     for (gl = a_babel_file_list; gl != NULL; gl = g_list_next(gl)) {
547       BabelFile *file = gl->data;
548       g_free ( file->name );
549       g_free ( file->ext );
550       g_free ( file->label );
551       g_free ( gl->data );
552     }
553     g_list_free ( a_babel_file_list );
554   }
555
556   if ( a_babel_device_list ) {
557     GList *gl;
558     for (gl = a_babel_device_list; gl != NULL; gl = g_list_next(gl)) {
559       BabelDevice *device = gl->data;
560       g_free ( device->name );
561       g_free ( device->label );
562       g_free ( gl->data );
563     }
564     g_list_free ( a_babel_device_list );
565   }
566
567 }