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