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);
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
106 * @cb: A callback function.
107 * @user_data: passed along to cb
108 * @not_used: Must use NULL
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.
114 * Returns: %TRUE on success
116 gboolean a_babel_convert( VikTrwLayer *vt, const char *babelargs, BabelStatusFunc cb, gpointer user_data, gpointer not_used )
120 gchar *name_src = NULL;
121 gboolean ret = FALSE;
122 gchar *bargs = g_strconcat(babelargs, " -i gpx", NULL);
124 if ((fd_src = g_file_open_tmp("tmp-viking.XXXXXX", &name_src, NULL)) >= 0) {
125 g_debug ("%s: temporary file: %s", __FUNCTION__, name_src);
126 f = fdopen(fd_src, "w");
127 a_gpx_write_file(vt, f, NULL);
130 ret = a_babel_convert_from ( vt, bargs, name_src, cb, user_data, not_used );
140 * Perform any cleanup actions once GPSBabel has completed running
142 static void babel_watch ( GPid pid,
146 g_spawn_close_pid ( pid );
150 * babel_general_convert:
151 * @args: The command line arguments passed to GPSBabel
152 * @cb: callback that is run for each line of GPSBabel output and at completion of the run
153 * callback may be NULL
154 * @user_data: passed along to cb
156 * The function to actually invoke the GPSBabel external command
158 * Returns: %TRUE on successful invocation of GPSBabel command
160 static gboolean babel_general_convert( BabelStatusFunc cb, gchar **args, gpointer user_data )
162 gboolean ret = FALSE;
164 GError *error = NULL;
167 if (!g_spawn_async_with_pipes (NULL, args, NULL, G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL, &pid, NULL, &babel_stdout, NULL, &error)) {
168 g_warning ("Async command failed: %s", error->message);
175 diag = fdopen(babel_stdout, "r");
176 setvbuf(diag, NULL, _IONBF, 0);
178 while (fgets(line, sizeof(line), diag)) {
180 cb(BABEL_DIAG_OUTPUT, line, user_data);
183 cb(BABEL_DONE, NULL, user_data);
187 g_child_watch_add ( pid, (GChildWatchFunc) babel_watch, NULL );
196 * babel_general_convert_from:
197 * @vtl: The TrackWaypoint Layer to save the data into
198 * If it is null it signifies that no data is to be processed,
199 * however the gpsbabel command is still ran as it can be for non-data related options eg:
200 * for use with the power off command - 'command_off'
201 * @cb: callback that is run upon new data from STDOUT (?)
202 * (TODO: STDERR would be nice since we usually redirect STDOUT)
203 * @user_data: passed along to cb
205 * Runs args[0] with the arguments and uses the GPX module
206 * to import the GPX data into layer vt. Assumes that upon
207 * running the command, the data will appear in the (usually
208 * temporary) file name_dst.
210 * Returns: %TRUE on success
212 static gboolean babel_general_convert_from( VikTrwLayer *vt, BabelStatusFunc cb, gchar **args, const gchar *name_dst, gpointer user_data )
214 gboolean ret = FALSE;
217 if (babel_general_convert(cb, args, user_data)) {
219 /* No data actually required but still need to have run gpsbabel anyway
220 - eg using the device power command_off */
224 f = g_fopen(name_dst, "r");
226 ret = a_gpx_read_file ( vt, f );
236 * a_babel_convert_from:
237 * @vt: The TRW layer to place data into. Duplicate items will be overwritten.
238 * @babelargs: A string containing gpsbabel command line options. In addition to any filters, this string
239 * must include the input file type (-i) option.
240 * @cb: Optional callback function. Same usage as in a_babel_convert().
241 * @user_data: passed along to cb
242 * @not_used: Must use NULL
244 * Loads data into a trw layer from a file, using gpsbabel. This routine is synchronous;
245 * that is, it will block the calling program until the conversion is done. To avoid blocking, call
246 * this routine from a worker thread.
248 * Returns: %TRUE on success
250 gboolean a_babel_convert_from( VikTrwLayer *vt, const char *babelargs, const char *from, BabelStatusFunc cb, gpointer user_data, gpointer not_used )
254 gchar *name_dst = NULL;
255 gboolean ret = FALSE;
258 if ((fd_dst = g_file_open_tmp("tmp-viking.XXXXXX", &name_dst, NULL)) >= 0) {
259 g_debug ("%s: temporary file: %s", __FUNCTION__, name_dst);
263 gchar **sub_args = g_strsplit(babelargs, " ", 0);
267 args[i++] = unbuffer_loc;
268 args[i++] = gpsbabel_loc;
269 for (j = 0; sub_args[j]; j++) {
270 /* some version of gpsbabel can not take extra blank arg */
271 if (sub_args[j][0] != '\0')
272 args[i++] = sub_args[j];
277 args[i++] = (char *)from;
279 args[i++] = name_dst;
282 ret = babel_general_convert_from ( vt, cb, args, name_dst, user_data );
284 g_strfreev(sub_args);
286 g_critical("gpsbabel not found in PATH");
295 * a_babel_convert_from_shellcommand:
296 * @vt: The #VikTrwLayer where to insert the collected data
297 * @input_cmd: the command to run
298 * @cb: Optional callback function. Same usage as in a_babel_convert().
299 * @user_data: passed along to cb
300 * @not_used: Must use NULL
302 * Runs the input command in a shell (bash) and optionally uses GPSBabel to convert from input_file_type.
303 * If input_file_type is %NULL, doesn't use GPSBabel. Input must be GPX (or Geocaching *.loc)
305 * Uses babel_general_convert_from() to actually run the command. This function
306 * prepares the command and temporary file, and sets up the arguments for bash.
308 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 )
311 gchar *name_dst = NULL;
312 gboolean ret = FALSE;
315 if ((fd_dst = g_file_open_tmp("tmp-viking.XXXXXX", &name_dst, NULL)) >= 0) {
316 g_debug ("%s: temporary file: %s", __FUNCTION__, name_dst);
317 gchar *shell_command;
318 if ( input_file_type )
319 shell_command = g_strdup_printf("%s | %s -i %s -f - -o gpx -F %s",
320 input_cmd, gpsbabel_loc, input_file_type, name_dst);
322 shell_command = g_strdup_printf("%s > %s", input_cmd, name_dst);
324 g_debug("%s: %s", __FUNCTION__, shell_command);
327 args = g_malloc(sizeof(gchar *)*4);
328 args[0] = BASH_LOCATION;
330 args[2] = shell_command;
333 ret = babel_general_convert_from ( vt, cb, args, name_dst, user_data );
335 g_free ( shell_command );
344 * a_babel_convert_from_url:
345 * @vt: The #VikTrwLayer where to insert the collected data
346 * @url: the URL to fetch
347 * @cb: Optional callback function. Same usage as in a_babel_convert().
348 * @user_data: passed along to cb
349 * @options: download options. Maybe NULL.
351 * Download the file pointed by the URL and optionally uses GPSBabel to convert from input_file_type.
352 * If input_file_type is %NULL, doesn't use GPSBabel. Input must be GPX.
354 * Returns: %TRUE on successful invocation of GPSBabel or read of the GPX
357 gboolean a_babel_convert_from_url ( VikTrwLayer *vt, const char *url, const char *input_type, BabelStatusFunc cb, gpointer user_data, DownloadMapOptions *options )
359 // If no download options specified, use defaults:
360 DownloadMapOptions myoptions = { FALSE, FALSE, NULL, 2, NULL, NULL, NULL };
362 myoptions = *options;
365 gboolean ret = FALSE;
366 gchar *name_src = NULL;
367 gchar *babelargs = NULL;
369 g_debug("%s: input_type=%s url=%s", __FUNCTION__, input_type, url);
371 if ((fd_src = g_file_open_tmp("tmp-viking.XXXXXX", &name_src, NULL)) >= 0) {
372 g_debug ("%s: temporary file: %s", __FUNCTION__, name_src);
376 fetch_ret = a_http_download_get_url(url, "", name_src, &myoptions, NULL);
377 if (fetch_ret == 0) {
378 if (input_type != NULL) {
379 babelargs = g_strdup_printf(" -i %s", input_type);
380 ret = a_babel_convert_from( vt, babelargs, name_src, NULL, NULL, NULL );
382 /* Process directly the retrieved file */
383 g_debug("%s: directly read GPX file %s", __FUNCTION__, name_src);
384 FILE *f = g_fopen(name_src, "r");
386 ret = a_gpx_read_file ( vt, f );
401 * a_babel_convert_from_url_or_shell:
402 * @vt: The #VikTrwLayer where to insert the collected data
403 * @url: the URL to fetch
404 * @cb: Optional callback function. Same usage as in a_babel_convert().
405 * @user_data: passed along to cb
406 * @options: download options. Maybe NULL.
408 * Download the file pointed by the URL and optionally uses GPSBabel to convert from input_file_type.
409 * If input_file_type is %NULL, doesn't use GPSBabel. Input must be GPX.
411 * Returns: %TRUE on successful invocation of GPSBabel or read of the GPX
414 gboolean a_babel_convert_from_url_or_shell ( VikTrwLayer *vt, const char *input, const char *input_type, BabelStatusFunc cb, gpointer user_data, DownloadMapOptions *options )
417 /* Check nature of input */
418 gboolean isUrl = FALSE;
420 for (i = 0 ; PROTOS[i] != NULL ; i++)
422 const gchar *proto = PROTOS[i];
423 if (strncmp (input, proto, strlen(proto)) == 0)
425 /* Procotol matches: save result */
432 return a_babel_convert_from_url (vt, input, input_type, cb, user_data, options);
434 return a_babel_convert_from_shellcommand (vt, input, input_type, cb, user_data, options);
437 static gboolean babel_general_convert_to( VikTrwLayer *vt, VikTrack *trk, BabelStatusFunc cb, gchar **args, const gchar *name_src, gpointer user_data )
439 // Now strips out invisible tracks and waypoints
440 if (!a_file_export(vt, name_src, FILE_TYPE_GPX, trk, FALSE)) {
441 g_critical("Error exporting to %s", name_src);
445 return babel_general_convert (cb, args, user_data);
449 * a_babel_convert_to:
450 * @vt: The TRW layer from which data is taken.
451 * @track: Operate on the individual track if specified. Use NULL when operating on a TRW layer
452 * @babelargs: A string containing gpsbabel command line options. In addition to any filters, this string
453 * must include the input file type (-i) option.
454 * @to: Filename or device the data is written to.
455 * @cb: Optional callback function. Same usage as in a_babel_convert.
456 * @user_data: passed along to cb
458 * Exports data using gpsbabel. This routine is synchronous;
459 * that is, it will block the calling program until the conversion is done. To avoid blocking, call
460 * this routine from a worker thread.
462 * Returns: %TRUE on successful invocation of GPSBabel command
464 gboolean a_babel_convert_to( VikTrwLayer *vt, VikTrack *track, const char *babelargs, const char *to, BabelStatusFunc cb, gpointer user_data )
468 gchar *name_src = NULL;
469 gboolean ret = FALSE;
472 if ((fd_src = g_file_open_tmp("tmp-viking.XXXXXX", &name_src, NULL)) >= 0) {
473 g_debug ("%s: temporary file: %s", __FUNCTION__, name_src);
477 gchar **sub_args = g_strsplit(babelargs, " ", 0);
481 args[i++] = unbuffer_loc;
482 args[i++] = gpsbabel_loc;
485 for (j = 0; sub_args[j]; j++)
486 /* some version of gpsbabel can not take extra blank arg */
487 if (sub_args[j][0] != '\0')
488 args[i++] = sub_args[j];
490 args[i++] = name_src;
492 args[i++] = (char *)to;
495 ret = babel_general_convert_to ( vt, track, cb, args, name_src, user_data );
497 g_strfreev(sub_args);
499 g_critical("gpsbabel not found in PATH");
507 static void set_mode(BabelMode *mode, gchar *smode)
509 mode->waypointsRead = smode[0] == 'r';
510 mode->waypointsWrite = smode[1] == 'w';
511 mode->tracksRead = smode[2] == 'r';
512 mode->tracksWrite = smode[3] == 'w';
513 mode->routesRead = smode[4] == 'r';
514 mode->routesWrite = smode[5] == 'w';
518 * load_feature_parse_line:
520 * Load a single feature stored in the given line.
522 static void load_feature_parse_line (gchar *line)
524 gchar **tokens = g_strsplit ( line, "\t", 0 );
526 && tokens[0] != NULL ) {
527 if ( strcmp("serial", tokens[0]) == 0 ) {
528 if ( tokens[1] != NULL
531 && tokens[4] != NULL ) {
532 BabelDevice *device = g_malloc ( sizeof (BabelDevice) );
533 set_mode (&(device->mode), tokens[1]);
534 device->name = g_strdup (tokens[2]);
535 device->label = g_strndup (tokens[4], 50); // Limit really long label text
536 a_babel_device_list = g_list_append (a_babel_device_list, device);
537 g_debug ("New gpsbabel device: %s, %d%d%d%d%d%d(%s)",
539 device->mode.waypointsRead, device->mode.waypointsWrite,
540 device->mode.tracksRead, device->mode.tracksWrite,
541 device->mode.routesRead, device->mode.routesWrite,
544 g_warning ( "Unexpected gpsbabel format string: %s", line);
546 } else if ( strcmp("file", tokens[0]) == 0 ) {
547 if ( tokens[1] != NULL
550 && tokens[4] != NULL ) {
551 BabelFile *file = g_malloc ( sizeof (BabelFile) );
552 set_mode (&(file->mode), tokens[1]);
553 file->name = g_strdup (tokens[2]);
554 file->ext = g_strdup (tokens[3]);
555 file->label = g_strdup (tokens[4]);
556 a_babel_file_list = g_list_append (a_babel_file_list, file);
557 g_debug ("New gpsbabel file: %s, %d%d%d%d%d%d(%s)",
559 file->mode.waypointsRead, file->mode.waypointsWrite,
560 file->mode.tracksRead, file->mode.tracksWrite,
561 file->mode.routesRead, file->mode.routesWrite,
564 g_warning ( "Unexpected gpsbabel format string: %s", line);
568 g_warning ( "Unexpected gpsbabel format string: %s", line);
570 g_strfreev ( tokens );
573 static void load_feature_cb (BabelProgressCode code, gpointer line, gpointer user_data)
576 load_feature_parse_line (line);
579 static gboolean load_feature ()
582 gboolean ret = FALSE;
585 if ( gpsbabel_loc ) {
588 args[i++] = unbuffer_loc;
589 args[i++] = gpsbabel_loc;
593 ret = babel_general_convert (load_feature_cb, args, NULL);
595 g_critical("gpsbabel not found in PATH");
603 * Initialises babel module.
604 * Mainly check existence of gpsbabel progam
605 * and load all features available in ths version.
609 /* TODO allow to set gpsbabel path via command line */
610 gpsbabel_loc = g_find_program_in_path( "gpsbabel" );
612 g_critical( "gpsbabel not found in PATH" );
614 // Unlikely to package unbuffer on Windows so ATM don't even bother trying
615 // Highly unlikely unbuffer is available on a Windows system otherwise
617 unbuffer_loc = g_find_program_in_path( "unbuffer" );
619 g_warning( "unbuffer not found in PATH" );
628 * Free resources acquired by a_babel_init.
630 void a_babel_uninit ()
632 g_free ( gpsbabel_loc );
633 g_free ( unbuffer_loc );
635 if ( a_babel_file_list ) {
637 for (gl = a_babel_file_list; gl != NULL; gl = g_list_next(gl)) {
638 BabelFile *file = gl->data;
639 g_free ( file->name );
640 g_free ( file->ext );
641 g_free ( file->label );
644 g_list_free ( a_babel_file_list );
647 if ( a_babel_device_list ) {
649 for (gl = a_babel_device_list; gl != NULL; gl = g_list_next(gl)) {
650 BabelDevice *device = gl->data;
651 g_free ( device->name );
652 g_free ( device->label );
655 g_list_free ( a_babel_device_list );
663 * Indicates if babel is available or not.
665 * Returns: true if babel available
667 gboolean a_babel_available ()
669 return a_babel_device_list != NULL;