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.
40 #include "preferences.h"
47 #include <glib/gstdio.h>
48 #include <glib/gi18n.h>
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"
54 * List of supported protocols.
56 const gchar *PROTOS[] = { "http://", "https://", "ftp://", NULL };
61 static gchar *gpsbabel_loc = NULL;
66 static gchar *unbuffer_loc = NULL;
69 * List of file formats supported by gpsbabel.
71 GList *a_babel_file_list;
74 * List of device supported by gpsbabel.
76 GList *a_babel_device_list;
79 * Run a function on all file formats supporting a given mode.
81 void a_babel_foreach_file_with_mode (BabelMode mode, GFunc func, gpointer user_data)
84 for ( current = g_list_first (a_babel_file_list) ;
86 current = g_list_next (current) )
88 BabelFile *currentFile = current->data;
89 /* Check compatibility of modes */
90 gboolean compat = TRUE;
91 if (mode.waypointsRead && ! currentFile->mode.waypointsRead) compat = FALSE;
92 if (mode.waypointsWrite && ! currentFile->mode.waypointsWrite) compat = FALSE;
93 if (mode.tracksRead && ! currentFile->mode.tracksRead) compat = FALSE;
94 if (mode.tracksWrite && ! currentFile->mode.tracksWrite) compat = FALSE;
95 if (mode.routesRead && ! currentFile->mode.routesRead) compat = FALSE;
96 if (mode.routesWrite && ! currentFile->mode.routesWrite) compat = FALSE;
99 func (currentFile, user_data);
104 * a_babel_foreach_file_read_any:
105 * @func: The function to be called on any file format with a read method
106 * @user_data: Data passed into the function
108 * Run a function on all file formats with any kind of read method
109 * (which is almost all but not quite - e.g. with GPSBabel v1.4.4 - PalmDoc is write only waypoints)
111 void a_babel_foreach_file_read_any (GFunc func, gpointer user_data)
114 for ( current = g_list_first (a_babel_file_list) ;
116 current = g_list_next (current) )
118 BabelFile *currentFile = current->data;
119 // Call function when any read mode found
120 if ( currentFile->mode.waypointsRead ||
121 currentFile->mode.tracksRead ||
122 currentFile->mode.routesRead)
123 func (currentFile, user_data);
129 * @vt: The TRW layer to modify. All data will be deleted, and replaced by what gpsbabel outputs.
130 * @babelargs: A string containing gpsbabel command line filter options. No file types or names should
132 * @cb: A callback function.
133 * @user_data: passed along to cb
134 * @not_used: Must use NULL
136 * This function modifies data in a trw layer using gpsbabel filters. This routine is synchronous;
137 * that is, it will block the calling program until the conversion is done. To avoid blocking, call
138 * this routine from a worker thread.
140 * Returns: %TRUE on success
142 gboolean a_babel_convert( VikTrwLayer *vt, const char *babelargs, BabelStatusFunc cb, gpointer user_data, gpointer not_used )
144 gboolean ret = FALSE;
145 gchar *bargs = g_strconcat(babelargs, " -i gpx", NULL);
146 gchar *name_src = a_gpx_write_tmp_file ( vt, NULL );
149 ret = a_babel_convert_from ( vt, bargs, name_src, cb, user_data, not_used );
159 * Perform any cleanup actions once GPSBabel has completed running
161 static void babel_watch ( GPid pid,
165 g_spawn_close_pid ( pid );
169 * babel_general_convert:
170 * @args: The command line arguments passed to GPSBabel
171 * @cb: callback that is run for each line of GPSBabel output and at completion of the run
172 * callback may be NULL
173 * @user_data: passed along to cb
175 * The function to actually invoke the GPSBabel external command
177 * Returns: %TRUE on successful invocation of GPSBabel command
179 static gboolean babel_general_convert( BabelStatusFunc cb, gchar **args, gpointer user_data )
181 gboolean ret = FALSE;
183 GError *error = NULL;
186 if (!g_spawn_async_with_pipes (NULL, args, NULL, G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL, &pid, NULL, &babel_stdout, NULL, &error)) {
187 g_warning ("Async command failed: %s", error->message);
194 diag = fdopen(babel_stdout, "r");
195 setvbuf(diag, NULL, _IONBF, 0);
197 while (fgets(line, sizeof(line), diag)) {
199 cb(BABEL_DIAG_OUTPUT, line, user_data);
202 cb(BABEL_DONE, NULL, user_data);
206 g_child_watch_add ( pid, (GChildWatchFunc) babel_watch, NULL );
215 * babel_general_convert_from:
216 * @vtl: The TrackWaypoint Layer to save the data into
217 * If it is null it signifies that no data is to be processed,
218 * however the gpsbabel command is still ran as it can be for non-data related options eg:
219 * for use with the power off command - 'command_off'
220 * @cb: callback that is run upon new data from STDOUT (?)
221 * (TODO: STDERR would be nice since we usually redirect STDOUT)
222 * @user_data: passed along to cb
224 * Runs args[0] with the arguments and uses the GPX module
225 * to import the GPX data into layer vt. Assumes that upon
226 * running the command, the data will appear in the (usually
227 * temporary) file name_dst.
229 * Returns: %TRUE on success
231 static gboolean babel_general_convert_from( VikTrwLayer *vt, BabelStatusFunc cb, gchar **args, const gchar *name_dst, gpointer user_data )
233 gboolean ret = FALSE;
236 if (babel_general_convert(cb, args, user_data)) {
238 /* No data actually required but still need to have run gpsbabel anyway
239 - eg using the device power command_off */
243 f = g_fopen(name_dst, "r");
245 ret = a_gpx_read_file ( vt, f );
255 * a_babel_convert_from_filter:
256 * @vt: The TRW layer to place data into. Duplicate items will be overwritten.
257 * @babelargs: A string containing gpsbabel command line options. This string
258 * must include the input file type (-i) option.
259 * @from the file name to convert from
260 * @babelfilters: A string containing gpsbabel filter command line options
261 * @cb: Optional callback function. Same usage as in a_babel_convert().
262 * @user_data: passed along to cb
263 * @not_used: Must use NULL
265 * Loads data into a trw layer from a file, using gpsbabel. This routine is synchronous;
266 * that is, it will block the calling program until the conversion is done. To avoid blocking, call
267 * this routine from a worker thread.
269 * Returns: %TRUE on success
271 gboolean a_babel_convert_from_filter( VikTrwLayer *vt, const char *babelargs, const char *from, const char *babelfilters, BabelStatusFunc cb, gpointer user_data, gpointer not_used )
275 gchar *name_dst = NULL;
276 gboolean ret = FALSE;
279 if ((fd_dst = g_file_open_tmp("tmp-viking.XXXXXX", &name_dst, NULL)) >= 0) {
280 g_debug ("%s: temporary file: %s", __FUNCTION__, name_dst);
284 gchar **sub_args = g_strsplit(babelargs, " ", 0);
285 gchar **sub_filters = NULL;
289 args[i++] = unbuffer_loc;
290 args[i++] = gpsbabel_loc;
291 for (j = 0; sub_args[j]; j++) {
292 /* some version of gpsbabel can not take extra blank arg */
293 if (sub_args[j][0] != '\0')
294 args[i++] = sub_args[j];
297 args[i++] = (char *)from;
299 sub_filters = g_strsplit(babelfilters, " ", 0);
300 for (j = 0; sub_filters[j]; j++) {
301 /* some version of gpsbabel can not take extra blank arg */
302 if (sub_filters[j][0] != '\0')
303 args[i++] = sub_filters[j];
309 args[i++] = name_dst;
312 ret = babel_general_convert_from ( vt, cb, args, name_dst, user_data );
314 g_strfreev(sub_args);
316 g_strfreev(sub_filters);
318 g_critical("gpsbabel not found in PATH");
327 * a_babel_convert_from:
328 * @vt: The TRW layer to place data into. Duplicate items will be overwritten.
329 * @babelargs: A string containing gpsbabel command line options. This string
330 * must include the input file type (-i) option.
331 * @from: The file name to convert from
332 * @cb: Optional callback function. Same usage as in a_babel_convert().
333 * @user_data: passed along to cb
334 * @not_used: Must use NULL
336 * Loads data into a trw layer from a file, using gpsbabel. This routine is synchronous;
337 * that is, it will block the calling program until the conversion is done. To avoid blocking, call
338 * this routine from a worker thread.
340 * Returns: %TRUE on success
342 gboolean a_babel_convert_from( VikTrwLayer *vt, const char *babelargs, const char *from, BabelStatusFunc cb, gpointer user_data, gpointer not_used )
344 return a_babel_convert_from_filter ( vt, babelargs, from, NULL, cb, user_data, not_used );
347 * a_babel_convert_from_shellcommand:
348 * @vt: The #VikTrwLayer where to insert the collected data
349 * @input_cmd: the command to run
350 * @cb: Optional callback function. Same usage as in a_babel_convert().
351 * @user_data: passed along to cb
352 * @not_used: Must use NULL
354 * Runs the input command in a shell (bash) and optionally uses GPSBabel to convert from input_file_type.
355 * If input_file_type is %NULL, doesn't use GPSBabel. Input must be GPX (or Geocaching *.loc)
357 * Uses babel_general_convert_from() to actually run the command. This function
358 * prepares the command and temporary file, and sets up the arguments for bash.
360 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 )
363 gchar *name_dst = NULL;
364 gboolean ret = FALSE;
367 if ((fd_dst = g_file_open_tmp("tmp-viking.XXXXXX", &name_dst, NULL)) >= 0) {
368 g_debug ("%s: temporary file: %s", __FUNCTION__, name_dst);
369 gchar *shell_command;
370 if ( input_file_type )
371 shell_command = g_strdup_printf("%s | %s -i %s -f - -o gpx -F %s",
372 input_cmd, gpsbabel_loc, input_file_type, name_dst);
374 shell_command = g_strdup_printf("%s > %s", input_cmd, name_dst);
376 g_debug("%s: %s", __FUNCTION__, shell_command);
379 args = g_malloc(sizeof(gchar *)*4);
380 args[0] = BASH_LOCATION;
382 args[2] = shell_command;
385 ret = babel_general_convert_from ( vt, cb, args, name_dst, user_data );
387 g_free ( shell_command );
396 * a_babel_convert_from_url:
397 * @vt: The #VikTrwLayer where to insert the collected data
398 * @url: the URL to fetch
399 * @babelfilters: the filter arguments to pass to gpsbabel
400 * @cb: Optional callback function. Same usage as in a_babel_convert().
401 * @user_data: passed along to cb
402 * @options: download options. Maybe NULL.
404 * Download the file pointed by the URL and optionally uses GPSBabel to convert from input_file_type.
405 * If input_file_type is %NULL, input must be GPX.
406 * If input_file_type and babelfilters are %NULL, gpsbabel is not used.
408 * Returns: %TRUE on successful invocation of GPSBabel or read of the GPX
411 gboolean a_babel_convert_from_url_filter ( VikTrwLayer *vt, const char *url, const char *input_type, const char *babelfilters, BabelStatusFunc cb, gpointer user_data, DownloadMapOptions *options )
413 // If no download options specified, use defaults:
414 DownloadMapOptions myoptions = { FALSE, FALSE, NULL, 2, NULL, NULL, NULL };
416 myoptions = *options;
419 gboolean ret = FALSE;
420 gchar *name_src = NULL;
421 gchar *babelargs = NULL;
423 g_debug("%s: input_type=%s url=%s", __FUNCTION__, input_type, url);
425 if ((fd_src = g_file_open_tmp("tmp-viking.XXXXXX", &name_src, NULL)) >= 0) {
426 g_debug ("%s: temporary file: %s", __FUNCTION__, name_src);
430 fetch_ret = a_http_download_get_url(url, "", name_src, &myoptions, NULL);
431 if (fetch_ret == DOWNLOAD_SUCCESS) {
432 if (input_type != NULL || babelfilters != NULL) {
433 babelargs = (input_type) ? g_strdup_printf(" -i %s", input_type) : g_strdup("");
434 ret = a_babel_convert_from_filter( vt, babelargs, name_src, babelfilters, NULL, NULL, NULL );
436 /* Process directly the retrieved file */
437 g_debug("%s: directly read GPX file %s", __FUNCTION__, name_src);
438 FILE *f = g_fopen(name_src, "r");
440 ret = a_gpx_read_file ( vt, f );
446 util_remove(name_src);
455 * a_babel_convert_from_url:
456 * @vt: The #VikTrwLayer where to insert the collected data
457 * @url: the URL to fetch
458 * @cb: Optional callback function. Same usage as in a_babel_convert().
459 * @user_data: passed along to cb
460 * @options: download options. Maybe NULL.
462 * Download the file pointed by the URL and optionally uses GPSBabel to convert from input_file_type.
463 * If input_file_type is %NULL, doesn't use GPSBabel. Input must be GPX.
465 * Returns: %TRUE on successful invocation of GPSBabel or read of the GPX
468 gboolean a_babel_convert_from_url ( VikTrwLayer *vt, const char *url, const char *input_type, BabelStatusFunc cb, gpointer user_data, DownloadMapOptions *options )
470 return a_babel_convert_from_url_filter ( vt, url, input_type, NULL, cb, user_data, options );
474 * a_babel_convert_from_url_or_shell:
475 * @vt: The #VikTrwLayer where to insert the collected data
476 * @url: the URL to fetch
477 * @cb: Optional callback function. Same usage as in a_babel_convert().
478 * @user_data: passed along to cb
479 * @options: download options. Maybe NULL.
481 * Download the file pointed by the URL and optionally uses GPSBabel to convert from input_file_type.
482 * If input_file_type is %NULL, doesn't use GPSBabel. Input must be GPX.
484 * Returns: %TRUE on successful invocation of GPSBabel or read of the GPX
487 gboolean a_babel_convert_from_url_or_shell ( VikTrwLayer *vt, const char *input, const char *input_type, BabelStatusFunc cb, gpointer user_data, DownloadMapOptions *options )
490 /* Check nature of input */
491 gboolean isUrl = FALSE;
493 for (i = 0 ; PROTOS[i] != NULL ; i++)
495 const gchar *proto = PROTOS[i];
496 if (strncmp (input, proto, strlen(proto)) == 0)
498 /* Procotol matches: save result */
505 return a_babel_convert_from_url (vt, input, input_type, cb, user_data, options);
507 return a_babel_convert_from_shellcommand (vt, input, input_type, cb, user_data, options);
510 static gboolean babel_general_convert_to( VikTrwLayer *vt, VikTrack *trk, BabelStatusFunc cb, gchar **args, const gchar *name_src, gpointer user_data )
512 // Now strips out invisible tracks and waypoints
513 if (!a_file_export(vt, name_src, FILE_TYPE_GPX, trk, FALSE)) {
514 g_critical("Error exporting to %s", name_src);
518 return babel_general_convert (cb, args, user_data);
522 * a_babel_convert_to:
523 * @vt: The TRW layer from which data is taken.
524 * @track: Operate on the individual track if specified. Use NULL when operating on a TRW layer
525 * @babelargs: A string containing gpsbabel command line options. In addition to any filters, this string
526 * must include the input file type (-i) option.
527 * @to: Filename or device the data is written to.
528 * @cb: Optional callback function. Same usage as in a_babel_convert.
529 * @user_data: passed along to cb
531 * Exports data using gpsbabel. This routine is synchronous;
532 * that is, it will block the calling program until the conversion is done. To avoid blocking, call
533 * this routine from a worker thread.
535 * Returns: %TRUE on successful invocation of GPSBabel command
537 gboolean a_babel_convert_to( VikTrwLayer *vt, VikTrack *track, const char *babelargs, const char *to, BabelStatusFunc cb, gpointer user_data )
541 gchar *name_src = NULL;
542 gboolean ret = FALSE;
545 if ((fd_src = g_file_open_tmp("tmp-viking.XXXXXX", &name_src, NULL)) >= 0) {
546 g_debug ("%s: temporary file: %s", __FUNCTION__, name_src);
550 gchar **sub_args = g_strsplit(babelargs, " ", 0);
554 args[i++] = unbuffer_loc;
555 args[i++] = gpsbabel_loc;
558 for (j = 0; sub_args[j]; j++)
559 /* some version of gpsbabel can not take extra blank arg */
560 if (sub_args[j][0] != '\0')
561 args[i++] = sub_args[j];
563 args[i++] = name_src;
565 args[i++] = (char *)to;
568 ret = babel_general_convert_to ( vt, track, cb, args, name_src, user_data );
570 g_strfreev(sub_args);
572 g_critical("gpsbabel not found in PATH");
580 static void set_mode(BabelMode *mode, gchar *smode)
582 mode->waypointsRead = smode[0] == 'r';
583 mode->waypointsWrite = smode[1] == 'w';
584 mode->tracksRead = smode[2] == 'r';
585 mode->tracksWrite = smode[3] == 'w';
586 mode->routesRead = smode[4] == 'r';
587 mode->routesWrite = smode[5] == 'w';
591 * load_feature_parse_line:
593 * Load a single feature stored in the given line.
595 static void load_feature_parse_line (gchar *line)
597 gchar **tokens = g_strsplit ( line, "\t", 0 );
599 && tokens[0] != NULL ) {
600 if ( strcmp("serial", tokens[0]) == 0 ) {
601 if ( tokens[1] != NULL
604 && tokens[4] != NULL ) {
605 BabelDevice *device = g_malloc ( sizeof (BabelDevice) );
606 set_mode (&(device->mode), tokens[1]);
607 device->name = g_strdup (tokens[2]);
608 device->label = g_strndup (tokens[4], 50); // Limit really long label text
609 a_babel_device_list = g_list_append (a_babel_device_list, device);
610 g_debug ("New gpsbabel device: %s, %d%d%d%d%d%d(%s)",
612 device->mode.waypointsRead, device->mode.waypointsWrite,
613 device->mode.tracksRead, device->mode.tracksWrite,
614 device->mode.routesRead, device->mode.routesWrite,
617 g_warning ( "Unexpected gpsbabel format string: %s", line);
619 } else if ( strcmp("file", tokens[0]) == 0 ) {
620 if ( tokens[1] != NULL
623 && tokens[4] != NULL ) {
624 BabelFile *file = g_malloc ( sizeof (BabelFile) );
625 set_mode (&(file->mode), tokens[1]);
626 file->name = g_strdup (tokens[2]);
627 file->ext = g_strdup (tokens[3]);
628 file->label = g_strdup (tokens[4]);
629 a_babel_file_list = g_list_append (a_babel_file_list, file);
630 g_debug ("New gpsbabel file: %s, %d%d%d%d%d%d(%s)",
632 file->mode.waypointsRead, file->mode.waypointsWrite,
633 file->mode.tracksRead, file->mode.tracksWrite,
634 file->mode.routesRead, file->mode.routesWrite,
637 g_warning ( "Unexpected gpsbabel format string: %s", line);
641 g_warning ( "Unexpected gpsbabel format string: %s", line);
643 g_strfreev ( tokens );
646 static void load_feature_cb (BabelProgressCode code, gpointer line, gpointer user_data)
649 load_feature_parse_line (line);
652 static gboolean load_feature ()
655 gboolean ret = FALSE;
658 if ( gpsbabel_loc ) {
661 args[i++] = unbuffer_loc;
662 args[i++] = gpsbabel_loc;
666 ret = babel_general_convert (load_feature_cb, args, NULL);
668 g_critical("gpsbabel not found in PATH");
673 static VikLayerParam prefs[] = {
674 { VIK_LAYER_NUM_TYPES, VIKING_PREFERENCES_IO_NAMESPACE "gpsbabel", VIK_LAYER_PARAM_STRING, VIK_LAYER_GROUP_NONE, N_("GPSBabel:"), VIK_LAYER_WIDGET_FILEENTRY, NULL, NULL,
675 N_("Allow setting the specific instance of GPSBabel. You must restart Viking for this value to take effect."), NULL, NULL, NULL },
681 * Initialises babel module.
682 * Mainly check existence of gpsbabel progam
683 * and load all features available in that version.
688 VikLayerParamData vlpd;
690 // Basic guesses - could use %ProgramFiles% but this is simpler:
691 if ( g_file_test ( "C:\\Program Files (x86)\\GPSBabel\\gpsbabel.exe", G_FILE_TEST_EXISTS ) )
692 // 32 bit location on a 64 bit system
693 vlpd.s = "C:\\Program Files (x86)\\GPSBabel\gpsbabel.exe";
695 vlpd.s = "C:\\Program Files\\GPSBabel\\gpsbabel.exe";
699 a_preferences_register(&prefs[0], vlpd, VIKING_PREFERENCES_IO_GROUP_KEY);
701 // Read the current preference
702 const gchar *gpsbabel = a_preferences_get(VIKING_PREFERENCES_IO_NAMESPACE "gpsbabel")->s;
703 // If setting is still the UNIX default then lookup in the path - otherwise attempt to use the specified value directly.
704 if ( g_strcmp0 ( gpsbabel, "gpsbabel" ) == 0 ) {
705 gpsbabel_loc = g_find_program_in_path( "gpsbabel" );
707 g_critical( "gpsbabel not found in PATH" );
710 gpsbabel_loc = (gchar*)gpsbabel;
712 // Unlikely to package unbuffer on Windows so ATM don't even bother trying
713 // Highly unlikely unbuffer is available on a Windows system otherwise
715 unbuffer_loc = g_find_program_in_path( "unbuffer" );
717 g_warning( "unbuffer not found in PATH" );
726 * Free resources acquired by a_babel_init.
728 void a_babel_uninit ()
730 g_free ( gpsbabel_loc );
731 g_free ( unbuffer_loc );
733 if ( a_babel_file_list ) {
735 for (gl = a_babel_file_list; gl != NULL; gl = g_list_next(gl)) {
736 BabelFile *file = gl->data;
737 g_free ( file->name );
738 g_free ( file->ext );
739 g_free ( file->label );
742 g_list_free ( a_babel_file_list );
745 if ( a_babel_device_list ) {
747 for (gl = a_babel_device_list; gl != NULL; gl = g_list_next(gl)) {
748 BabelDevice *device = gl->data;
749 g_free ( device->name );
750 g_free ( device->label );
753 g_list_free ( a_babel_device_list );
761 * Indicates if babel is available or not.
763 * Returns: true if babel available
765 gboolean a_babel_available ()
767 return a_babel_device_list != NULL;