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