Bug fix: pdf and djvu files
[geeqie.git] / src / image-load.c
1 /*
2  * Copyright (C) 2004 John Ellis
3  * Copyright (C) 2008 - 2016 The Geeqie Team
4  *
5  * Author: John Ellis
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along
18  * with this program; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  */
21
22 #include "main.h"
23 #include "image-load.h"
24 #include "image_load_gdk.h"
25 #include "image_load_jpeg.h"
26 #include "image_load_tiff.h"
27 #include "image_load_dds.h"
28 #include "image_load_djvu.h"
29 #include "image_load_pdf.h"
30 #include "image_load_heif.h"
31 #include "image_load_ffmpegthumbnailer.h"
32 #include "image_load_collection.h"
33 #include "image_load_webp.h"
34
35 #include "exif.h"
36 #include "filedata.h"
37 #include "ui_fileops.h"
38 #include "gq-marshal.h"
39
40 #include <fcntl.h>
41 #include <sys/mman.h>
42
43 #define IMAGE_LOADER_READ_BUFFER_SIZE_DEFAULT   4096
44 #define IMAGE_LOADER_IDLE_READ_LOOP_COUNT_DEFAULT       1
45
46
47 /**************************************************************************************/
48 /* image loader class */
49
50
51 enum {
52         SIGNAL_AREA_READY = 0,
53         SIGNAL_ERROR,
54         SIGNAL_DONE,
55         SIGNAL_PERCENT,
56         SIGNAL_SIZE,
57         SIGNAL_COUNT
58 };
59
60 static guint signals[SIGNAL_COUNT] = { 0 };
61
62 static void image_loader_init(GTypeInstance *instance, gpointer g_class);
63 static void image_loader_class_init(ImageLoaderClass *class);
64 static void image_loader_finalize(GObject *object);
65 static void image_loader_stop(ImageLoader *il);
66
67 GType image_loader_get_type(void)
68 {
69         static GType type = 0;
70         if (type == 0)
71                 {
72                 static const GTypeInfo info = {
73                         sizeof(ImageLoaderClass),
74                         NULL,   /* base_init */
75                         NULL,   /* base_finalize */
76                         (GClassInitFunc)image_loader_class_init, /* class_init */
77                         NULL,   /* class_finalize */
78                         NULL,   /* class_data */
79                         sizeof(ImageLoader),
80                         0,      /* n_preallocs */
81                         (GInstanceInitFunc)image_loader_init, /* instance_init */
82                         NULL    /* value_table */
83                         };
84                 type = g_type_register_static(G_TYPE_OBJECT, "ImageLoaderType", &info, 0);
85                 }
86         return type;
87 }
88
89 static void image_loader_init(GTypeInstance *instance, gpointer g_class)
90 {
91         ImageLoader *il = (ImageLoader *)instance;
92
93         il->pixbuf = NULL;
94         il->idle_id = 0;
95         il->idle_priority = G_PRIORITY_DEFAULT_IDLE;
96         il->done = FALSE;
97         il->loader = NULL;
98
99         il->bytes_read = 0;
100         il->bytes_total = 0;
101
102         il->idle_done_id = 0;
103
104         il->idle_read_loop_count = IMAGE_LOADER_IDLE_READ_LOOP_COUNT_DEFAULT;
105         il->read_buffer_size = IMAGE_LOADER_READ_BUFFER_SIZE_DEFAULT;
106         il->mapped_file = NULL;
107
108         il->requested_width = 0;
109         il->requested_height = 0;
110         il->actual_width = 0;
111         il->actual_height = 0;
112         il->shrunk = FALSE;
113
114         il->can_destroy = TRUE;
115
116 #ifdef HAVE_GTHREAD
117 #if GLIB_CHECK_VERSION(2,32,0)
118         il->data_mutex = g_new(GMutex, 1);
119         g_mutex_init(il->data_mutex);
120         il->can_destroy_cond = g_new(GCond, 1);
121         g_cond_init(il->can_destroy_cond);
122 #else
123         il->data_mutex = g_mutex_new();
124         il->can_destroy_cond = g_cond_new();
125 #endif
126 #endif
127         DEBUG_1("new image loader %p, bufsize=%" G_GSIZE_FORMAT " idle_loop=%u", il, il->read_buffer_size, il->idle_read_loop_count);
128 }
129
130 static void image_loader_class_init(ImageLoaderClass *class)
131 {
132         GObjectClass *gobject_class = G_OBJECT_CLASS (class);
133
134 //      gobject_class->set_property = image_loader_set_property;
135 //      gobject_class->get_property = image_loader_get_property;
136
137         gobject_class->finalize = image_loader_finalize;
138
139
140         signals[SIGNAL_AREA_READY] =
141                 g_signal_new("area_ready",
142                              G_OBJECT_CLASS_TYPE(gobject_class),
143                              G_SIGNAL_RUN_LAST,
144                              G_STRUCT_OFFSET(ImageLoaderClass, area_ready),
145                              NULL, NULL,
146                              gq_marshal_VOID__INT_INT_INT_INT,
147                              G_TYPE_NONE, 4,
148                              G_TYPE_INT,
149                              G_TYPE_INT,
150                              G_TYPE_INT,
151                              G_TYPE_INT);
152
153         signals[SIGNAL_ERROR] =
154                 g_signal_new("error",
155                              G_OBJECT_CLASS_TYPE(gobject_class),
156                              G_SIGNAL_RUN_LAST,
157                              G_STRUCT_OFFSET(ImageLoaderClass, error),
158                              NULL, NULL,
159                              g_cclosure_marshal_VOID__VOID,
160                              G_TYPE_NONE, 0);
161
162         signals[SIGNAL_DONE] =
163                 g_signal_new("done",
164                              G_OBJECT_CLASS_TYPE(gobject_class),
165                              G_SIGNAL_RUN_LAST,
166                              G_STRUCT_OFFSET(ImageLoaderClass, done),
167                              NULL, NULL,
168                              g_cclosure_marshal_VOID__VOID,
169                              G_TYPE_NONE, 0);
170
171         signals[SIGNAL_PERCENT] =
172                 g_signal_new("percent",
173                              G_OBJECT_CLASS_TYPE(gobject_class),
174                              G_SIGNAL_RUN_LAST,
175                              G_STRUCT_OFFSET(ImageLoaderClass, percent),
176                              NULL, NULL,
177                              g_cclosure_marshal_VOID__DOUBLE,
178                              G_TYPE_NONE, 1,
179                              G_TYPE_DOUBLE);
180
181         signals[SIGNAL_SIZE] =
182                 g_signal_new("size_prepared",
183                              G_OBJECT_CLASS_TYPE(gobject_class),
184                              G_SIGNAL_RUN_LAST,
185                              G_STRUCT_OFFSET(ImageLoaderClass, area_ready),
186                              NULL, NULL,
187                              gq_marshal_VOID__INT_INT,
188                              G_TYPE_NONE, 2,
189                              G_TYPE_INT,
190                              G_TYPE_INT);
191
192 }
193
194 static void image_loader_finalize(GObject *object)
195 {
196         ImageLoader *il = (ImageLoader *)object;
197
198         image_loader_stop(il);
199
200         if (il->error) DEBUG_1("%s", image_loader_get_error(il));
201
202         DEBUG_1("freeing image loader %p bytes_read=%" G_GSIZE_FORMAT, il, il->bytes_read);
203
204         if (il->idle_done_id)
205                 {
206                 g_source_remove(il->idle_done_id);
207                 il->idle_done_id = 0;
208                 }
209
210         while (g_source_remove_by_user_data(il))
211                 {
212                 DEBUG_2("pending signals detected");
213                 }
214
215         while (il->area_param_list)
216                 {
217                 DEBUG_1("pending area_ready signals detected");
218                 while (g_source_remove_by_user_data(il->area_param_list->data)) {}
219                 g_free(il->area_param_list->data);
220                 il->area_param_list = g_list_delete_link(il->area_param_list, il->area_param_list);
221                 }
222
223         while (il->area_param_delayed_list)
224                 {
225                 g_free(il->area_param_delayed_list->data);
226                 il->area_param_delayed_list = g_list_delete_link(il->area_param_delayed_list, il->area_param_delayed_list);
227                 }
228
229         if (il->pixbuf) g_object_unref(il->pixbuf);
230
231         if (il->error) g_error_free(il->error);
232
233         file_data_unref(il->fd);
234 #ifdef HAVE_GTHREAD
235 #if GLIB_CHECK_VERSION(2,32,0)
236         g_mutex_clear(il->data_mutex);
237         g_free(il->data_mutex);
238         g_cond_clear(il->can_destroy_cond);
239         g_free(il->can_destroy_cond);
240 #else
241         g_mutex_free(il->data_mutex);
242         g_cond_free(il->can_destroy_cond);
243 #endif
244 #endif
245 }
246
247 void image_loader_free(ImageLoader *il)
248 {
249         if (!il) return;
250         g_object_unref(G_OBJECT(il));
251 }
252
253
254 ImageLoader *image_loader_new(FileData *fd)
255 {
256         ImageLoader *il;
257
258         if (!fd) return NULL;
259
260         il = (ImageLoader *) g_object_new(TYPE_IMAGE_LOADER, NULL);
261
262         il->fd = file_data_ref(fd);
263
264         return il;
265 }
266
267 /**************************************************************************************/
268 /* send signals via idle calbacks - the callback are executed in the main thread */
269
270 typedef struct _ImageLoaderAreaParam ImageLoaderAreaParam;
271 struct _ImageLoaderAreaParam {
272         ImageLoader *il;
273         guint x;
274         guint y;
275         guint w;
276         guint h;
277 };
278
279
280 static gboolean image_loader_emit_area_ready_cb(gpointer data)
281 {
282         ImageLoaderAreaParam *par = data;
283         ImageLoader *il = par->il;
284         guint x, y, w, h;
285         g_mutex_lock(il->data_mutex);
286         il->area_param_list = g_list_remove(il->area_param_list, par);
287         x = par->x;
288         y = par->y;
289         w = par->w;
290         h = par->h;
291         g_free(par);
292         g_mutex_unlock(il->data_mutex);
293
294         g_signal_emit(il, signals[SIGNAL_AREA_READY], 0, x, y, w, h);
295
296         return FALSE;
297 }
298
299 static gboolean image_loader_emit_done_cb(gpointer data)
300 {
301         ImageLoader *il = data;
302         g_signal_emit(il, signals[SIGNAL_DONE], 0);
303         return FALSE;
304 }
305
306 static gboolean image_loader_emit_error_cb(gpointer data)
307 {
308         ImageLoader *il = data;
309         g_signal_emit(il, signals[SIGNAL_ERROR], 0);
310         return FALSE;
311 }
312
313 static gboolean image_loader_emit_percent_cb(gpointer data)
314 {
315         ImageLoader *il = data;
316         g_signal_emit(il, signals[SIGNAL_PERCENT], 0, image_loader_get_percent(il));
317         return FALSE;
318 }
319
320 static gboolean image_loader_emit_size_cb(gpointer data)
321 {
322         gint width, height;
323         ImageLoader *il = data;
324         g_mutex_lock(il->data_mutex);
325         width = il->actual_width;
326         height = il->actual_height;
327         g_mutex_unlock(il->data_mutex);
328         g_signal_emit(il, signals[SIGNAL_SIZE], 0, width, height);
329         return FALSE;
330 }
331
332
333 /* DONE and ERROR are emited only once, thus they can have normal priority
334    PERCENT and AREA_READY should be processed ASAP
335 */
336
337 static void image_loader_emit_done(ImageLoader *il)
338 {
339         g_idle_add_full(il->idle_priority, image_loader_emit_done_cb, il, NULL);
340 }
341
342 static void image_loader_emit_error(ImageLoader *il)
343 {
344         g_idle_add_full(il->idle_priority, image_loader_emit_error_cb, il, NULL);
345 }
346
347 static void image_loader_emit_percent(ImageLoader *il)
348 {
349         g_idle_add_full(G_PRIORITY_HIGH, image_loader_emit_percent_cb, il, NULL);
350 }
351
352 static void image_loader_emit_size(ImageLoader *il)
353 {
354         g_idle_add_full(G_PRIORITY_HIGH, image_loader_emit_size_cb, il, NULL);
355 }
356
357 static ImageLoaderAreaParam *image_loader_queue_area_ready(ImageLoader *il, GList **list, guint x, guint y, guint w, guint h)
358 {
359         if (*list)
360                 {
361                 ImageLoaderAreaParam *prev_par = (*list)->data;
362                 if (prev_par->x == x && prev_par->w == w &&
363                     prev_par->y + prev_par->h == y)
364                         {
365                         /* we can merge the notifications */
366                         prev_par->h += h;
367                         return NULL;
368                         }
369                 if (prev_par->x == x && prev_par->w == w &&
370                     y + h == prev_par->y)
371                         {
372                         /* we can merge the notifications */
373                         prev_par->h += h;
374                         prev_par->y = y;
375                         return NULL;
376                         }
377                 if (prev_par->y == y && prev_par->h == h &&
378                     prev_par->x + prev_par->w == x)
379                         {
380                         /* we can merge the notifications */
381                         prev_par->w += w;
382                         return NULL;
383                         }
384                 if (prev_par->y == y && prev_par->h == h &&
385                     x + w == prev_par->x)
386                         {
387                         /* we can merge the notifications */
388                         prev_par->w += w;
389                         prev_par->x = x;
390                         return NULL;
391                         }
392                 }
393
394         ImageLoaderAreaParam *par = g_new0(ImageLoaderAreaParam, 1);
395         par->il = il;
396         par->x = x;
397         par->y = y;
398         par->w = w;
399         par->h = h;
400
401         *list = g_list_prepend(*list, par);
402         return par;
403 }
404
405 /* this function expects that il->data_mutex is locked by caller */
406 static void image_loader_emit_area_ready(ImageLoader *il, guint x, guint y, guint w, guint h)
407 {
408         ImageLoaderAreaParam *par = image_loader_queue_area_ready(il, &il->area_param_list, x, y, w, h);
409
410         if (par)
411                 {
412                 g_idle_add_full(G_PRIORITY_HIGH, image_loader_emit_area_ready_cb, par, NULL);
413                 }
414 }
415
416 /**************************************************************************************/
417 /* the following functions may be executed in separate thread */
418
419 /* this function expects that il->data_mutex is locked by caller */
420 static void image_loader_queue_delayed_area_ready(ImageLoader *il, guint x, guint y, guint w, guint h)
421 {
422         image_loader_queue_area_ready(il, &il->area_param_delayed_list, x, y, w, h);
423 }
424
425
426
427 static gboolean image_loader_get_stopping(ImageLoader *il)
428 {
429         gboolean ret;
430         if (!il) return FALSE;
431
432         g_mutex_lock(il->data_mutex);
433         ret = il->stopping;
434         g_mutex_unlock(il->data_mutex);
435
436         return ret;
437 }
438
439
440 static void image_loader_sync_pixbuf(ImageLoader *il)
441 {
442         GdkPixbuf *pb;
443
444         g_mutex_lock(il->data_mutex);
445
446         if (!il->loader)
447                 {
448                 g_mutex_unlock(il->data_mutex);
449                 return;
450                 }
451
452         pb = il->backend.get_pixbuf(il->loader);
453
454         if (pb == il->pixbuf)
455                 {
456                 g_mutex_unlock(il->data_mutex);
457                 return;
458                 }
459
460         if (g_ascii_strcasecmp(".jps", il->fd->extension) == 0)
461                 {
462                 g_object_set_data(G_OBJECT(pb), "stereo_data", GINT_TO_POINTER(STEREO_PIXBUF_CROSS));
463                 }
464
465         if (il->pixbuf) g_object_unref(il->pixbuf);
466
467         il->pixbuf = pb;
468         if (il->pixbuf) g_object_ref(il->pixbuf);
469
470         g_mutex_unlock(il->data_mutex);
471 }
472
473 static void image_loader_area_updated_cb(gpointer loader,
474                                  guint x, guint y, guint w, guint h,
475                                  gpointer data)
476 {
477         ImageLoader *il = data;
478
479         if (!image_loader_get_pixbuf(il))
480                 {
481                 image_loader_sync_pixbuf(il);
482                 if (!image_loader_get_pixbuf(il))
483                         {
484                         log_printf("critical: area_ready signal with NULL pixbuf (out of mem?)\n");
485                         }
486                 }
487
488         g_mutex_lock(il->data_mutex);
489         if (il->delay_area_ready)
490                 image_loader_queue_delayed_area_ready(il, x, y, w, h);
491         else
492                 image_loader_emit_area_ready(il, x, y, w, h);
493
494         if (il->stopping) il->backend.abort(il->loader);
495
496         g_mutex_unlock(il->data_mutex);
497 }
498
499 static void image_loader_area_prepared_cb(gpointer loader, gpointer data)
500 {
501         ImageLoader *il = data;
502         GdkPixbuf *pb;
503         guchar *pix;
504         size_t h, rs;
505
506         /* a workaround for
507            http://bugzilla.gnome.org/show_bug.cgi?id=547669
508            http://bugzilla.gnome.org/show_bug.cgi?id=589334
509         */
510         gchar *format = il->backend.get_format_name(loader);
511         if (strcmp(format, "svg") == 0 ||
512             strcmp(format, "xpm") == 0)
513                 {
514                 g_free(format);
515                 return;
516                 }
517
518         g_free(format);
519
520         pb = il->backend.get_pixbuf(loader);
521
522         h = gdk_pixbuf_get_height(pb);
523         rs = gdk_pixbuf_get_rowstride(pb);
524         pix = gdk_pixbuf_get_pixels(pb);
525
526         memset(pix, 0, rs * h); /*this should be faster than pixbuf_fill */
527
528 }
529
530 static void image_loader_size_cb(gpointer loader,
531                                  gint width, gint height, gpointer data)
532 {
533         ImageLoader *il = data;
534         gchar **mime_types;
535         gboolean scale = FALSE;
536         gint n;
537
538         g_mutex_lock(il->data_mutex);
539         il->actual_width = width;
540         il->actual_height = height;
541         if (il->requested_width < 1 || il->requested_height < 1)
542                 {
543                 g_mutex_unlock(il->data_mutex);
544                 image_loader_emit_size(il);
545                 return;
546                 }
547         g_mutex_unlock(il->data_mutex);
548
549 #ifdef HAVE_FFMPEGTHUMBNAILER
550         if (il->fd->format_class == FORMAT_CLASS_VIDEO)
551                 scale = TRUE;
552 #endif
553         mime_types = il->backend.get_format_mime_types(loader);
554         n = 0;
555         while (mime_types[n] && !scale)
556                 {
557                 if (strstr(mime_types[n], "jpeg")) scale = TRUE;
558                 n++;
559                 }
560         g_strfreev(mime_types);
561
562         if (!scale)
563                 {
564                 image_loader_emit_size(il);
565                 return;
566                 }
567
568         g_mutex_lock(il->data_mutex);
569
570         gint nw, nh;
571         if (width > il->requested_width || height > il->requested_height)
572                 {
573
574                 if (((gdouble)il->requested_width / width) < ((gdouble)il->requested_height / height))
575                         {
576                         nw = il->requested_width;
577                         nh = (gdouble)nw / width * height;
578                         if (nh < 1) nh = 1;
579                         }
580                 else
581                         {
582                         nh = il->requested_height;
583                         nw = (gdouble)nh / height * width;
584                         if (nw < 1) nw = 1;
585                         }
586
587                 il->actual_width = nw;
588                 il->actual_height = nh;
589                 il->backend.set_size(loader, nw, nh);
590                 il->shrunk = TRUE;
591                 }
592
593         g_mutex_unlock(il->data_mutex);
594         image_loader_emit_size(il);
595 }
596
597 static void image_loader_stop_loader(ImageLoader *il)
598 {
599         if (!il) return;
600
601         if (il->loader)
602                 {
603                 /* some loaders do not have a pixbuf till close, order is important here */
604                 il->backend.close(il->loader, il->error ? NULL : &il->error); /* we are interested in the first error only */
605                 image_loader_sync_pixbuf(il);
606                 il->backend.free(il->loader);
607                 il->loader = NULL;
608                 }
609         g_mutex_lock(il->data_mutex);
610         il->done = TRUE;
611         g_mutex_unlock(il->data_mutex);
612 }
613
614 static void image_loader_setup_loader(ImageLoader *il)
615 {
616         gchar *format;
617
618         g_mutex_lock(il->data_mutex);
619 #ifdef HAVE_FFMPEGTHUMBNAILER
620         if (il->fd->format_class == FORMAT_CLASS_VIDEO)
621                 {
622                 DEBUG_1("Using custom ffmpegthumbnailer loader");
623                 image_loader_backend_set_ft(&il->backend);
624                 }
625         else
626 #endif
627 #ifdef HAVE_PDF
628         if (il->bytes_total >= 4 &&
629             (memcmp(il->mapped_file + 0, "%PDF", 4) == 0))
630                 {
631                 DEBUG_1("Using custom pdf loader");
632                 image_loader_backend_set_pdf(&il->backend);
633                 }
634         else
635 #endif
636 #ifdef HAVE_HEIF
637         if (il->bytes_total >= 10 &&
638             (memcmp(il->mapped_file + 4, "ftypheic", 8) == 0))
639                 {
640                 DEBUG_1("Using custom heif loader");
641                 image_loader_backend_set_heif(&il->backend);
642                 }
643         else
644 #endif
645 #ifdef HAVE_WEBP
646         if (il->bytes_total >= 12 &&
647                 (memcmp(il->mapped_file, "RIFF", 4) == 0) &&
648                 (memcmp(il->mapped_file + 8, "WEBP", 4) == 0))
649                 {
650                 DEBUG_1("Using custom webp loader");
651                 image_loader_backend_set_webp(&il->backend);
652                 }
653         else
654 #endif
655 #ifdef HAVE_DJVU
656         if (il->bytes_total >= 16 &&
657                 (memcmp(il->mapped_file, "AT&TFORM", 8) == 0) &&
658                 (memcmp(il->mapped_file + 12, "DJV", 3) == 0))
659                 {
660                 DEBUG_1("Using custom djvu loader");
661                 image_loader_backend_set_djvu(&il->backend);
662                 }
663         else
664 #endif
665 #ifdef HAVE_JPEG
666         if (il->bytes_total >= 2 && il->mapped_file[0] == 0xff && il->mapped_file[1] == 0xd8)
667                 {
668                 DEBUG_1("Using custom jpeg loader");
669                 image_loader_backend_set_jpeg(&il->backend);
670                 }
671         else
672 #endif
673 #ifdef HAVE_TIFF
674         if (il->bytes_total >= 10 &&
675             (memcmp(il->mapped_file, "MM\0*", 4) == 0 ||
676              memcmp(il->mapped_file, "MM\0+\0\x08\0\0", 8) == 0 ||
677              memcmp(il->mapped_file, "II+\0\x08\0\0\0", 8) == 0 ||
678              memcmp(il->mapped_file, "II*\0", 4) == 0))
679                 {
680                 DEBUG_1("Using custom tiff loader");
681                 image_loader_backend_set_tiff(&il->backend);
682                 }
683         else
684 #endif
685         if (il->bytes_total >= 3 && il->mapped_file[0] == 0x44 && il->mapped_file[1] == 0x44 && il->mapped_file[2] == 0x53)
686                 {
687                 DEBUG_1("Using dds loader");
688                 image_loader_backend_set_dds(&il->backend);
689                 }
690         else
691         if (il->fd->format_class == FORMAT_CLASS_COLLECTION)
692                 {
693                 DEBUG_1("Using custom collection loader");
694                 image_loader_backend_set_collection(&il->backend);
695                 }
696         else
697                 image_loader_backend_set_default(&il->backend);
698
699         il->loader = il->backend.loader_new(image_loader_area_updated_cb, image_loader_size_cb, image_loader_area_prepared_cb, il);
700
701 #ifdef HAVE_PDF
702         format = il->backend.get_format_name(il->loader);
703         if (g_strcmp0(format, "pdf") == 0)
704                 {
705                 il->backend.set_page_num(il->loader, il->fd->page_num);
706                 }
707         g_free(format);
708 #endif
709
710 #ifdef HAVE_DJVU
711         format = il->backend.get_format_name(il->loader);
712         if (g_strcmp0(format, "djvu") == 0)
713                 {
714                 il->backend.set_page_num(il->loader, il->fd->page_num);
715                 }
716         g_free(format);
717 #endif
718
719         g_mutex_unlock(il->data_mutex);
720 }
721
722
723 static void image_loader_done(ImageLoader *il)
724 {
725         image_loader_stop_loader(il);
726
727         image_loader_emit_done(il);
728 }
729
730 static void image_loader_error(ImageLoader *il)
731 {
732         image_loader_stop_loader(il);
733
734         DEBUG_1("pixbuf_loader reported load error for: %s", il->fd->path);
735
736         image_loader_emit_error(il);
737 }
738
739 static gboolean image_loader_continue(ImageLoader *il)
740 {
741         gint b;
742         gint c;
743
744         if (!il) return FALSE;
745
746         c = il->idle_read_loop_count ? il->idle_read_loop_count : 1;
747         while (c > 0 && !image_loader_get_stopping(il))
748                 {
749                 b = MIN(il->read_buffer_size, il->bytes_total - il->bytes_read);
750
751                 if (b == 0)
752                         {
753                         image_loader_done(il);
754                         return FALSE;
755                         }
756
757                 if (b < 0 || (b > 0 && !il->backend.write(il->loader, il->mapped_file + il->bytes_read, b, &il->error)))
758                         {
759                         image_loader_error(il);
760                         return FALSE;
761                         }
762
763                 il->bytes_read += b;
764
765                 c--;
766                 }
767
768         if (il->bytes_total > 0)
769                 {
770                 image_loader_emit_percent(il);
771                 }
772
773         return TRUE;
774 }
775
776 static gboolean image_loader_begin(ImageLoader *il)
777 {
778         gssize b;
779         gchar *format;
780
781         if (il->pixbuf) return FALSE;
782
783         b = MIN(il->read_buffer_size, il->bytes_total - il->bytes_read);
784         if (b < 1) return FALSE;
785
786         image_loader_setup_loader(il);
787
788         g_assert(il->bytes_read == 0);
789         if (il->backend.load) {
790                 b = il->bytes_total;
791                 if (!il->backend.load(il->loader, il->mapped_file, b, &il->error))
792                         {
793                         image_loader_stop_loader(il);
794                         return FALSE;
795                         }
796         }
797         else if (!il->backend.write(il->loader, il->mapped_file, b, &il->error))
798                 {
799                 image_loader_stop_loader(il);
800                 return FALSE;
801                 }
802
803 #ifdef HAVE_PDF
804         format = il->backend.get_format_name(il->loader);
805         if (g_strcmp0(format, "pdf") == 0)
806                 {
807                 gint i = il->backend.get_page_total(il->loader);
808                 file_data_set_page_total(il->fd, i);
809                 }
810         g_free(format);
811 #endif
812 #ifdef HAVE_DJVU
813         format = il->backend.get_format_name(il->loader);
814         if (g_strcmp0(format, "djvu") == 0)
815                 {
816                 gint i = il->backend.get_page_total(il->loader);
817                 file_data_set_page_total(il->fd, i);
818                 }
819         g_free(format);
820 #endif
821
822         il->bytes_read += b;
823
824         /* read until size is known */
825         while (il->loader && !il->backend.get_pixbuf(il->loader) && b > 0 && !image_loader_get_stopping(il))
826                 {
827                 b = MIN(il->read_buffer_size, il->bytes_total - il->bytes_read);
828                 if (b < 0 || (b > 0 && !il->backend.write(il->loader, il->mapped_file + il->bytes_read, b, &il->error)))
829                         {
830                         image_loader_stop_loader(il);
831                         return FALSE;
832                         }
833                 il->bytes_read += b;
834                 }
835         if (!il->pixbuf) image_loader_sync_pixbuf(il);
836
837         if (il->bytes_read == il->bytes_total || b < 1)
838                 {
839                 /* done, handle (broken) loaders that do not have pixbuf till close */
840                 image_loader_stop_loader(il);
841
842                 if (!il->pixbuf) return FALSE;
843
844                 image_loader_done(il);
845                 return TRUE;
846                 }
847
848         if (!il->pixbuf)
849                 {
850                 image_loader_stop_loader(il);
851                 return FALSE;
852                 }
853
854         return TRUE;
855 }
856
857 /**************************************************************************************/
858 /* the following functions are always executed in the main thread */
859
860
861 static gboolean image_loader_setup_source(ImageLoader *il)
862 {
863         struct stat st;
864         gchar *pathl;
865
866         if (!il || il->loader || il->mapped_file) return FALSE;
867
868         il->mapped_file = NULL;
869
870         if (il->fd)
871                 {
872                 ExifData *exif = exif_read_fd(il->fd);
873
874                 if (options->thumbnails.use_exif)
875                         il->mapped_file = exif_get_preview(exif, (guint *)&il->bytes_total, il->requested_width, il->requested_height);
876                 else
877                         il->mapped_file = exif_get_preview(exif, (guint *)&il->bytes_total, 0, 0); /* get the largest available preview image or NULL for normal images*/
878
879                 if (il->mapped_file)
880                         {
881                         il->preview = TRUE;
882                         DEBUG_1("Usable reduced size (preview) image loaded from file %s", il->fd->path);
883                         }
884                 exif_free_fd(il->fd, exif);
885                 }
886
887
888         if (!il->mapped_file)
889                 {
890                 /* normal file */
891                 gint load_fd;
892
893                 pathl = path_from_utf8(il->fd->path);
894                 load_fd = open(pathl, O_RDONLY | O_NONBLOCK);
895                 g_free(pathl);
896                 if (load_fd == -1) return FALSE;
897
898                 if (fstat(load_fd, &st) == 0)
899                         {
900                         il->bytes_total = st.st_size;
901                         }
902                 else
903                         {
904                         close(load_fd);
905                         return FALSE;
906                         }
907
908                 il->mapped_file = mmap(0, il->bytes_total, PROT_READ|PROT_WRITE, MAP_PRIVATE, load_fd, 0);
909                 close(load_fd);
910                 if (il->mapped_file == MAP_FAILED)
911                         {
912                         il->mapped_file = 0;
913                         return FALSE;
914                         }
915                 il->preview = FALSE;
916                 }
917
918         return TRUE;
919 }
920
921 static void image_loader_stop_source(ImageLoader *il)
922 {
923         if (!il) return;
924
925         if (il->mapped_file)
926                 {
927                 if (il->preview)
928                         {
929                         exif_free_preview(il->mapped_file);
930                         }
931                 else
932                         {
933                         munmap(il->mapped_file, il->bytes_total);
934                         }
935                 il->mapped_file = NULL;
936                 }
937 }
938
939 static void image_loader_stop(ImageLoader *il)
940 {
941         if (!il) return;
942
943         if (il->idle_id)
944                 {
945                 g_source_remove(il->idle_id);
946                 il->idle_id = 0;
947                 }
948
949         if (il->thread)
950                 {
951                 /* stop loader in the other thread */
952                 g_mutex_lock(il->data_mutex);
953                 il->stopping = TRUE;
954                 while (!il->can_destroy) g_cond_wait(il->can_destroy_cond, il->data_mutex);
955                 g_mutex_unlock(il->data_mutex);
956                 }
957
958         image_loader_stop_loader(il);
959         image_loader_stop_source(il);
960
961 }
962
963 void image_loader_delay_area_ready(ImageLoader *il, gboolean enable)
964 {
965         g_mutex_lock(il->data_mutex);
966         il->delay_area_ready = enable;
967         if (!enable)
968                 {
969                 /* send delayed */
970                 GList *list, *work;
971                 list = g_list_reverse(il->area_param_delayed_list);
972                 il->area_param_delayed_list = NULL;
973                 g_mutex_unlock(il->data_mutex);
974
975                 work = list;
976
977                 while (work)
978                         {
979                         ImageLoaderAreaParam *par = work->data;
980                         work = work->next;
981
982                         g_signal_emit(il, signals[SIGNAL_AREA_READY], 0, par->x, par->y, par->w, par->h);
983                         g_free(par);
984                         }
985                 g_list_free(list);
986                 }
987         else
988                 {
989                 /* just unlock */
990                 g_mutex_unlock(il->data_mutex);
991                 }
992 }
993
994
995 /**************************************************************************************/
996 /* execution via idle calls */
997
998 static gboolean image_loader_idle_cb(gpointer data)
999 {
1000         gboolean ret = FALSE;
1001         ImageLoader *il = data;
1002
1003         if (il->idle_id)
1004                 {
1005                 ret = image_loader_continue(il);
1006                 }
1007
1008         if (!ret)
1009                 {
1010                 image_loader_stop_source(il);
1011                 }
1012
1013         return ret;
1014 }
1015
1016
1017 static gboolean image_loader_start_idle(ImageLoader *il)
1018 {
1019         gboolean ret;
1020
1021         if (!il) return FALSE;
1022
1023         if (!il->fd) return FALSE;
1024
1025         if (!image_loader_setup_source(il)) return FALSE;
1026
1027         ret = image_loader_begin(il);
1028
1029         if (ret && !il->done) il->idle_id = g_idle_add_full(il->idle_priority, image_loader_idle_cb, il, NULL);
1030         return ret;
1031 }
1032
1033 /**************************************************************************************/
1034 /* execution via thread */
1035
1036 #ifdef HAVE_GTHREAD
1037 static GThreadPool *image_loader_thread_pool = NULL;
1038
1039 static GCond *image_loader_prio_cond = NULL;
1040 static GMutex *image_loader_prio_mutex = NULL;
1041 static gint image_loader_prio_num = 0;
1042
1043
1044 static void image_loader_thread_enter_high(void)
1045 {
1046         g_mutex_lock(image_loader_prio_mutex);
1047         image_loader_prio_num++;
1048         g_mutex_unlock(image_loader_prio_mutex);
1049 }
1050
1051 static void image_loader_thread_leave_high(void)
1052 {
1053         g_mutex_lock(image_loader_prio_mutex);
1054         image_loader_prio_num--;
1055         if (image_loader_prio_num == 0) g_cond_broadcast(image_loader_prio_cond); /* wake up all low prio threads */
1056         g_mutex_unlock(image_loader_prio_mutex);
1057 }
1058
1059 static void image_loader_thread_wait_high(void)
1060 {
1061         g_mutex_lock(image_loader_prio_mutex);
1062         while (image_loader_prio_num)
1063                 {
1064                 g_cond_wait(image_loader_prio_cond, image_loader_prio_mutex);
1065                 }
1066
1067         g_mutex_unlock(image_loader_prio_mutex);
1068 }
1069
1070
1071 static void image_loader_thread_run(gpointer data, gpointer user_data)
1072 {
1073         ImageLoader *il = data;
1074         gboolean cont;
1075         gboolean err;
1076
1077         if (il->idle_priority > G_PRIORITY_DEFAULT_IDLE)
1078                 {
1079                 /* low prio, wait untill high prio tasks finishes */
1080                 image_loader_thread_wait_high();
1081                 }
1082         else
1083                 {
1084                 /* high prio */
1085                 image_loader_thread_enter_high();
1086                 }
1087
1088         err = !image_loader_begin(il);
1089
1090         if (err)
1091                 {
1092                 /*
1093                 loader failed, we have to send signal
1094                 (idle mode returns the image_loader_begin return value directly)
1095                 (success is always reported indirectly from image_loader_begin)
1096                 */
1097                 image_loader_emit_error(il);
1098                 }
1099
1100         cont = !err;
1101
1102         while (cont && !image_loader_get_is_done(il) && !image_loader_get_stopping(il))
1103                 {
1104                 if (il->idle_priority > G_PRIORITY_DEFAULT_IDLE)
1105                         {
1106                         /* low prio, wait untill high prio tasks finishes */
1107                         image_loader_thread_wait_high();
1108                         }
1109                 cont = image_loader_continue(il);
1110                 }
1111         image_loader_stop_loader(il);
1112
1113         if (il->idle_priority <= G_PRIORITY_DEFAULT_IDLE)
1114                 {
1115                 /* high prio */
1116                 image_loader_thread_leave_high();
1117                 }
1118
1119         g_mutex_lock(il->data_mutex);
1120         il->can_destroy = TRUE;
1121         g_cond_signal(il->can_destroy_cond);
1122         g_mutex_unlock(il->data_mutex);
1123
1124 }
1125
1126
1127 static gboolean image_loader_start_thread(ImageLoader *il)
1128 {
1129         if (!il) return FALSE;
1130
1131         if (!il->fd) return FALSE;
1132
1133         il->thread = TRUE;
1134
1135         if (!image_loader_setup_source(il)) return FALSE;
1136
1137         if (!image_loader_thread_pool)
1138                 {
1139                 image_loader_thread_pool = g_thread_pool_new(image_loader_thread_run, NULL, -1, FALSE, NULL);
1140 #if GLIB_CHECK_VERSION(2,32,0)
1141                 if (!image_loader_prio_cond) image_loader_prio_cond = g_new(GCond, 1);
1142                 g_cond_init(image_loader_prio_cond);
1143                 if (!image_loader_prio_mutex) image_loader_prio_mutex = g_new(GMutex, 1);
1144                 g_mutex_init(image_loader_prio_mutex);
1145 #else
1146                 image_loader_prio_cond = g_cond_new();
1147                 image_loader_prio_mutex = g_mutex_new();
1148 #endif
1149                 }
1150
1151         il->can_destroy = FALSE; /* ImageLoader can't be freed until image_loader_thread_run finishes */
1152
1153         g_thread_pool_push(image_loader_thread_pool, il, NULL);
1154         DEBUG_1("Thread pool num threads: %d", g_thread_pool_get_num_threads(image_loader_thread_pool));
1155
1156         return TRUE;
1157 }
1158 #endif /* HAVE_GTHREAD */
1159
1160
1161 /**************************************************************************************/
1162 /* public interface */
1163
1164
1165 gboolean image_loader_start(ImageLoader *il)
1166 {
1167         if (!il) return FALSE;
1168
1169         if (!il->fd) return FALSE;
1170
1171 #ifdef HAVE_GTHREAD
1172         return image_loader_start_thread(il);
1173 #else
1174         return image_loader_start_idle(il);
1175 #endif
1176 }
1177
1178
1179 /* don't forget to gdk_pixbuf_ref() it if you want to use it after image_loader_free() */
1180 GdkPixbuf *image_loader_get_pixbuf(ImageLoader *il)
1181 {
1182         GdkPixbuf *ret;
1183         if (!il) return NULL;
1184
1185         g_mutex_lock(il->data_mutex);
1186         ret = il->pixbuf;
1187         g_mutex_unlock(il->data_mutex);
1188         return ret;
1189 }
1190
1191 void image_loader_set_requested_size(ImageLoader *il, gint width, gint height)
1192 {
1193         if (!il) return;
1194
1195         g_mutex_lock(il->data_mutex);
1196         il->requested_width = width;
1197         il->requested_height = height;
1198         g_mutex_unlock(il->data_mutex);
1199 }
1200
1201 void image_loader_set_buffer_size(ImageLoader *il, guint count)
1202 {
1203         if (!il) return;
1204
1205         g_mutex_lock(il->data_mutex);
1206         il->idle_read_loop_count = count ? count : 1;
1207         g_mutex_unlock(il->data_mutex);
1208 }
1209
1210 void image_loader_set_priority(ImageLoader *il, gint priority)
1211 {
1212         if (!il) return;
1213
1214         if (il->thread) return; /* can't change prio if the thread already runs */
1215         il->idle_priority = priority;
1216 }
1217
1218
1219 gdouble image_loader_get_percent(ImageLoader *il)
1220 {
1221         gdouble ret;
1222         if (!il) return 0.0;
1223
1224         g_mutex_lock(il->data_mutex);
1225         if (il->bytes_total == 0)
1226                 {
1227                 ret = 0.0;
1228                 }
1229         else
1230                 {
1231                 ret = (gdouble)il->bytes_read / il->bytes_total;
1232                 }
1233         g_mutex_unlock(il->data_mutex);
1234         return ret;
1235 }
1236
1237 gboolean image_loader_get_is_done(ImageLoader *il)
1238 {
1239         gboolean ret;
1240         if (!il) return FALSE;
1241
1242         g_mutex_lock(il->data_mutex);
1243         ret = il->done;
1244         g_mutex_unlock(il->data_mutex);
1245
1246         return ret;
1247 }
1248
1249 FileData *image_loader_get_fd(ImageLoader *il)
1250 {
1251         FileData *ret;
1252         if (!il) return NULL;
1253
1254         g_mutex_lock(il->data_mutex);
1255         ret = il->fd;
1256         g_mutex_unlock(il->data_mutex);
1257
1258         return ret;
1259 }
1260
1261 gboolean image_loader_get_shrunk(ImageLoader *il)
1262 {
1263         gboolean ret;
1264         if (!il) return FALSE;
1265
1266         g_mutex_lock(il->data_mutex);
1267         ret = il->shrunk;
1268         g_mutex_unlock(il->data_mutex);
1269         return ret;
1270 }
1271
1272 const gchar *image_loader_get_error(ImageLoader *il)
1273 {
1274         const gchar *ret = NULL;
1275         if (!il) return NULL;
1276         g_mutex_lock(il->data_mutex);
1277         if (il->error) ret = il->error->message;
1278         g_mutex_unlock(il->data_mutex);
1279         return ret;
1280 }
1281
1282
1283 /* FIXME - this can be rather slow and blocks until the size is known */
1284 gboolean image_load_dimensions(FileData *fd, gint *width, gint *height)
1285 {
1286         ImageLoader *il;
1287         gboolean success;
1288
1289         il = image_loader_new(fd);
1290
1291         success = image_loader_start_idle(il);
1292
1293         if (success && il->pixbuf)
1294                 {
1295                 if (width) *width = gdk_pixbuf_get_width(il->pixbuf);
1296                 if (height) *height = gdk_pixbuf_get_height(il->pixbuf);;
1297                 }
1298         else
1299                 {
1300                 if (width) *width = -1;
1301                 if (height) *height = -1;
1302                 }
1303
1304         image_loader_free(il);
1305
1306         return success;
1307 }
1308 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */