1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8; c-indent-level: 8 -*- */
3 * Copyright (C) 2009-2010 Juanjo Marín <juanj.marin@juntadeandalucia.es>
4 * Copyright (C) 2005, Teemu Tervo <teemu.tervo@gmx.net>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2, or (at your option)
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
29 #include <glib/gi18n-lib.h>
30 #include <glib/gstdio.h>
34 # define WIFEXITED(x) ((x) != 3)
35 # define WEXITSTATUS(x) (x)
37 # include <sys/wait.h>
40 #include "comics-document.h"
41 #include "ev-document-misc.h"
42 #include "ev-document-thumbnails.h"
43 #include "ev-file-helpers.h"
46 /* On windows g_spawn_command_line_sync reads stdout in O_BINARY mode, not in O_TEXT mode.
47 * As a consequence, newlines are in a platform dependent representation (\r\n). This
48 * might be considered a bug in glib.
62 } ComicBookDecompressType;
64 typedef struct _ComicsDocumentClass ComicsDocumentClass;
66 struct _ComicsDocumentClass
68 EvDocumentClass parent_class;
71 struct _ComicsDocument
73 EvDocument parent_instance;
76 GPtrArray *page_names;
77 gchar *selected_command, *alternative_command;
78 gchar *extract_command, *list_command, *decompress_tmp;
81 ComicBookDecompressType command_usage;
88 /* For perfomance reasons of 7z* we've choosen to decompress on the temporary
89 * directory instead of decompressing on the stdout */
92 * @extract: command line arguments to pass to extract a file from the archive
94 * @list: command line arguments to list the archive contents
95 * @decompress_tmp: command line arguments to pass to extract the archive
97 * @regex_arg: whether the command can accept regex expressions
98 * @offset: the position offset of the filename on each line in the output of
99 * running the @list command
104 char *decompress_tmp;
107 } ComicBookDecompressCommand;
109 static const ComicBookDecompressCommand command_usage_def[] = {
111 {"%s p -c- -ierr --", "%s vb -c- -- %s", NULL , FALSE, NO_OFFSET},
114 {NULL , "%s t %s" , "%s -xf %s %s" , FALSE, NO_OFFSET},
117 {"%s -p -C --" , "%s %s" , NULL , TRUE , OFFSET_ZIP},
120 {NULL , "%s l -- %s" , "%s x -y %s -o%s", FALSE, OFFSET_7Z},
123 {"%s -xOf" , "%s -tf %s" , NULL , FALSE, NO_OFFSET}
126 static void comics_document_document_thumbnails_iface_init (EvDocumentThumbnailsInterface *iface);
128 static GSList* get_supported_image_extensions (void);
129 static void get_page_size_area_prepared_cb (GdkPixbufLoader *loader,
131 static void render_pixbuf_size_prepared_cb (GdkPixbufLoader *loader,
135 static char** extract_argv (EvDocument *document,
139 EV_BACKEND_REGISTER_WITH_CODE (ComicsDocument, comics_document,
141 EV_BACKEND_IMPLEMENT_INTERFACE (EV_TYPE_DOCUMENT_THUMBNAILS,
142 comics_document_document_thumbnails_iface_init);
146 * comics_regex_quote:
147 * @unquoted_string: a literal string
149 * Quotes a string so unzip will not interpret the regex expressions of
150 * @unquoted_string. Basically, this functions uses [] to disable regex
151 * expressions. The return value must be freed with * g_free()
153 * Return value: quoted and disabled-regex string
156 comics_regex_quote (const gchar *unquoted_string)
161 dest = g_string_new ("'");
167 /* * matches a sequence of 0 or more characters */
169 /* ? matches exactly 1 charactere */
171 /* [...] matches any single character found inside
172 * the brackets. Disabling the first bracket is enough.
175 g_string_append (dest, "[");
176 g_string_append_c (dest, *p);
177 g_string_append (dest, "]");
179 /* Because \ escapes regex expressions that we are
180 * disabling for unzip, we need to disable \ too */
182 g_string_append (dest, "[\\\\]");
184 /* Escape single quote inside the string */
186 g_string_append (dest, "'\\''");
189 g_string_append_c (dest, *p);
194 g_string_append_c (dest, '\'');
195 return g_string_free (dest, FALSE);
199 /* This function manages the command for decompressing a comic book */
201 comics_decompress_temp_dir (const gchar *command_decompress_tmp,
202 const gchar *command,
206 gchar *std_out, *basename;
210 success = g_spawn_command_line_sync (command_decompress_tmp, &std_out,
211 NULL, &retval, &err);
212 basename = g_path_get_basename (command);
216 EV_DOCUMENT_ERROR_INVALID,
217 _("Error launching the command “%s” in order to "
218 "decompress the comic book: %s"),
222 } else if (WIFEXITED (retval)) {
223 if (WEXITSTATUS (retval) == EXIT_SUCCESS) {
230 EV_DOCUMENT_ERROR_INVALID,
231 _("The command “%s” failed at "
232 "decompressing the comic book."),
239 EV_DOCUMENT_ERROR_INVALID,
240 _("The command “%s” did not end normally."),
248 /* This function shows how to use the choosen command for decompressing a
249 * comic book file. It modifies fields of the ComicsDocument struct with
250 * this information */
252 comics_generate_command_lines (ComicsDocument *comics_document,
256 gchar *quoted_command;
257 ComicBookDecompressType type;
259 type = comics_document->command_usage;
260 comics_document->regex_arg = command_usage_def[type].regex_arg;
261 quoted_command = g_shell_quote (comics_document->selected_command);
262 if (comics_document->regex_arg) {
263 quoted_file = comics_regex_quote (comics_document->archive);
264 comics_document->list_command =
265 g_strdup_printf (command_usage_def[type].list,
266 comics_document->alternative_command,
267 comics_document->archive);
269 quoted_file = g_shell_quote (comics_document->archive);
270 comics_document->list_command =
271 g_strdup_printf (command_usage_def[type].list,
272 quoted_command, quoted_file);
274 comics_document->extract_command =
275 g_strdup_printf (command_usage_def[type].extract,
277 comics_document->offset = command_usage_def[type].offset;
278 if (command_usage_def[type].decompress_tmp) {
279 comics_document->dir = ev_mkdtemp ("evince-comics-XXXXXX", error);
280 if (comics_document->dir == NULL)
283 /* unrar-free can't create directories, but ev_mkdtemp already created the dir */
285 comics_document->decompress_tmp =
286 g_strdup_printf (command_usage_def[type].decompress_tmp,
287 quoted_command, quoted_file,
288 comics_document->dir);
289 g_free (quoted_file);
290 g_free (quoted_command);
292 if (!comics_decompress_temp_dir (comics_document->decompress_tmp,
293 comics_document->selected_command, error))
298 g_free (quoted_file);
299 g_free (quoted_command);
305 /* This function chooses an external command for decompressing a comic
306 * book based on its mime tipe. */
308 comics_check_decompress_command (gchar *mime_type,
309 ComicsDocument *comics_document,
313 gchar *std_out, *std_err;
317 /* FIXME, use proper cbr/cbz mime types once they're
318 * included in shared-mime-info */
320 if (!strcmp (mime_type, "application/x-cbr") ||
321 !strcmp (mime_type, "application/x-rar")) {
322 /* The RARLAB provides a no-charge proprietary (freeware)
323 * decompress-only client for Linux called unrar. Another
324 * option is a GPLv2-licensed command-line tool developed by
325 * the Gna! project. Confusingly enough, the free software RAR
326 * decoder is also named unrar. For this reason we need to add
327 * some lines for disambiguation. Sorry for the added the
328 * complexity but it's life :)
329 * Finally, some distributions, like Debian, rename this free
330 * option as unrar-free.
332 comics_document->selected_command =
333 g_find_program_in_path ("unrar");
334 if (comics_document->selected_command) {
335 /* We only use std_err to avoid printing useless error
336 * messages on the terminal */
338 g_spawn_command_line_sync (
339 comics_document->selected_command,
343 g_propagate_error (error, err);
346 /* I don't check retval status because RARLAB unrar
347 * doesn't have a way to return 0 without involving an
348 * operation with a file*/
349 } else if (WIFEXITED (retval)) {
350 if (g_strrstr (std_out,"freeware") != NULL)
351 /* The RARLAB freeware client */
352 comics_document->command_usage = RARLABS;
354 /* The Gna! free software client */
355 comics_document->command_usage = GNAUNRAR;
362 /* The Gna! free software client with Debian naming convention */
363 comics_document->selected_command =
364 g_find_program_in_path ("unrar-free");
365 if (comics_document->selected_command) {
366 comics_document->command_usage = GNAUNRAR;
370 } else if (!strcmp (mime_type, "application/x-cbz") ||
371 !strcmp (mime_type, "application/zip")) {
372 /* InfoZIP's unzip program */
373 comics_document->selected_command =
374 g_find_program_in_path ("unzip");
375 comics_document->alternative_command =
376 g_find_program_in_path ("zipnote");
377 if (comics_document->selected_command &&
378 comics_document->alternative_command) {
379 comics_document->command_usage = UNZIP;
383 } else if (!strcmp (mime_type, "application/x-cb7") ||
384 !strcmp (mime_type, "application/x-7z-compressed")) {
385 /* 7zr, 7za and 7z are the commands from the p7zip project able
386 * to decompress .7z files */
387 comics_document->selected_command =
388 g_find_program_in_path ("7zr");
389 if (comics_document->selected_command) {
390 comics_document->command_usage = P7ZIP;
393 comics_document->selected_command =
394 g_find_program_in_path ("7za");
395 if (comics_document->selected_command) {
396 comics_document->command_usage = P7ZIP;
399 comics_document->selected_command =
400 g_find_program_in_path ("7z");
401 if (comics_document->selected_command) {
402 comics_document->command_usage = P7ZIP;
405 } else if (!strcmp (mime_type, "application/x-cbt") ||
406 !strcmp (mime_type, "application/x-tar")) {
407 /* tar utility (Tape ARchive) */
408 comics_document->selected_command =
409 g_find_program_in_path ("tar");
410 if (comics_document->selected_command) {
411 comics_document->command_usage = TAR;
417 EV_DOCUMENT_ERROR_INVALID,
418 _("Not a comic book MIME type: %s"),
422 g_set_error_literal (error,
424 EV_DOCUMENT_ERROR_INVALID,
425 _("Can't find an appropriate command to "
426 "decompress this type of comic book"));
431 sort_page_names (gconstpointer a,
434 return strcmp (* (const char **) a, * (const char **) b);
438 comics_document_load (EvDocument *document,
442 ComicsDocument *comics_document = COMICS_DOCUMENT (document);
443 GSList *supported_extensions;
446 gchar **cb_files, *cb_file;
451 comics_document->archive = g_filename_from_uri (uri, NULL, error);
452 if (!comics_document->archive)
455 mime_type = ev_file_get_mime_type (uri, FALSE, &err);
458 g_propagate_error (error, err);
460 g_set_error_literal (error,
462 EV_DOCUMENT_ERROR_INVALID,
463 _("Unknown MIME Type"));
469 if (!comics_check_decompress_command (mime_type, comics_document,
473 } else if (!comics_generate_command_lines (comics_document, error)) {
480 /* Get list of files in archive */
481 success = g_spawn_command_line_sync (comics_document->list_command,
482 &std_out, NULL, &retval, error);
486 } else if (!WIFEXITED(retval) || WEXITSTATUS(retval) != EXIT_SUCCESS) {
487 g_set_error_literal (error,
489 EV_DOCUMENT_ERROR_INVALID,
490 _("File corrupted"));
494 /* FIXME: is this safe against filenames containing \n in the archive ? */
495 cb_files = g_strsplit (std_out, EV_EOL, 0);
500 g_set_error_literal (error,
502 EV_DOCUMENT_ERROR_INVALID,
503 _("No files in archive"));
507 comics_document->page_names = g_ptr_array_sized_new (64);
509 supported_extensions = get_supported_image_extensions ();
510 for (i = 0; cb_files[i] != NULL; i++) {
511 if (comics_document->offset != NO_OFFSET) {
512 if (g_utf8_strlen (cb_files[i],-1) >
513 comics_document->offset) {
515 g_utf8_offset_to_pointer (cb_files[i],
516 comics_document->offset);
521 cb_file = cb_files[i];
523 gchar *suffix = g_strrstr (cb_file, ".");
526 suffix = g_ascii_strdown (suffix + 1, -1);
527 if (g_slist_find_custom (supported_extensions, suffix,
528 (GCompareFunc) strcmp) != NULL) {
529 g_ptr_array_add (comics_document->page_names,
530 g_strstrip (g_strdup (cb_file)));
534 g_strfreev (cb_files);
535 g_slist_foreach (supported_extensions, (GFunc) g_free, NULL);
536 g_slist_free (supported_extensions);
538 if (comics_document->page_names->len == 0) {
541 EV_DOCUMENT_ERROR_INVALID,
542 _("No images found in archive %s"),
547 /* Now sort the pages */
548 g_ptr_array_sort (comics_document->page_names, sort_page_names);
555 comics_document_save (EvDocument *document,
559 ComicsDocument *comics_document = COMICS_DOCUMENT (document);
561 return ev_xfer_uri_simple (comics_document->archive, uri, error);
565 comics_document_get_n_pages (EvDocument *document)
567 ComicsDocument *comics_document = COMICS_DOCUMENT (document);
569 if (comics_document->page_names == NULL)
572 return comics_document->page_names->len;
576 comics_document_get_page_size (EvDocument *document,
581 GdkPixbufLoader *loader;
584 gboolean success, got_size = FALSE;
590 ComicsDocument *comics_document = COMICS_DOCUMENT (document);
592 if (!comics_document->decompress_tmp) {
593 argv = extract_argv (document, page->index);
594 success = g_spawn_async_with_pipes (NULL, argv, NULL,
595 G_SPAWN_SEARCH_PATH |
596 G_SPAWN_STDERR_TO_DEV_NULL,
599 NULL, &outpipe, NULL, NULL);
601 g_return_if_fail (success == TRUE);
603 loader = gdk_pixbuf_loader_new ();
604 g_signal_connect (loader, "area-prepared",
605 G_CALLBACK (get_page_size_area_prepared_cb),
608 while (outpipe >= 0) {
609 bytes = read (outpipe, buf, 1024);
612 gdk_pixbuf_loader_write (loader, buf, bytes, NULL);
613 if (bytes <= 0 || got_size) {
616 gdk_pixbuf_loader_close (loader, NULL);
620 if (gdk_pixbuf_loader_get_pixbuf (loader)) {
621 pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);
623 *width = gdk_pixbuf_get_width (pixbuf);
625 *height = gdk_pixbuf_get_height (pixbuf);
628 g_spawn_close_pid (child_pid);
629 g_object_unref (loader);
631 filename = g_build_filename (comics_document->dir,
632 (char *) comics_document->page_names->pdata[page->index],
634 pixbuf = gdk_pixbuf_new_from_file (filename, NULL);
637 *width = gdk_pixbuf_get_width (pixbuf);
639 *height = gdk_pixbuf_get_height (pixbuf);
644 get_page_size_area_prepared_cb (GdkPixbufLoader *loader,
647 gboolean *got_size = data;
652 comics_document_render_pixbuf (EvDocument *document,
655 GdkPixbufLoader *loader;
656 GdkPixbuf *rotated_pixbuf;
665 ComicsDocument *comics_document = COMICS_DOCUMENT (document);
667 if (!comics_document->decompress_tmp) {
668 argv = extract_argv (document, rc->page->index);
669 success = g_spawn_async_with_pipes (NULL, argv, NULL,
670 G_SPAWN_SEARCH_PATH |
671 G_SPAWN_STDERR_TO_DEV_NULL,
674 NULL, &outpipe, NULL, NULL);
676 g_return_val_if_fail (success == TRUE, NULL);
678 loader = gdk_pixbuf_loader_new ();
679 g_signal_connect (loader, "size-prepared",
680 G_CALLBACK (render_pixbuf_size_prepared_cb),
683 while (outpipe >= 0) {
684 bytes = read (outpipe, buf, 4096);
687 gdk_pixbuf_loader_write (loader, buf, bytes,
689 } else if (bytes <= 0) {
691 gdk_pixbuf_loader_close (loader, NULL);
696 rotated_pixbuf = gdk_pixbuf_rotate_simple (
697 gdk_pixbuf_loader_get_pixbuf (loader),
699 g_spawn_close_pid (child_pid);
700 g_object_unref (loader);
703 g_build_filename (comics_document->dir,
704 (char *) comics_document->page_names->pdata[rc->page->index],
707 gdk_pixbuf_get_file_info (filename, &width, &height);
710 gdk_pixbuf_rotate_simple (gdk_pixbuf_new_from_file_at_size (
711 filename, width * (rc->scale) + 0.5,
712 height * (rc->scale) + 0.5, NULL),
717 return rotated_pixbuf;
720 static cairo_surface_t *
721 comics_document_render (EvDocument *document,
725 cairo_surface_t *surface;
727 pixbuf = comics_document_render_pixbuf (document, rc);
728 surface = ev_document_misc_surface_from_pixbuf (pixbuf);
729 g_object_unref (pixbuf);
735 render_pixbuf_size_prepared_cb (GdkPixbufLoader *loader,
740 double *scale = data;
741 int w = (width * (*scale) + 0.5);
742 int h = (height * (*scale) + 0.5);
744 gdk_pixbuf_loader_set_size (loader, w, h);
748 * comics_remove_dir: Removes a directory recursively.
750 * 0 if it was successfully deleted,
751 * -1 if an error occurred
754 comics_remove_dir (gchar *path_name)
757 const gchar *filename;
758 gchar *filename_with_path;
760 if (g_file_test (path_name, G_FILE_TEST_IS_DIR)) {
761 content_dir = g_dir_open (path_name, 0, NULL);
762 filename = g_dir_read_name (content_dir);
765 g_build_filename (path_name,
767 comics_remove_dir (filename_with_path);
768 g_free (filename_with_path);
769 filename = g_dir_read_name (content_dir);
771 g_dir_close (content_dir);
773 /* Note from g_remove() documentation: on Windows, it is in general not
774 * possible to remove a file that is open to some process, or mapped
776 return (g_remove (path_name));
780 comics_document_finalize (GObject *object)
782 ComicsDocument *comics_document = COMICS_DOCUMENT (object);
784 if (comics_document->decompress_tmp) {
785 if (comics_remove_dir (comics_document->dir) == -1)
786 g_warning (_("There was an error deleting “%s”."),
787 comics_document->dir);
788 g_free (comics_document->dir);
791 if (comics_document->page_names) {
792 g_ptr_array_foreach (comics_document->page_names, (GFunc) g_free, NULL);
793 g_ptr_array_free (comics_document->page_names, TRUE);
796 g_free (comics_document->archive);
797 g_free (comics_document->selected_command);
798 g_free (comics_document->alternative_command);
799 g_free (comics_document->extract_command);
800 g_free (comics_document->list_command);
802 G_OBJECT_CLASS (comics_document_parent_class)->finalize (object);
806 comics_document_class_init (ComicsDocumentClass *klass)
808 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
809 EvDocumentClass *ev_document_class = EV_DOCUMENT_CLASS (klass);
811 gobject_class->finalize = comics_document_finalize;
813 ev_document_class->load = comics_document_load;
814 ev_document_class->save = comics_document_save;
815 ev_document_class->get_n_pages = comics_document_get_n_pages;
816 ev_document_class->get_page_size = comics_document_get_page_size;
817 ev_document_class->render = comics_document_render;
821 comics_document_init (ComicsDocument *comics_document)
823 comics_document->archive = NULL;
824 comics_document->page_names = NULL;
825 comics_document->extract_command = NULL;
828 /* Returns a list of file extensions supported by gdk-pixbuf */
830 get_supported_image_extensions()
832 GSList *extensions = NULL;
833 GSList *formats = gdk_pixbuf_get_formats ();
836 for (l = formats; l != NULL; l = l->next) {
838 gchar **ext = gdk_pixbuf_format_get_extensions (l->data);
840 for (i = 0; ext[i] != NULL; i++) {
841 extensions = g_slist_append (extensions,
848 g_slist_free (formats);
853 comics_document_thumbnails_get_thumbnail (EvDocumentThumbnails *document,
857 GdkPixbuf *thumbnail;
859 thumbnail = comics_document_render_pixbuf (EV_DOCUMENT (document), rc);
862 GdkPixbuf *tmp_pixbuf = thumbnail;
864 thumbnail = ev_document_misc_get_thumbnail_frame (-1, -1, tmp_pixbuf);
865 g_object_unref (tmp_pixbuf);
872 comics_document_thumbnails_get_dimensions (EvDocumentThumbnails *document,
877 gdouble page_width, page_height;
879 comics_document_get_page_size (EV_DOCUMENT (document), rc->page,
880 &page_width, &page_height);
882 if (rc->rotation == 90 || rc->rotation == 270) {
883 *width = (gint) (page_height * rc->scale);
884 *height = (gint) (page_width * rc->scale);
886 *width = (gint) (page_width * rc->scale);
887 *height = (gint) (page_height * rc->scale);
892 comics_document_document_thumbnails_iface_init (EvDocumentThumbnailsInterface *iface)
894 iface->get_thumbnail = comics_document_thumbnails_get_thumbnail;
895 iface->get_dimensions = comics_document_thumbnails_get_dimensions;
899 extract_argv (EvDocument *document, gint page)
901 ComicsDocument *comics_document = COMICS_DOCUMENT (document);
903 char *command_line, *quoted_archive, *quoted_filename;
906 if (page >= comics_document->page_names->len)
909 if (comics_document->regex_arg) {
910 quoted_archive = comics_regex_quote (comics_document->archive);
912 comics_regex_quote (comics_document->page_names->pdata[page]);
914 quoted_archive = g_shell_quote (comics_document->archive);
915 quoted_filename = g_shell_quote (comics_document->page_names->pdata[page]);
918 command_line = g_strdup_printf ("%s %s %s",
919 comics_document->extract_command,
922 g_shell_parse_argv (command_line, NULL, &argv, &err);
925 g_warning (_("Error %s"), err->message);
930 g_free (command_line);
931 g_free (quoted_archive);
932 g_free (quoted_filename);