]> www.fi.muni.cz Git - evince.git/blob - libdocument/ev-file-helpers.c
Make sure to fill in @error on failure. Also, since this is exported in
[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 gboolean
180 ev_xfer_uri_simple (const char *from,
181                     const char *to,
182                     GError     **error)
183 {
184         GFile *source_file;
185         GFile *target_file;
186         GError *ioerror = NULL;
187         gboolean result;
188         
189         if (!from)
190                 return FALSE;
191         
192         source_file = g_file_new_for_uri (from);
193         target_file = g_file_new_for_uri (to);
194         
195         result = g_file_copy (source_file, target_file,
196 #if GLIB_CHECK_VERSION(2,19,0)
197                               G_FILE_COPY_TARGET_DEFAULT_PERMS |
198 #endif
199                               G_FILE_COPY_OVERWRITE,
200                               NULL, NULL, NULL, &ioerror);
201
202         g_object_unref (target_file);
203         g_object_unref (source_file);
204     
205         if (!result) {
206                 g_propagate_error (error, ioerror);
207         }
208         return result;
209
210 }
211
212 static gchar *
213 get_mime_type_from_uri (const gchar *uri, GError **error)
214 {
215         GFile       *file;
216         GFileInfo   *file_info;
217         const gchar *content_type;
218
219         file = g_file_new_for_uri (uri);
220         file_info = g_file_query_info (file,
221                                        G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE,
222                                        0, NULL, error);
223         g_object_unref (file);
224
225         if (file_info == NULL)
226                 return NULL;
227
228         content_type = g_file_info_get_content_type (file_info);
229         g_object_unref (file_info);
230
231         if (!content_type)
232                 return NULL;
233
234         return g_content_type_get_mime_type (content_type);
235 }
236
237 static gchar *
238 get_mime_type_from_data (const gchar *uri, GError **error)
239 {
240         GFile            *file;
241         GFileInputStream *input_stream;
242         gssize            size_read;
243         guchar            buffer[1024];
244         gboolean          retval;
245         gchar            *content_type, *mime_type;
246
247         file = g_file_new_for_uri (uri);
248         
249         input_stream = g_file_read (file, NULL, error);
250         if (!input_stream) {
251                 g_object_unref (file);
252                 return NULL;
253         }
254
255         size_read = g_input_stream_read (G_INPUT_STREAM (input_stream),
256                                          buffer, sizeof (buffer), NULL, error);
257         if (size_read == -1) {
258                 g_object_unref (input_stream);
259                 g_object_unref (file);
260                 return NULL;
261         }
262
263         retval = g_input_stream_close (G_INPUT_STREAM (input_stream), NULL, error);
264
265         g_object_unref (input_stream);
266         g_object_unref (file);
267         if (!retval)
268                 return NULL;
269
270         content_type = g_content_type_guess (NULL, /* no filename */
271                                              buffer, size_read,
272                                              NULL);
273         if (!content_type)
274                 return NULL;
275
276         mime_type = g_content_type_get_mime_type (content_type);
277         g_free (content_type);
278         return mime_type;
279 }
280
281 /**
282  * ev_file_get_mime_type:
283  * @uri: the URI
284  * @fast: whether to use fast MIME type detection
285  * @error: a #GError location to store an error, or %NULL
286  *
287  * Note: on unknown MIME types, this may return NULL without @error
288  * being filled in.
289  * 
290  * Returns: a newly allocated string with the MIME type of the file at
291  *   @uri, or %NULL on error or if the MIME type could not be determined
292  */
293 gchar *
294 ev_file_get_mime_type (const gchar *uri,
295                        gboolean     fast,
296                        GError     **error)
297 {
298         return fast ? get_mime_type_from_uri (uri, error) : get_mime_type_from_data (uri, error);
299 }
300
301 /* Compressed files support */
302 #define BZIPCOMMAND "bzip2"
303 #define GZIPCOMMAND "gzip"
304 #define N_ARGS      4
305 #define BUFFER_SIZE 1024
306
307 static gchar *
308 compression_run (const gchar       *uri,
309                  EvCompressionType  type,
310                  gboolean           compress, 
311                  GError           **error)
312 {
313         gchar *argv[N_ARGS];
314         gchar *uri_dst = NULL;
315         gchar *filename, *filename_dst;
316         gchar *cmd;
317         gint   fd, pout;
318         GError *err = NULL;
319
320         if (type == EV_COMPRESSION_NONE)
321                 return NULL;
322
323         cmd = g_find_program_in_path ((type == EV_COMPRESSION_BZIP2) ? BZIPCOMMAND : GZIPCOMMAND);
324         if (!cmd) {
325                 /* FIXME: better error codes! */
326                 /* FIXME: i18n later */
327                 g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
328                              "Failed to find the \"%s\" command in the search path.",
329                              type == EV_COMPRESSION_BZIP2 ? BZIPCOMMAND : GZIPCOMMAND);
330                 return NULL;
331         }
332
333         filename = g_filename_from_uri (uri, NULL, error);
334         if (!filename) {
335                 g_free (cmd);
336                 return NULL;
337         }
338         
339         filename_dst = g_build_filename (ev_tmp_dir (), "evinceXXXXXX", NULL);
340         fd = g_mkstemp (filename_dst);
341         if (fd < 0) {
342                 int errsv = errno;
343
344                 g_free (cmd);
345                 g_free (filename);
346                 g_free (filename_dst);
347
348                 g_set_error (error, G_IO_ERROR,
349                              g_io_error_from_errno (errsv),
350                              "Error creating a temporary file: %s",
351                              g_strerror (errsv));
352                 return NULL;
353         }
354
355         argv[0] = cmd;
356         argv[1] = compress ? "-c" : "-cd";
357         argv[2] = filename;
358         argv[3] = NULL;
359
360         if (g_spawn_async_with_pipes (NULL, argv, NULL,
361                                       G_SPAWN_STDERR_TO_DEV_NULL,
362                                       NULL, NULL, NULL,
363                                       NULL, &pout, NULL, &err)) {
364                 GIOChannel *in, *out;
365                 gchar buf[BUFFER_SIZE];
366                 GIOStatus read_st, write_st;
367                 gsize bytes_read, bytes_written;
368
369                 in = g_io_channel_unix_new (pout);
370                 g_io_channel_set_encoding (in, NULL, NULL);
371                 out = g_io_channel_unix_new (fd);
372                 g_io_channel_set_encoding (out, NULL, NULL);
373
374                 do {
375                         read_st = g_io_channel_read_chars (in, buf,
376                                                            BUFFER_SIZE,
377                                                            &bytes_read,
378                                                            error);
379                         if (read_st == G_IO_STATUS_NORMAL) {
380                                 write_st = g_io_channel_write_chars (out, buf,
381                                                                      bytes_read,
382                                                                      &bytes_written,
383                                                                      error);
384                                 if (write_st == G_IO_STATUS_ERROR)
385                                         break;
386                         } else if (read_st == G_IO_STATUS_ERROR) {
387                                 break;
388                         }
389                 } while (bytes_read > 0);
390
391                 g_io_channel_unref (in);
392                 g_io_channel_unref (out);
393         }
394
395         close (fd);
396
397         if (err) {
398                 g_propagate_error (error, err);
399         } else {
400                 uri_dst = g_filename_to_uri (filename_dst, NULL, error);
401         }
402
403         g_free (cmd);
404         g_free (filename);
405         g_free (filename_dst);
406
407         return uri_dst;
408 }
409
410 /**
411  * ev_file_uncompress:
412  * @uri: a file URI
413  * @type: the compression type
414  * @error: a #GError location to store an error, or %NULL
415  *
416  * Uncompresses the file at @uri.
417  *
418  * If @type is %EV_COMPRESSION_NONE, it does nothing and returns %NULL.
419  *
420  * Otherwise, it returns the filename of a
421  * temporary file containing the decompressed data from the file at @uri.
422  * On error it returns %NULL and fills in @error.
423  *
424  * It is the caller's responsibility to unlink the temp file after use.
425  *
426  * Returns: a newly allocated string URI, or %NULL on error
427  */
428 gchar *
429 ev_file_uncompress (const gchar       *uri,
430                     EvCompressionType  type,
431                     GError           **error)
432 {
433         g_return_val_if_fail (uri != NULL, NULL);
434
435         return compression_run (uri, type, FALSE, error);
436 }
437
438 /**
439  * ev_file_compress:
440  * @uri: a file URI
441  * @type: the compression type
442  * @error: a #GError location to store an error, or %NULL
443  *
444  * Compresses the file at @uri.
445  
446  * If @type is %EV_COMPRESSION_NONE, it does nothing and returns %NULL.
447  *
448  * Otherwise, it returns the filename of a
449  * temporary file containing the compressed data from the file at @uri.
450  *
451  * On error it returns %NULL and fills in @error.
452  *
453  * It is the caller's responsibility to unlink the temp file after use.
454  *
455  * Returns: a newly allocated string URI, or %NULL on error
456  */
457 gchar *
458 ev_file_compress (const gchar       *uri,
459                   EvCompressionType  type,
460                   GError           **error)
461 {
462         g_return_val_if_fail (uri != NULL, NULL);
463
464         return compression_run (uri, type, TRUE, error);
465 }