]> www.fi.muni.cz Git - evince.git/blob - libdocument/ev-file-helpers.c
67e884a4ee4e47959c135dc3bfb0a4dae7f10ba8
[evince.git] / libdocument / ev-file-helpers.c
1 /*
2  *  Copyright (C) 2002 Jorn Baayen
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, or (at your option)
7  *  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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17  *
18  *  $Id$
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif
24
25 #include <stdlib.h>
26 #include <sys/types.h>
27 #include <unistd.h>
28 #include <string.h>
29 #include <glib.h>
30 #include <glib/gstdio.h>
31 #include <errno.h>
32
33 #include "ev-file-helpers.h"
34
35 static gchar *tmp_dir = NULL;
36 static gint   count = 0;
37
38 gboolean
39 ev_dir_ensure_exists (const gchar *dir,
40                       int          mode)
41 {
42         if (g_mkdir_with_parents (dir, mode) == 0)
43                 return TRUE;
44
45         if (errno == EEXIST)
46                 return g_file_test (dir, G_FILE_TEST_IS_DIR);
47         
48         g_warning ("Failed to create directory %s: %s", dir, g_strerror (errno));
49         return FALSE;
50 }
51
52 const gchar *
53 ev_tmp_dir (void)
54 {
55         if (tmp_dir == NULL) {
56                 gboolean exists;
57                 gchar   *dirname, *prgname;
58
59                 prgname = g_get_prgname ();
60                 dirname = g_strdup_printf ("%s-%u", prgname ? prgname : "unknown", getpid ());
61                 tmp_dir = g_build_filename (g_get_tmp_dir (),
62                                             dirname,
63                                             NULL);
64                 g_free (dirname);
65
66                 exists = ev_dir_ensure_exists (tmp_dir, 0700);
67                 g_assert (exists);
68         }
69
70         return tmp_dir;
71 }
72
73 void
74 _ev_file_helpers_init (void)
75 {
76 }
77
78 void
79 _ev_file_helpers_shutdown (void)
80 {       
81         if (tmp_dir != NULL)    
82                 g_rmdir (tmp_dir);
83
84         g_free (tmp_dir);
85         tmp_dir = NULL;
86 }
87
88 GFile *
89 ev_tmp_file_get (const gchar *prefix)
90 {
91         gchar *path;
92         GFile *file;
93
94         path = ev_tmp_filename (prefix);
95         file = g_file_new_for_path (path);
96         
97         g_free (path);
98         
99         return file;
100 }
101
102 gchar * 
103 ev_tmp_filename (const gchar *prefix)
104 {
105         gchar *basename;
106         gchar *filename = NULL;
107
108         do {
109                 if (filename != NULL)
110                         g_free (filename);
111                         
112                 basename = g_strdup_printf ("%s-%d",
113                                             prefix ? prefix : "document",
114                                             count ++);
115                 
116                 filename = g_build_filename (ev_tmp_dir (),
117                                              basename, NULL);
118                 
119                 g_free (basename);
120         } while (g_file_test (filename, G_FILE_TEST_EXISTS));
121                         
122         return filename;
123 }
124
125 /* Remove a local temp file created by evince */
126 void
127 ev_tmp_filename_unlink (const gchar *filename)
128 {
129         const gchar *tempdir;
130         
131         if (!filename)
132                 return;
133
134         tempdir = g_get_tmp_dir ();
135         if (g_ascii_strncasecmp (filename, tempdir, strlen (tempdir)) == 0) {
136                 g_unlink (filename);
137         }
138 }
139
140 void
141 ev_tmp_file_unlink (GFile *file)
142 {
143         gboolean res;
144         GError  *error = NULL;
145
146         if (!file)
147                 return;
148         
149         res = g_file_delete (file, NULL, &error);
150         if (!res) {
151                 char *uri;
152                 
153                 uri = g_file_get_uri (file);
154                 g_warning ("Unable to delete temp file %s: %s\n", uri, error->message);
155                 g_free (uri);
156                 g_error_free (error);
157         }
158 }
159
160 void
161 ev_tmp_uri_unlink (const gchar *uri)
162 {
163         GFile *file;
164         
165         if (!uri)
166                 return;
167         
168         file = g_file_new_for_uri (uri);
169         if (!g_file_is_native (file)) {
170                 g_warning ("Attempting to delete non native uri: %s\n", uri);
171                 g_object_unref (file);
172                 return;
173         }
174         
175         ev_tmp_file_unlink (file);
176         g_object_unref (file);
177 }
178
179 /**
180  * ev_xfer_uri_simple:
181  * @from: the source URI
182  * @to: the target URI
183  * @error: a #GError location to store an error, or %NULL
184  *
185  * Performs a g_file_copy() from @from to @to.
186  *
187  * Returns: %TRUE on success, or %FALSE on error with @error filled in
188  */
189 gboolean
190 ev_xfer_uri_simple (const char *from,
191                     const char *to,
192                     GError     **error)
193 {
194         GFile *source_file;
195         GFile *target_file;
196         gboolean result;
197         
198         if (!from)
199                 return TRUE;
200
201         g_return_val_if_fail (to != NULL, TRUE);
202
203         source_file = g_file_new_for_uri (from);
204         target_file = g_file_new_for_uri (to);
205         
206         result = g_file_copy (source_file, target_file,
207 #if GLIB_CHECK_VERSION(2,19,0)
208                               G_FILE_COPY_TARGET_DEFAULT_PERMS |
209 #endif
210                               G_FILE_COPY_OVERWRITE,
211                               NULL, NULL, NULL, error);
212
213         g_object_unref (target_file);
214         g_object_unref (source_file);
215     
216         return result;
217 }
218
219 static gchar *
220 get_mime_type_from_uri (const gchar *uri, GError **error)
221 {
222         GFile       *file;
223         GFileInfo   *file_info;
224         const gchar *content_type;
225         gchar       *mime_type = NULL;
226
227         file = g_file_new_for_uri (uri);
228         file_info = g_file_query_info (file,
229                                        G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE,
230                                        0, NULL, error);
231         g_object_unref (file);
232
233         if (file_info == NULL)
234                 return NULL;
235
236         content_type = g_file_info_get_content_type (file_info);
237         if (content_type) {
238                 mime_type = g_content_type_get_mime_type (content_type);
239         }
240
241         g_object_unref (file_info);
242         return mime_type;
243 }
244
245 static gchar *
246 get_mime_type_from_data (const gchar *uri, GError **error)
247 {
248         GFile            *file;
249         GFileInputStream *input_stream;
250         gssize            size_read;
251         guchar            buffer[1024];
252         gboolean          retval;
253         gchar            *content_type, *mime_type;
254
255         file = g_file_new_for_uri (uri);
256         
257         input_stream = g_file_read (file, NULL, error);
258         if (!input_stream) {
259                 g_object_unref (file);
260                 return NULL;
261         }
262
263         size_read = g_input_stream_read (G_INPUT_STREAM (input_stream),
264                                          buffer, sizeof (buffer), NULL, error);
265         if (size_read == -1) {
266                 g_object_unref (input_stream);
267                 g_object_unref (file);
268                 return NULL;
269         }
270
271         retval = g_input_stream_close (G_INPUT_STREAM (input_stream), NULL, error);
272
273         g_object_unref (input_stream);
274         g_object_unref (file);
275         if (!retval)
276                 return NULL;
277
278         content_type = g_content_type_guess (NULL, /* no filename */
279                                              buffer, size_read,
280                                              NULL);
281         if (!content_type)
282                 return NULL;
283
284         mime_type = g_content_type_get_mime_type (content_type);
285         g_free (content_type);
286         return mime_type;
287 }
288
289 /**
290  * ev_file_get_mime_type:
291  * @uri: the URI
292  * @fast: whether to use fast MIME type detection
293  * @error: a #GError location to store an error, or %NULL
294  *
295  * Note: on unknown MIME types, this may return NULL without @error
296  * being filled in.
297  * 
298  * Returns: a newly allocated string with the MIME type of the file at
299  *   @uri, or %NULL on error or if the MIME type could not be determined
300  */
301 gchar *
302 ev_file_get_mime_type (const gchar *uri,
303                        gboolean     fast,
304                        GError     **error)
305 {
306         return fast ? get_mime_type_from_uri (uri, error) : get_mime_type_from_data (uri, error);
307 }
308
309 /* Compressed files support */
310 #define BZIPCOMMAND "bzip2"
311 #define GZIPCOMMAND "gzip"
312 #define N_ARGS      4
313 #define BUFFER_SIZE 1024
314
315 static gchar *
316 compression_run (const gchar       *uri,
317                  EvCompressionType  type,
318                  gboolean           compress, 
319                  GError           **error)
320 {
321         gchar *argv[N_ARGS];
322         gchar *uri_dst = NULL;
323         gchar *filename, *filename_dst;
324         gchar *cmd;
325         gint   fd, pout;
326         GError *err = NULL;
327
328         if (type == EV_COMPRESSION_NONE)
329                 return NULL;
330
331         cmd = g_find_program_in_path ((type == EV_COMPRESSION_BZIP2) ? BZIPCOMMAND : GZIPCOMMAND);
332         if (!cmd) {
333                 /* FIXME: better error codes! */
334                 /* FIXME: i18n later */
335                 g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
336                              "Failed to find the \"%s\" command in the search path.",
337                              type == EV_COMPRESSION_BZIP2 ? BZIPCOMMAND : GZIPCOMMAND);
338                 return NULL;
339         }
340
341         filename = g_filename_from_uri (uri, NULL, error);
342         if (!filename) {
343                 g_free (cmd);
344                 return NULL;
345         }
346         
347         filename_dst = g_build_filename (ev_tmp_dir (), "evinceXXXXXX", NULL);
348         fd = g_mkstemp (filename_dst);
349         if (fd < 0) {
350                 int errsv = errno;
351
352                 g_free (cmd);
353                 g_free (filename);
354                 g_free (filename_dst);
355
356                 g_set_error (error, G_IO_ERROR,
357                              g_io_error_from_errno (errsv),
358                              "Error creating a temporary file: %s",
359                              g_strerror (errsv));
360                 return NULL;
361         }
362
363         argv[0] = cmd;
364         argv[1] = compress ? "-c" : "-cd";
365         argv[2] = filename;
366         argv[3] = NULL;
367
368         if (g_spawn_async_with_pipes (NULL, argv, NULL,
369                                       G_SPAWN_STDERR_TO_DEV_NULL,
370                                       NULL, NULL, NULL,
371                                       NULL, &pout, NULL, &err)) {
372                 GIOChannel *in, *out;
373                 gchar buf[BUFFER_SIZE];
374                 GIOStatus read_st, write_st;
375                 gsize bytes_read, bytes_written;
376
377                 in = g_io_channel_unix_new (pout);
378                 g_io_channel_set_encoding (in, NULL, NULL);
379                 out = g_io_channel_unix_new (fd);
380                 g_io_channel_set_encoding (out, NULL, NULL);
381
382                 do {
383                         read_st = g_io_channel_read_chars (in, buf,
384                                                            BUFFER_SIZE,
385                                                            &bytes_read,
386                                                            error);
387                         if (read_st == G_IO_STATUS_NORMAL) {
388                                 write_st = g_io_channel_write_chars (out, buf,
389                                                                      bytes_read,
390                                                                      &bytes_written,
391                                                                      error);
392                                 if (write_st == G_IO_STATUS_ERROR)
393                                         break;
394                         } else if (read_st == G_IO_STATUS_ERROR) {
395                                 break;
396                         }
397                 } while (bytes_read > 0);
398
399                 g_io_channel_unref (in);
400                 g_io_channel_unref (out);
401         }
402
403         close (fd);
404
405         if (err) {
406                 g_propagate_error (error, err);
407         } else {
408                 uri_dst = g_filename_to_uri (filename_dst, NULL, error);
409         }
410
411         g_free (cmd);
412         g_free (filename);
413         g_free (filename_dst);
414
415         return uri_dst;
416 }
417
418 /**
419  * ev_file_uncompress:
420  * @uri: a file URI
421  * @type: the compression type
422  * @error: a #GError location to store an error, or %NULL
423  *
424  * Uncompresses the file at @uri.
425  *
426  * If @type is %EV_COMPRESSION_NONE, it does nothing and returns %NULL.
427  *
428  * Otherwise, it returns the filename of a
429  * temporary file containing the decompressed data from the file at @uri.
430  * On error it returns %NULL and fills in @error.
431  *
432  * It is the caller's responsibility to unlink the temp file after use.
433  *
434  * Returns: a newly allocated string URI, or %NULL on error
435  */
436 gchar *
437 ev_file_uncompress (const gchar       *uri,
438                     EvCompressionType  type,
439                     GError           **error)
440 {
441         g_return_val_if_fail (uri != NULL, NULL);
442
443         return compression_run (uri, type, FALSE, error);
444 }
445
446 /**
447  * ev_file_compress:
448  * @uri: a file URI
449  * @type: the compression type
450  * @error: a #GError location to store an error, or %NULL
451  *
452  * Compresses the file at @uri.
453  
454  * If @type is %EV_COMPRESSION_NONE, it does nothing and returns %NULL.
455  *
456  * Otherwise, it returns the filename of a
457  * temporary file containing the compressed data from the file at @uri.
458  *
459  * On error it returns %NULL and fills in @error.
460  *
461  * It is the caller's responsibility to unlink the temp file after use.
462  *
463  * Returns: a newly allocated string URI, or %NULL on error
464  */
465 gchar *
466 ev_file_compress (const gchar       *uri,
467                   EvCompressionType  type,
468                   GError           **error)
469 {
470         g_return_val_if_fail (uri != NULL, NULL);
471
472         return compression_run (uri, type, TRUE, error);
473 }