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