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,
255 gchar *quoted_file, *quoted_file_aux;
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 quoted_file_aux = g_shell_quote (comics_document->archive);
265 comics_document->list_command =
266 g_strdup_printf (command_usage_def[type].list,
267 comics_document->alternative_command,
269 g_free (quoted_file_aux);
271 quoted_file = g_shell_quote (comics_document->archive);
272 comics_document->list_command =
273 g_strdup_printf (command_usage_def[type].list,
274 quoted_command, quoted_file);
276 comics_document->extract_command =
277 g_strdup_printf (command_usage_def[type].extract,
279 comics_document->offset = command_usage_def[type].offset;
280 if (command_usage_def[type].decompress_tmp) {
281 comics_document->dir = ev_mkdtemp ("evince-comics-XXXXXX", error);
282 if (comics_document->dir == NULL)
285 /* unrar-free can't create directories, but ev_mkdtemp already created the dir */
287 comics_document->decompress_tmp =
288 g_strdup_printf (command_usage_def[type].decompress_tmp,
289 quoted_command, quoted_file,
290 comics_document->dir);
291 g_free (quoted_file);
292 g_free (quoted_command);
294 if (!comics_decompress_temp_dir (comics_document->decompress_tmp,
295 comics_document->selected_command, error))
300 g_free (quoted_file);
301 g_free (quoted_command);
307 /* This function chooses an external command for decompressing a comic
308 * book based on its mime tipe. */
310 comics_check_decompress_command (gchar *mime_type,
311 ComicsDocument *comics_document,
315 gchar *std_out, *std_err;
319 /* FIXME, use proper cbr/cbz mime types once they're
320 * included in shared-mime-info */
322 if (!strcmp (mime_type, "application/x-cbr") ||
323 !strcmp (mime_type, "application/x-rar")) {
324 /* The RARLAB provides a no-charge proprietary (freeware)
325 * decompress-only client for Linux called unrar. Another
326 * option is a GPLv2-licensed command-line tool developed by
327 * the Gna! project. Confusingly enough, the free software RAR
328 * decoder is also named unrar. For this reason we need to add
329 * some lines for disambiguation. Sorry for the added the
330 * complexity but it's life :)
331 * Finally, some distributions, like Debian, rename this free
332 * option as unrar-free.
334 comics_document->selected_command =
335 g_find_program_in_path ("unrar");
336 if (comics_document->selected_command) {
337 /* We only use std_err to avoid printing useless error
338 * messages on the terminal */
340 g_spawn_command_line_sync (
341 comics_document->selected_command,
345 g_propagate_error (error, err);
348 /* I don't check retval status because RARLAB unrar
349 * doesn't have a way to return 0 without involving an
350 * operation with a file*/
351 } else if (WIFEXITED (retval)) {
352 if (g_strrstr (std_out,"freeware") != NULL)
353 /* The RARLAB freeware client */
354 comics_document->command_usage = RARLABS;
356 /* The Gna! free software client */
357 comics_document->command_usage = GNAUNRAR;
364 /* The Gna! free software client with Debian naming convention */
365 comics_document->selected_command =
366 g_find_program_in_path ("unrar-free");
367 if (comics_document->selected_command) {
368 comics_document->command_usage = GNAUNRAR;
372 } else if (!strcmp (mime_type, "application/x-cbz") ||
373 !strcmp (mime_type, "application/zip")) {
374 /* InfoZIP's unzip program */
375 comics_document->selected_command =
376 g_find_program_in_path ("unzip");
377 comics_document->alternative_command =
378 g_find_program_in_path ("zipnote");
379 if (comics_document->selected_command &&
380 comics_document->alternative_command) {
381 comics_document->command_usage = UNZIP;
385 } else if (!strcmp (mime_type, "application/x-cb7") ||
386 !strcmp (mime_type, "application/x-7z-compressed")) {
387 /* 7zr, 7za and 7z are the commands from the p7zip project able
388 * to decompress .7z files */
389 comics_document->selected_command =
390 g_find_program_in_path ("7zr");
391 if (comics_document->selected_command) {
392 comics_document->command_usage = P7ZIP;
395 comics_document->selected_command =
396 g_find_program_in_path ("7za");
397 if (comics_document->selected_command) {
398 comics_document->command_usage = P7ZIP;
401 comics_document->selected_command =
402 g_find_program_in_path ("7z");
403 if (comics_document->selected_command) {
404 comics_document->command_usage = P7ZIP;
407 } else if (!strcmp (mime_type, "application/x-cbt") ||
408 !strcmp (mime_type, "application/x-tar")) {
409 /* tar utility (Tape ARchive) */
410 comics_document->selected_command =
411 g_find_program_in_path ("tar");
412 if (comics_document->selected_command) {
413 comics_document->command_usage = TAR;
419 EV_DOCUMENT_ERROR_INVALID,
420 _("Not a comic book MIME type: %s"),
424 g_set_error_literal (error,
426 EV_DOCUMENT_ERROR_INVALID,
427 _("Can't find an appropriate command to "
428 "decompress this type of comic book"));
433 sort_page_names (gconstpointer a,
436 return strcmp (* (const char **) a, * (const char **) b);
440 comics_document_load (EvDocument *document,
444 ComicsDocument *comics_document = COMICS_DOCUMENT (document);
445 GSList *supported_extensions;
448 gchar **cb_files, *cb_file;
453 comics_document->archive = g_filename_from_uri (uri, NULL, error);
454 if (!comics_document->archive)
457 mime_type = ev_file_get_mime_type (uri, FALSE, &err);
460 g_propagate_error (error, err);
462 g_set_error_literal (error,
464 EV_DOCUMENT_ERROR_INVALID,
465 _("Unknown MIME Type"));
471 if (!comics_check_decompress_command (mime_type, comics_document,
475 } else if (!comics_generate_command_lines (comics_document, error)) {
482 /* Get list of files in archive */
483 success = g_spawn_command_line_sync (comics_document->list_command,
484 &std_out, NULL, &retval, error);
488 } else if (!WIFEXITED(retval) || WEXITSTATUS(retval) != EXIT_SUCCESS) {
489 g_set_error_literal (error,
491 EV_DOCUMENT_ERROR_INVALID,
492 _("File corrupted"));
496 /* FIXME: is this safe against filenames containing \n in the archive ? */
497 cb_files = g_strsplit (std_out, EV_EOL, 0);
502 g_set_error_literal (error,
504 EV_DOCUMENT_ERROR_INVALID,
505 _("No files in archive"));
509 comics_document->page_names = g_ptr_array_sized_new (64);
511 supported_extensions = get_supported_image_extensions ();
512 for (i = 0; cb_files[i] != NULL; i++) {
513 if (comics_document->offset != NO_OFFSET) {
514 if (g_utf8_strlen (cb_files[i],-1) >
515 comics_document->offset) {
517 g_utf8_offset_to_pointer (cb_files[i],
518 comics_document->offset);
523 cb_file = cb_files[i];
525 gchar *suffix = g_strrstr (cb_file, ".");
528 suffix = g_ascii_strdown (suffix + 1, -1);
529 if (g_slist_find_custom (supported_extensions, suffix,
530 (GCompareFunc) strcmp) != NULL) {
531 g_ptr_array_add (comics_document->page_names,
532 g_strstrip (g_strdup (cb_file)));
536 g_strfreev (cb_files);
537 g_slist_foreach (supported_extensions, (GFunc) g_free, NULL);
538 g_slist_free (supported_extensions);
540 if (comics_document->page_names->len == 0) {
543 EV_DOCUMENT_ERROR_INVALID,
544 _("No images found in archive %s"),
549 /* Now sort the pages */
550 g_ptr_array_sort (comics_document->page_names, sort_page_names);
557 comics_document_save (EvDocument *document,
561 ComicsDocument *comics_document = COMICS_DOCUMENT (document);
563 return ev_xfer_uri_simple (comics_document->archive, uri, error);
567 comics_document_get_n_pages (EvDocument *document)
569 ComicsDocument *comics_document = COMICS_DOCUMENT (document);
571 if (comics_document->page_names == NULL)
574 return comics_document->page_names->len;
578 comics_document_get_page_size (EvDocument *document,
583 GdkPixbufLoader *loader;
586 gboolean success, got_size = FALSE;
592 ComicsDocument *comics_document = COMICS_DOCUMENT (document);
594 if (!comics_document->decompress_tmp) {
595 argv = extract_argv (document, page->index);
596 success = g_spawn_async_with_pipes (NULL, argv, NULL,
597 G_SPAWN_SEARCH_PATH |
598 G_SPAWN_STDERR_TO_DEV_NULL,
601 NULL, &outpipe, NULL, NULL);
603 g_return_if_fail (success == TRUE);
605 loader = gdk_pixbuf_loader_new ();
606 g_signal_connect (loader, "area-prepared",
607 G_CALLBACK (get_page_size_area_prepared_cb),
610 while (outpipe >= 0) {
611 bytes = read (outpipe, buf, 1024);
614 gdk_pixbuf_loader_write (loader, buf, bytes, NULL);
615 if (bytes <= 0 || got_size) {
618 gdk_pixbuf_loader_close (loader, NULL);
622 if (gdk_pixbuf_loader_get_pixbuf (loader)) {
623 pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);
625 *width = gdk_pixbuf_get_width (pixbuf);
627 *height = gdk_pixbuf_get_height (pixbuf);
630 g_spawn_close_pid (child_pid);
631 g_object_unref (loader);
633 filename = g_build_filename (comics_document->dir,
634 (char *) comics_document->page_names->pdata[page->index],
636 pixbuf = gdk_pixbuf_new_from_file (filename, NULL);
639 *width = gdk_pixbuf_get_width (pixbuf);
641 *height = gdk_pixbuf_get_height (pixbuf);
646 get_page_size_area_prepared_cb (GdkPixbufLoader *loader,
649 gboolean *got_size = data;
654 comics_document_render_pixbuf (EvDocument *document,
657 GdkPixbufLoader *loader;
658 GdkPixbuf *rotated_pixbuf;
667 ComicsDocument *comics_document = COMICS_DOCUMENT (document);
669 if (!comics_document->decompress_tmp) {
670 argv = extract_argv (document, rc->page->index);
671 success = g_spawn_async_with_pipes (NULL, argv, NULL,
672 G_SPAWN_SEARCH_PATH |
673 G_SPAWN_STDERR_TO_DEV_NULL,
676 NULL, &outpipe, NULL, NULL);
678 g_return_val_if_fail (success == TRUE, NULL);
680 loader = gdk_pixbuf_loader_new ();
681 g_signal_connect (loader, "size-prepared",
682 G_CALLBACK (render_pixbuf_size_prepared_cb),
685 while (outpipe >= 0) {
686 bytes = read (outpipe, buf, 4096);
689 gdk_pixbuf_loader_write (loader, buf, bytes,
691 } else if (bytes <= 0) {
693 gdk_pixbuf_loader_close (loader, NULL);
698 rotated_pixbuf = gdk_pixbuf_rotate_simple (
699 gdk_pixbuf_loader_get_pixbuf (loader),
701 g_spawn_close_pid (child_pid);
702 g_object_unref (loader);
705 g_build_filename (comics_document->dir,
706 (char *) comics_document->page_names->pdata[rc->page->index],
709 gdk_pixbuf_get_file_info (filename, &width, &height);
712 gdk_pixbuf_rotate_simple (gdk_pixbuf_new_from_file_at_size (
713 filename, width * (rc->scale) + 0.5,
714 height * (rc->scale) + 0.5, NULL),
719 return rotated_pixbuf;
722 static cairo_surface_t *
723 comics_document_render (EvDocument *document,
727 cairo_surface_t *surface;
729 pixbuf = comics_document_render_pixbuf (document, rc);
730 surface = ev_document_misc_surface_from_pixbuf (pixbuf);
731 g_object_unref (pixbuf);
737 render_pixbuf_size_prepared_cb (GdkPixbufLoader *loader,
742 double *scale = data;
743 int w = (width * (*scale) + 0.5);
744 int h = (height * (*scale) + 0.5);
746 gdk_pixbuf_loader_set_size (loader, w, h);
750 * comics_remove_dir: Removes a directory recursively.
752 * 0 if it was successfully deleted,
753 * -1 if an error occurred
756 comics_remove_dir (gchar *path_name)
759 const gchar *filename;
760 gchar *filename_with_path;
762 if (g_file_test (path_name, G_FILE_TEST_IS_DIR)) {
763 content_dir = g_dir_open (path_name, 0, NULL);
764 filename = g_dir_read_name (content_dir);
767 g_build_filename (path_name,
769 comics_remove_dir (filename_with_path);
770 g_free (filename_with_path);
771 filename = g_dir_read_name (content_dir);
773 g_dir_close (content_dir);
775 /* Note from g_remove() documentation: on Windows, it is in general not
776 * possible to remove a file that is open to some process, or mapped
778 return (g_remove (path_name));
782 comics_document_finalize (GObject *object)
784 ComicsDocument *comics_document = COMICS_DOCUMENT (object);
786 if (comics_document->decompress_tmp) {
787 if (comics_remove_dir (comics_document->dir) == -1)
788 g_warning (_("There was an error deleting “%s”."),
789 comics_document->dir);
790 g_free (comics_document->dir);
793 if (comics_document->page_names) {
794 g_ptr_array_foreach (comics_document->page_names, (GFunc) g_free, NULL);
795 g_ptr_array_free (comics_document->page_names, TRUE);
798 g_free (comics_document->archive);
799 g_free (comics_document->selected_command);
800 g_free (comics_document->alternative_command);
801 g_free (comics_document->extract_command);
802 g_free (comics_document->list_command);
804 G_OBJECT_CLASS (comics_document_parent_class)->finalize (object);
808 comics_document_class_init (ComicsDocumentClass *klass)
810 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
811 EvDocumentClass *ev_document_class = EV_DOCUMENT_CLASS (klass);
813 gobject_class->finalize = comics_document_finalize;
815 ev_document_class->load = comics_document_load;
816 ev_document_class->save = comics_document_save;
817 ev_document_class->get_n_pages = comics_document_get_n_pages;
818 ev_document_class->get_page_size = comics_document_get_page_size;
819 ev_document_class->render = comics_document_render;
823 comics_document_init (ComicsDocument *comics_document)
825 comics_document->archive = NULL;
826 comics_document->page_names = NULL;
827 comics_document->extract_command = NULL;
830 /* Returns a list of file extensions supported by gdk-pixbuf */
832 get_supported_image_extensions()
834 GSList *extensions = NULL;
835 GSList *formats = gdk_pixbuf_get_formats ();
838 for (l = formats; l != NULL; l = l->next) {
840 gchar **ext = gdk_pixbuf_format_get_extensions (l->data);
842 for (i = 0; ext[i] != NULL; i++) {
843 extensions = g_slist_append (extensions,
850 g_slist_free (formats);
855 comics_document_thumbnails_get_thumbnail (EvDocumentThumbnails *document,
859 GdkPixbuf *thumbnail;
861 thumbnail = comics_document_render_pixbuf (EV_DOCUMENT (document), rc);
864 GdkPixbuf *tmp_pixbuf = thumbnail;
866 thumbnail = ev_document_misc_get_thumbnail_frame (-1, -1, tmp_pixbuf);
867 g_object_unref (tmp_pixbuf);
874 comics_document_thumbnails_get_dimensions (EvDocumentThumbnails *document,
879 gdouble page_width, page_height;
881 comics_document_get_page_size (EV_DOCUMENT (document), rc->page,
882 &page_width, &page_height);
884 if (rc->rotation == 90 || rc->rotation == 270) {
885 *width = (gint) (page_height * rc->scale);
886 *height = (gint) (page_width * rc->scale);
888 *width = (gint) (page_width * rc->scale);
889 *height = (gint) (page_height * rc->scale);
894 comics_document_document_thumbnails_iface_init (EvDocumentThumbnailsInterface *iface)
896 iface->get_thumbnail = comics_document_thumbnails_get_thumbnail;
897 iface->get_dimensions = comics_document_thumbnails_get_dimensions;
901 extract_argv (EvDocument *document, gint page)
903 ComicsDocument *comics_document = COMICS_DOCUMENT (document);
905 char *command_line, *quoted_archive, *quoted_filename;
908 if (page >= comics_document->page_names->len)
911 if (comics_document->regex_arg) {
912 quoted_archive = comics_regex_quote (comics_document->archive);
914 comics_regex_quote (comics_document->page_names->pdata[page]);
916 quoted_archive = g_shell_quote (comics_document->archive);
917 quoted_filename = g_shell_quote (comics_document->page_names->pdata[page]);
920 command_line = g_strdup_printf ("%s %s %s",
921 comics_document->extract_command,
924 g_shell_parse_argv (command_line, NULL, &argv, &err);
927 g_warning (_("Error %s"), err->message);
932 g_free (command_line);
933 g_free (quoted_archive);
934 g_free (quoted_filename);