fish: Add 'display' command for displaying graphical files.
[libguestfs.git] / fish / display.c
1 /* guestfish - the filesystem interactive shell
2  * Copyright (C) 2011 Red Hat Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  */
18
19 #include <config.h>
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <inttypes.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29
30 #include "fish.h"
31
32 int
33 run_display (const char *cmd, size_t argc, char *argv[])
34 {
35   TMP_TEMPLATE_ON_STACK (filename);
36   char *remote;
37   const char *display;
38   char buf[256];
39   int r, fd;
40
41   if (argc != 1) {
42     fprintf (stderr, _("display filename\n"));
43     return -1;
44   }
45
46   /* Choose a display command. */
47   display = getenv ("GUESTFISH_DISPLAY_IMAGE");
48   if (display == NULL)
49     display = "display";
50
51   remote = argv[0];
52
53   /* Allow win:... prefix on remote. */
54   remote = win_prefix (remote);
55   if (remote == NULL)
56     return -1;
57
58   /* Download the file and write it to a temporary. */
59   fd = mkstemp (filename);
60   if (fd == -1) {
61     perror ("mkstemp");
62     free (remote);
63     return -1;
64   }
65
66   snprintf (buf, sizeof buf, "/dev/fd/%d", fd);
67
68   if (guestfs_download (g, remote, buf) == -1) {
69     close (fd);
70     unlink (filename);
71     free (remote);
72     return -1;
73   }
74
75   if (close (fd) == -1) {
76     perror (filename);
77     unlink (filename);
78     free (remote);
79     return -1;
80   }
81
82   /* View it. */
83   snprintf (buf, sizeof buf, "%s %s", display, filename);
84
85   r = system (buf);
86   unlink (filename);
87   if (r != 0) {
88     perror (buf);
89     free (remote);
90     return -1;
91   }
92
93   free (remote);
94   return 0;
95 }