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