2 * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
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>
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.
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.
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
26 * @short_description: running external programs and redirecting to TRWLayers.
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.
46 #include <glib/gstdio.h>
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"
52 * List of supported protocols.
54 const gchar *PROTOS[] = { "http://", "https://", "ftp://", NULL };
59 static gchar *gpsbabel_loc = NULL;
64 static gchar *unbuffer_loc = NULL;
67 * List of file formats supported by gpsbabel.
69 GList *a_babel_file_list;
72 * List of device supported by gpsbabel.
74 GList *a_babel_device_list;
77 * Run a function on all file formats supporting a given mode.
79 void a_babel_foreach_file_with_mode (BabelMode mode, GFunc func, gpointer user_data)
82 for ( current = g_list_first (a_babel_file_list) ;
84 current = g_list_next (current) )
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;
97 func (currentFile, user_data);
102 * a_babel_foreach_file_read_any:
103 * @func: The function to be called on any file format with a read method
104 * @user_data: Data passed into the function
106 * Run a function on all file formats with any kind of read method
107 * (which is almost all but not quite - e.g. with GPSBabel v1.4.4 - PalmDoc is write only waypoints)
109 void a_babel_foreach_file_read_any (GFunc func, gpointer user_data)
112 for ( current = g_list_first (a_babel_file_list) ;
114 current = g_list_next (current) )
116 BabelFile *currentFile = current->data;
117 // Call function when any read mode found
118 if ( currentFile->mode.waypointsRead ||
119 currentFile->mode.tracksRead ||
120 currentFile->mode.routesRead)
121 func (currentFile, user_data);
127 * @vt: The TRW layer to modify. All data will be deleted, and replaced by what gpsbabel outputs.
128 * @babelargs: A string containing gpsbabel command line filter options. No file types or names should
130 * @cb: A callback function.
131 * @user_data: passed along to cb
132 * @not_used: Must use NULL
134 * This function modifies data in a trw layer using gpsbabel filters. This routine is synchronous;
135 * that is, it will block the calling program until the conversion is done. To avoid blocking, call
136 * this routine from a worker thread.
138 * Returns: %TRUE on success
140 gboolean a_babel_convert( VikTrwLayer *vt, const char *babelargs, BabelStatusFunc cb, gpointer user_data, gpointer not_used )
142 gboolean ret = FALSE;
143 gchar *bargs = g_strconcat(babelargs, " -i gpx", NULL);
144 gchar *name_src = a_gpx_write_tmp_file ( vt, NULL );
147 ret = a_babel_convert_from ( vt, bargs, name_src, cb, user_data, not_used );
157 * Perform any cleanup actions once GPSBabel has completed running
159 static void babel_watch ( GPid pid,
163 g_spawn_close_pid ( pid );
167 * babel_general_convert:
168 * @args: The command line arguments passed to GPSBabel
169 * @cb: callback that is run for each line of GPSBabel output and at completion of the run
170 * callback may be NULL
171 * @user_data: passed along to cb
173 * The function to actually invoke the GPSBabel external command
175 * Returns: %TRUE on successful invocation of GPSBabel command
177 static gboolean babel_general_convert( BabelStatusFunc cb, gchar **args, gpointer user_data )
179 gboolean ret = FALSE;
181 GError *error = NULL;
184 if (!g_spawn_async_with_pipes (NULL, args, NULL, G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL, &pid, NULL, &babel_stdout, NULL, &error)) {
185 g_warning ("Async command failed: %s", error->message);
192 diag = fdopen(babel_stdout, "r");
193 setvbuf(diag, NULL, _IONBF, 0);
195 while (fgets(line, sizeof(line), diag)) {
197 cb(BABEL_DIAG_OUTPUT, line, user_data);
200 cb(BABEL_DONE, NULL, user_data);
204 g_child_watch_add ( pid, (GChildWatchFunc) babel_watch, NULL );
213 * babel_general_convert_from:
214 * @vtl: The TrackWaypoint Layer to save the data into
215 * If it is null it signifies that no data is to be processed,
216 * however the gpsbabel command is still ran as it can be for non-data related options eg:
217 * for use with the power off command - 'command_off'
218 * @cb: callback that is run upon new data from STDOUT (?)
219 * (TODO: STDERR would be nice since we usually redirect STDOUT)
220 * @user_data: passed along to cb
222 * Runs args[0] with the arguments and uses the GPX module
223 * to import the GPX data into layer vt. Assumes that upon
224 * running the command, the data will appear in the (usually
225 * temporary) file name_dst.
227 * Returns: %TRUE on success
229 static gboolean babel_general_convert_from( VikTrwLayer *vt, BabelStatusFunc cb, gchar **args, const gchar *name_dst, gpointer user_data )
231 gboolean ret = FALSE;
234 if (babel_general_convert(cb, args, user_data)) {
236 /* No data actually required but still need to have run gpsbabel anyway
237 - eg using the device power command_off */
241 f = g_fopen(name_dst, "r");
243 ret = a_gpx_read_file ( vt, f );
253 * a_babel_convert_from:
254 * @vt: The TRW layer to place data into. Duplicate items will be overwritten.
255 * @babelargs: A string containing gpsbabel command line options. In addition to any filters, this string
256 * must include the input file type (-i) option.
257 * @cb: Optional callback function. Same usage as in a_babel_convert().
258 * @user_data: passed along to cb
259 * @not_used: Must use NULL
261 * Loads data into a trw layer from a file, using gpsbabel. This routine is synchronous;
262 * that is, it will block the calling program until the conversion is done. To avoid blocking, call
263 * this routine from a worker thread.
265 * Returns: %TRUE on success
267 gboolean a_babel_convert_from( VikTrwLayer *vt, const char *babelargs, const char *from, BabelStatusFunc cb, gpointer user_data, gpointer not_used )
271 gchar *name_dst = NULL;
272 gboolean ret = FALSE;
275 if ((fd_dst = g_file_open_tmp("tmp-viking.XXXXXX", &name_dst, NULL)) >= 0) {
276 g_debug ("%s: temporary file: %s", __FUNCTION__, name_dst);
280 gchar **sub_args = g_strsplit(babelargs, " ", 0);
284 args[i++] = unbuffer_loc;
285 args[i++] = gpsbabel_loc;
286 for (j = 0; sub_args[j]; j++) {
287 /* some version of gpsbabel can not take extra blank arg */
288 if (sub_args[j][0] != '\0')
289 args[i++] = sub_args[j];
294 args[i++] = (char *)from;
296 args[i++] = name_dst;
299 ret = babel_general_convert_from ( vt, cb, args, name_dst, user_data );
301 g_strfreev(sub_args);
303 g_critical("gpsbabel not found in PATH");
312 * a_babel_convert_from_shellcommand:
313 * @vt: The #VikTrwLayer where to insert the collected data
314 * @input_cmd: the command to run
315 * @cb: Optional callback function. Same usage as in a_babel_convert().
316 * @user_data: passed along to cb
317 * @not_used: Must use NULL
319 * Runs the input command in a shell (bash) and optionally uses GPSBabel to convert from input_file_type.
320 * If input_file_type is %NULL, doesn't use GPSBabel. Input must be GPX (or Geocaching *.loc)
322 * Uses babel_general_convert_from() to actually run the command. This function
323 * prepares the command and temporary file, and sets up the arguments for bash.
325 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 )
328 gchar *name_dst = NULL;
329 gboolean ret = FALSE;
332 if ((fd_dst = g_file_open_tmp("tmp-viking.XXXXXX", &name_dst, NULL)) >= 0) {
333 g_debug ("%s: temporary file: %s", __FUNCTION__, name_dst);
334 gchar *shell_command;
335 if ( input_file_type )
336 shell_command = g_strdup_printf("%s | %s -i %s -f - -o gpx -F %s",
337 input_cmd, gpsbabel_loc, input_file_type, name_dst);
339 shell_command = g_strdup_printf("%s > %s", input_cmd, name_dst);
341 g_debug("%s: %s", __FUNCTION__, shell_command);
344 args = g_malloc(sizeof(gchar *)*4);
345 args[0] = BASH_LOCATION;
347 args[2] = shell_command;
350 ret = babel_general_convert_from ( vt, cb, args, name_dst, user_data );
352 g_free ( shell_command );
361 * a_babel_convert_from_url:
362 * @vt: The #VikTrwLayer where to insert the collected data
363 * @url: the URL to fetch
364 * @cb: Optional callback function. Same usage as in a_babel_convert().
365 * @user_data: passed along to cb
366 * @options: download options. Maybe NULL.
368 * Download the file pointed by the URL and optionally uses GPSBabel to convert from input_file_type.
369 * If input_file_type is %NULL, doesn't use GPSBabel. Input must be GPX.
371 * Returns: %TRUE on successful invocation of GPSBabel or read of the GPX
374 gboolean a_babel_convert_from_url ( VikTrwLayer *vt, const char *url, const char *input_type, BabelStatusFunc cb, gpointer user_data, DownloadMapOptions *options )
376 // If no download options specified, use defaults:
377 DownloadMapOptions myoptions = { FALSE, FALSE, NULL, 2, NULL, NULL, NULL };
379 myoptions = *options;
382 gboolean ret = FALSE;
383 gchar *name_src = NULL;
384 gchar *babelargs = NULL;
386 g_debug("%s: input_type=%s url=%s", __FUNCTION__, input_type, url);
388 if ((fd_src = g_file_open_tmp("tmp-viking.XXXXXX", &name_src, NULL)) >= 0) {
389 g_debug ("%s: temporary file: %s", __FUNCTION__, name_src);
393 fetch_ret = a_http_download_get_url(url, "", name_src, &myoptions, NULL);
394 if (fetch_ret == DOWNLOAD_SUCCESS) {
395 if (input_type != NULL) {
396 babelargs = g_strdup_printf(" -i %s", input_type);
397 ret = a_babel_convert_from( vt, babelargs, name_src, NULL, NULL, NULL );
399 /* Process directly the retrieved file */
400 g_debug("%s: directly read GPX file %s", __FUNCTION__, name_src);
401 FILE *f = g_fopen(name_src, "r");
403 ret = a_gpx_read_file ( vt, f );
418 * a_babel_convert_from_url_or_shell:
419 * @vt: The #VikTrwLayer where to insert the collected data
420 * @url: the URL to fetch
421 * @cb: Optional callback function. Same usage as in a_babel_convert().
422 * @user_data: passed along to cb
423 * @options: download options. Maybe NULL.
425 * Download the file pointed by the URL and optionally uses GPSBabel to convert from input_file_type.
426 * If input_file_type is %NULL, doesn't use GPSBabel. Input must be GPX.
428 * Returns: %TRUE on successful invocation of GPSBabel or read of the GPX
431 gboolean a_babel_convert_from_url_or_shell ( VikTrwLayer *vt, const char *input, const char *input_type, BabelStatusFunc cb, gpointer user_data, DownloadMapOptions *options )
434 /* Check nature of input */
435 gboolean isUrl = FALSE;
437 for (i = 0 ; PROTOS[i] != NULL ; i++)
439 const gchar *proto = PROTOS[i];
440 if (strncmp (input, proto, strlen(proto)) == 0)
442 /* Procotol matches: save result */
449 return a_babel_convert_from_url (vt, input, input_type, cb, user_data, options);
451 return a_babel_convert_from_shellcommand (vt, input, input_type, cb, user_data, options);
454 static gboolean babel_general_convert_to( VikTrwLayer *vt, VikTrack *trk, BabelStatusFunc cb, gchar **args, const gchar *name_src, gpointer user_data )
456 // Now strips out invisible tracks and waypoints
457 if (!a_file_export(vt, name_src, FILE_TYPE_GPX, trk, FALSE)) {
458 g_critical("Error exporting to %s", name_src);
462 return babel_general_convert (cb, args, user_data);
466 * a_babel_convert_to:
467 * @vt: The TRW layer from which data is taken.
468 * @track: Operate on the individual track if specified. Use NULL when operating on a TRW layer
469 * @babelargs: A string containing gpsbabel command line options. In addition to any filters, this string
470 * must include the input file type (-i) option.
471 * @to: Filename or device the data is written to.
472 * @cb: Optional callback function. Same usage as in a_babel_convert.
473 * @user_data: passed along to cb
475 * Exports data using gpsbabel. This routine is synchronous;
476 * that is, it will block the calling program until the conversion is done. To avoid blocking, call
477 * this routine from a worker thread.
479 * Returns: %TRUE on successful invocation of GPSBabel command
481 gboolean a_babel_convert_to( VikTrwLayer *vt, VikTrack *track, const char *babelargs, const char *to, BabelStatusFunc cb, gpointer user_data )
485 gchar *name_src = NULL;
486 gboolean ret = FALSE;
489 if ((fd_src = g_file_open_tmp("tmp-viking.XXXXXX", &name_src, NULL)) >= 0) {
490 g_debug ("%s: temporary file: %s", __FUNCTION__, name_src);
494 gchar **sub_args = g_strsplit(babelargs, " ", 0);
498 args[i++] = unbuffer_loc;
499 args[i++] = gpsbabel_loc;
502 for (j = 0; sub_args[j]; j++)
503 /* some version of gpsbabel can not take extra blank arg */
504 if (sub_args[j][0] != '\0')
505 args[i++] = sub_args[j];
507 args[i++] = name_src;
509 args[i++] = (char *)to;
512 ret = babel_general_convert_to ( vt, track, cb, args, name_src, user_data );
514 g_strfreev(sub_args);
516 g_critical("gpsbabel not found in PATH");
524 static void set_mode(BabelMode *mode, gchar *smode)
526 mode->waypointsRead = smode[0] == 'r';
527 mode->waypointsWrite = smode[1] == 'w';
528 mode->tracksRead = smode[2] == 'r';
529 mode->tracksWrite = smode[3] == 'w';
530 mode->routesRead = smode[4] == 'r';
531 mode->routesWrite = smode[5] == 'w';
535 * load_feature_parse_line:
537 * Load a single feature stored in the given line.
539 static void load_feature_parse_line (gchar *line)
541 gchar **tokens = g_strsplit ( line, "\t", 0 );
543 && tokens[0] != NULL ) {
544 if ( strcmp("serial", tokens[0]) == 0 ) {
545 if ( tokens[1] != NULL
548 && tokens[4] != NULL ) {
549 BabelDevice *device = g_malloc ( sizeof (BabelDevice) );
550 set_mode (&(device->mode), tokens[1]);
551 device->name = g_strdup (tokens[2]);
552 device->label = g_strndup (tokens[4], 50); // Limit really long label text
553 a_babel_device_list = g_list_append (a_babel_device_list, device);
554 g_debug ("New gpsbabel device: %s, %d%d%d%d%d%d(%s)",
556 device->mode.waypointsRead, device->mode.waypointsWrite,
557 device->mode.tracksRead, device->mode.tracksWrite,
558 device->mode.routesRead, device->mode.routesWrite,
561 g_warning ( "Unexpected gpsbabel format string: %s", line);
563 } else if ( strcmp("file", tokens[0]) == 0 ) {
564 if ( tokens[1] != NULL
567 && tokens[4] != NULL ) {
568 BabelFile *file = g_malloc ( sizeof (BabelFile) );
569 set_mode (&(file->mode), tokens[1]);
570 file->name = g_strdup (tokens[2]);
571 file->ext = g_strdup (tokens[3]);
572 file->label = g_strdup (tokens[4]);
573 a_babel_file_list = g_list_append (a_babel_file_list, file);
574 g_debug ("New gpsbabel file: %s, %d%d%d%d%d%d(%s)",
576 file->mode.waypointsRead, file->mode.waypointsWrite,
577 file->mode.tracksRead, file->mode.tracksWrite,
578 file->mode.routesRead, file->mode.routesWrite,
581 g_warning ( "Unexpected gpsbabel format string: %s", line);
585 g_warning ( "Unexpected gpsbabel format string: %s", line);
587 g_strfreev ( tokens );
590 static void load_feature_cb (BabelProgressCode code, gpointer line, gpointer user_data)
593 load_feature_parse_line (line);
596 static gboolean load_feature ()
599 gboolean ret = FALSE;
602 if ( gpsbabel_loc ) {
605 args[i++] = unbuffer_loc;
606 args[i++] = gpsbabel_loc;
610 ret = babel_general_convert (load_feature_cb, args, NULL);
612 g_critical("gpsbabel not found in PATH");
620 * Initialises babel module.
621 * Mainly check existence of gpsbabel progam
622 * and load all features available in ths version.
626 /* TODO allow to set gpsbabel path via command line */
627 gpsbabel_loc = g_find_program_in_path( "gpsbabel" );
629 g_critical( "gpsbabel not found in PATH" );
631 // Unlikely to package unbuffer on Windows so ATM don't even bother trying
632 // Highly unlikely unbuffer is available on a Windows system otherwise
634 unbuffer_loc = g_find_program_in_path( "unbuffer" );
636 g_warning( "unbuffer not found in PATH" );
645 * Free resources acquired by a_babel_init.
647 void a_babel_uninit ()
649 g_free ( gpsbabel_loc );
650 g_free ( unbuffer_loc );
652 if ( a_babel_file_list ) {
654 for (gl = a_babel_file_list; gl != NULL; gl = g_list_next(gl)) {
655 BabelFile *file = gl->data;
656 g_free ( file->name );
657 g_free ( file->ext );
658 g_free ( file->label );
661 g_list_free ( a_babel_file_list );
664 if ( a_babel_device_list ) {
666 for (gl = a_babel_device_list; gl != NULL; gl = g_list_next(gl)) {
667 BabelDevice *device = gl->data;
668 g_free ( device->name );
669 g_free ( device->label );
672 g_list_free ( a_babel_device_list );
680 * Indicates if babel is available or not.
682 * Returns: true if babel available
684 gboolean a_babel_available ()
686 return a_babel_device_list != NULL;