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;
78 * @vt: The TRW layer to modify. All data will be deleted, and replaced by what gpsbabel outputs.
79 * @babelargs: A string containing gpsbabel command line filter options. No file types or names should
81 * @cb: A callback function.
82 * @user_data: passed along to cb
83 * @not_used: Must use NULL
85 * This function modifies data in a trw layer using gpsbabel filters. This routine is synchronous;
86 * that is, it will block the calling program until the conversion is done. To avoid blocking, call
87 * this routine from a worker thread.
89 * Returns: %TRUE on success
91 gboolean a_babel_convert( VikTrwLayer *vt, const char *babelargs, BabelStatusFunc cb, gpointer user_data, gpointer not_used )
95 gchar *name_src = NULL;
97 gchar *bargs = g_strconcat(babelargs, " -i gpx", NULL);
99 if ((fd_src = g_file_open_tmp("tmp-viking.XXXXXX", &name_src, NULL)) >= 0) {
100 g_debug ("%s: temporary file: %s", __FUNCTION__, name_src);
101 f = fdopen(fd_src, "w");
102 a_gpx_write_file(vt, f, NULL);
105 ret = a_babel_convert_from ( vt, bargs, name_src, cb, user_data, not_used );
115 * Perform any cleanup actions once GPSBabel has completed running
117 static void babel_watch ( GPid pid,
121 g_spawn_close_pid ( pid );
125 * babel_general_convert:
126 * @args: The command line arguments passed to GPSBabel
127 * @cb: callback that is run for each line of GPSBabel output and at completion of the run
128 * callback may be NULL
129 * @user_data: passed along to cb
131 * The function to actually invoke the GPSBabel external command
133 * Returns: %TRUE on successful invocation of GPSBabel command
135 static gboolean babel_general_convert( BabelStatusFunc cb, gchar **args, gpointer user_data )
137 gboolean ret = FALSE;
139 GError *error = NULL;
142 if (!g_spawn_async_with_pipes (NULL, args, NULL, G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL, &pid, NULL, &babel_stdout, NULL, &error)) {
143 g_warning ("Async command failed: %s", error->message);
150 diag = fdopen(babel_stdout, "r");
151 setvbuf(diag, NULL, _IONBF, 0);
153 while (fgets(line, sizeof(line), diag)) {
155 cb(BABEL_DIAG_OUTPUT, line, user_data);
158 cb(BABEL_DONE, NULL, user_data);
162 g_child_watch_add ( pid, (GChildWatchFunc) babel_watch, NULL );
171 * babel_general_convert_from:
172 * @vtl: The TrackWaypoint Layer to save the data into
173 * If it is null it signifies that no data is to be processed,
174 * however the gpsbabel command is still ran as it can be for non-data related options eg:
175 * for use with the power off command - 'command_off'
176 * @cb: callback that is run upon new data from STDOUT (?)
177 * (TODO: STDERR would be nice since we usually redirect STDOUT)
178 * @user_data: passed along to cb
180 * Runs args[0] with the arguments and uses the GPX module
181 * to import the GPX data into layer vt. Assumes that upon
182 * running the command, the data will appear in the (usually
183 * temporary) file name_dst.
185 * Returns: %TRUE on success
187 static gboolean babel_general_convert_from( VikTrwLayer *vt, BabelStatusFunc cb, gchar **args, const gchar *name_dst, gpointer user_data )
189 gboolean ret = FALSE;
192 if (babel_general_convert(cb, args, user_data)) {
194 /* No data actually required but still need to have run gpsbabel anyway
195 - eg using the device power command_off */
199 f = g_fopen(name_dst, "r");
201 ret = a_gpx_read_file ( vt, f );
211 * a_babel_convert_from:
212 * @vt: The TRW layer to place data into. Duplicate items will be overwritten.
213 * @babelargs: A string containing gpsbabel command line options. In addition to any filters, this string
214 * must include the input file type (-i) option.
215 * @cb: Optional callback function. Same usage as in a_babel_convert().
216 * @user_data: passed along to cb
217 * @not_used: Must use NULL
219 * Loads data into a trw layer from a file, using gpsbabel. This routine is synchronous;
220 * that is, it will block the calling program until the conversion is done. To avoid blocking, call
221 * this routine from a worker thread.
223 * Returns: %TRUE on success
225 gboolean a_babel_convert_from( VikTrwLayer *vt, const char *babelargs, const char *from, BabelStatusFunc cb, gpointer user_data, gpointer not_used )
229 gchar *name_dst = NULL;
230 gboolean ret = FALSE;
233 if ((fd_dst = g_file_open_tmp("tmp-viking.XXXXXX", &name_dst, NULL)) >= 0) {
234 g_debug ("%s: temporary file: %s", __FUNCTION__, name_dst);
238 gchar **sub_args = g_strsplit(babelargs, " ", 0);
242 args[i++] = unbuffer_loc;
243 args[i++] = gpsbabel_loc;
244 for (j = 0; sub_args[j]; j++) {
245 /* some version of gpsbabel can not take extra blank arg */
246 if (sub_args[j][0] != '\0')
247 args[i++] = sub_args[j];
252 args[i++] = (char *)from;
254 args[i++] = name_dst;
257 ret = babel_general_convert_from ( vt, cb, args, name_dst, user_data );
259 g_strfreev(sub_args);
261 g_critical("gpsbabel not found in PATH");
270 * a_babel_convert_from_shellcommand:
271 * @vt: The #VikTrwLayer where to insert the collected data
272 * @input_cmd: the command to run
273 * @cb: Optional callback function. Same usage as in a_babel_convert().
274 * @user_data: passed along to cb
275 * @not_used: Must use NULL
277 * Runs the input command in a shell (bash) and optionally uses GPSBabel to convert from input_file_type.
278 * If input_file_type is %NULL, doesn't use GPSBabel. Input must be GPX (or Geocaching *.loc)
280 * Uses babel_general_convert_from() to actually run the command. This function
281 * prepares the command and temporary file, and sets up the arguments for bash.
283 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 )
286 gchar *name_dst = NULL;
287 gboolean ret = FALSE;
290 if ((fd_dst = g_file_open_tmp("tmp-viking.XXXXXX", &name_dst, NULL)) >= 0) {
291 g_debug ("%s: temporary file: %s", __FUNCTION__, name_dst);
292 gchar *shell_command;
293 if ( input_file_type )
294 shell_command = g_strdup_printf("%s | %s -i %s -f - -o gpx -F %s",
295 input_cmd, gpsbabel_loc, input_file_type, name_dst);
297 shell_command = g_strdup_printf("%s > %s", input_cmd, name_dst);
299 g_debug("%s: %s", __FUNCTION__, shell_command);
302 args = g_malloc(sizeof(gchar *)*4);
303 args[0] = BASH_LOCATION;
305 args[2] = shell_command;
308 ret = babel_general_convert_from ( vt, cb, args, name_dst, user_data );
310 g_free ( shell_command );
319 * a_babel_convert_from_url:
320 * @vt: The #VikTrwLayer where to insert the collected data
321 * @url: the URL to fetch
322 * @cb: Optional callback function. Same usage as in a_babel_convert().
323 * @user_data: passed along to cb
324 * @options: download options. Maybe NULL.
326 * Download the file pointed by the URL and optionally uses GPSBabel to convert from input_file_type.
327 * If input_file_type is %NULL, doesn't use GPSBabel. Input must be GPX.
329 * Returns: %TRUE on successful invocation of GPSBabel or read of the GPX
332 gboolean a_babel_convert_from_url ( VikTrwLayer *vt, const char *url, const char *input_type, BabelStatusFunc cb, gpointer user_data, DownloadMapOptions *options )
334 // If no download options specified, use defaults:
335 DownloadMapOptions myoptions = { FALSE, FALSE, NULL, 2, NULL, NULL, NULL };
337 myoptions = *options;
340 gboolean ret = FALSE;
341 gchar *name_src = NULL;
342 gchar *babelargs = NULL;
344 g_debug("%s: input_type=%s url=%s", __FUNCTION__, input_type, url);
346 if ((fd_src = g_file_open_tmp("tmp-viking.XXXXXX", &name_src, NULL)) >= 0) {
347 g_debug ("%s: temporary file: %s", __FUNCTION__, name_src);
351 fetch_ret = a_http_download_get_url(url, "", name_src, &myoptions, NULL);
352 if (fetch_ret == 0) {
353 if (input_type != NULL) {
354 babelargs = g_strdup_printf(" -i %s", input_type);
355 ret = a_babel_convert_from( vt, babelargs, name_src, NULL, NULL, NULL );
357 /* Process directly the retrieved file */
358 g_debug("%s: directly read GPX file %s", __FUNCTION__, name_src);
359 FILE *f = g_fopen(name_src, "r");
361 ret = a_gpx_read_file ( vt, f );
376 * a_babel_convert_from_url_or_shell:
377 * @vt: The #VikTrwLayer where to insert the collected data
378 * @url: the URL to fetch
379 * @cb: Optional callback function. Same usage as in a_babel_convert().
380 * @user_data: passed along to cb
381 * @options: download options. Maybe NULL.
383 * Download the file pointed by the URL and optionally uses GPSBabel to convert from input_file_type.
384 * If input_file_type is %NULL, doesn't use GPSBabel. Input must be GPX.
386 * Returns: %TRUE on successful invocation of GPSBabel or read of the GPX
389 gboolean a_babel_convert_from_url_or_shell ( VikTrwLayer *vt, const char *input, const char *input_type, BabelStatusFunc cb, gpointer user_data, DownloadMapOptions *options )
392 /* Check nature of input */
393 gboolean isUrl = FALSE;
395 for (i = 0 ; PROTOS[i] != NULL ; i++)
397 const gchar *proto = PROTOS[i];
398 if (strncmp (input, proto, strlen(proto)) == 0)
400 /* Procotol matches: save result */
407 return a_babel_convert_from_url (vt, input, input_type, cb, user_data, options);
409 return a_babel_convert_from_shellcommand (vt, input, input_type, cb, user_data, options);
412 static gboolean babel_general_convert_to( VikTrwLayer *vt, VikTrack *trk, BabelStatusFunc cb, gchar **args, const gchar *name_src, gpointer user_data )
414 // Now strips out invisible tracks and waypoints
415 if (!a_file_export(vt, name_src, FILE_TYPE_GPX, trk, FALSE)) {
416 g_critical("Error exporting to %s", name_src);
420 return babel_general_convert (cb, args, user_data);
424 * a_babel_convert_to:
425 * @vt: The TRW layer from which data is taken.
426 * @track: Operate on the individual track if specified. Use NULL when operating on a TRW layer
427 * @babelargs: A string containing gpsbabel command line options. In addition to any filters, this string
428 * must include the input file type (-i) option.
429 * @to: Filename or device the data is written to.
430 * @cb: Optional callback function. Same usage as in a_babel_convert.
431 * @user_data: passed along to cb
433 * Exports data using gpsbabel. This routine is synchronous;
434 * that is, it will block the calling program until the conversion is done. To avoid blocking, call
435 * this routine from a worker thread.
437 * Returns: %TRUE on successful invocation of GPSBabel command
439 gboolean a_babel_convert_to( VikTrwLayer *vt, VikTrack *track, const char *babelargs, const char *to, BabelStatusFunc cb, gpointer user_data )
443 gchar *name_src = NULL;
444 gboolean ret = FALSE;
447 if ((fd_src = g_file_open_tmp("tmp-viking.XXXXXX", &name_src, NULL)) >= 0) {
448 g_debug ("%s: temporary file: %s", __FUNCTION__, name_src);
452 gchar **sub_args = g_strsplit(babelargs, " ", 0);
456 args[i++] = unbuffer_loc;
457 args[i++] = gpsbabel_loc;
460 for (j = 0; sub_args[j]; j++)
461 /* some version of gpsbabel can not take extra blank arg */
462 if (sub_args[j][0] != '\0')
463 args[i++] = sub_args[j];
465 args[i++] = name_src;
467 args[i++] = (char *)to;
470 ret = babel_general_convert_to ( vt, track, cb, args, name_src, user_data );
472 g_strfreev(sub_args);
474 g_critical("gpsbabel not found in PATH");
482 static void set_mode(BabelMode mode, gchar *smode)
484 mode.waypointsRead = smode[0] == 'r';
485 mode.waypointsWrite = smode[1] == 'w';
486 mode.tracksRead = smode[2] == 'r';
487 mode.tracksWrite = smode[3] == 'w';
488 mode.routesRead = smode[4] == 'r';
489 mode.routesWrite = smode[5] == 'w';
493 * load_feature_parse_line:
495 * Load a single feature stored in the given line.
497 static void load_feature_parse_line (gchar *line)
499 gchar **tokens = g_strsplit ( line, "\t", 0 );
501 && tokens[0] != NULL ) {
502 if ( strcmp("serial", tokens[0]) == 0 ) {
503 if ( tokens[1] != NULL
506 && tokens[4] != NULL ) {
507 BabelDevice *device = g_malloc ( sizeof (BabelDevice) );
508 set_mode (device->mode, tokens[1]);
509 device->name = g_strdup (tokens[2]);
510 device->label = g_strndup (tokens[4], 50); // Limit really long label text
511 a_babel_device_list = g_list_append (a_babel_device_list, device);
512 g_debug ("New gpsbabel device: %s", device->name);
514 g_warning ( "Unexpected gpsbabel format string: %s", line);
516 } else if ( strcmp("file", tokens[0]) == 0 ) {
517 if ( tokens[1] != NULL
520 && tokens[4] != NULL ) {
521 BabelFile *file = g_malloc ( sizeof (BabelFile) );
522 set_mode (file->mode, tokens[1]);
523 file->name = g_strdup (tokens[2]);
524 file->ext = g_strdup (tokens[3]);
525 file->label = g_strdup (tokens[4]);
526 a_babel_file_list = g_list_append (a_babel_file_list, file);
527 g_debug ("New gpsbabel file: %s", file->name);
529 g_warning ( "Unexpected gpsbabel format string: %s", line);
533 g_warning ( "Unexpected gpsbabel format string: %s", line);
535 g_strfreev ( tokens );
538 static void load_feature_cb (BabelProgressCode code, gpointer line, gpointer user_data)
541 load_feature_parse_line (line);
544 static gboolean load_feature ()
547 gboolean ret = FALSE;
550 if ( gpsbabel_loc ) {
553 args[i++] = unbuffer_loc;
554 args[i++] = gpsbabel_loc;
558 ret = babel_general_convert (load_feature_cb, args, NULL);
560 g_critical("gpsbabel not found in PATH");
568 * Initialises babel module.
569 * Mainly check existence of gpsbabel progam
570 * and load all features available in ths version.
574 /* TODO allow to set gpsbabel path via command line */
575 gpsbabel_loc = g_find_program_in_path( "gpsbabel" );
577 g_critical( "gpsbabel not found in PATH" );
579 // Unlikely to package unbuffer on Windows so ATM don't even bother trying
580 // Highly unlikely unbuffer is available on a Windows system otherwise
582 unbuffer_loc = g_find_program_in_path( "unbuffer" );
584 g_warning( "unbuffer not found in PATH" );
593 * Free resources acquired by a_babel_init.
595 void a_babel_uninit ()
597 g_free ( gpsbabel_loc );
598 g_free ( unbuffer_loc );
600 if ( a_babel_file_list ) {
602 for (gl = a_babel_file_list; gl != NULL; gl = g_list_next(gl)) {
603 BabelFile *file = gl->data;
604 g_free ( file->name );
605 g_free ( file->ext );
606 g_free ( file->label );
609 g_list_free ( a_babel_file_list );
612 if ( a_babel_device_list ) {
614 for (gl = a_babel_device_list; gl != NULL; gl = g_list_next(gl)) {
615 BabelDevice *device = gl->data;
616 g_free ( device->name );
617 g_free ( device->label );
620 g_list_free ( a_babel_device_list );