65f038a51fdeeafae8b7d6a804970b80eaf8a8f7
[geeqie.git] / src / thumb-standard.cc
1 /*
2  * Copyright (C) 2006 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 "thumb-standard.h"
24
25 #include "cache.h"
26 #include "image-load.h"
27 #include "md5-util.h"
28 #include "pixbuf-util.h"
29 #include "ui-fileops.h"
30 #include "filedata.h"
31 #include "exif.h"
32 #include "metadata.h"
33 #include "color-man.h"
34
35
36 /**
37  * @file
38  * 
39  * This thumbnail caching implementation attempts to conform
40  * to the Thumbnail Managing Standard proposed on freedesktop.org
41  * The standard is documented here: \n
42  *   https://www.freedesktop.org/wiki/Specifications/thumbnails/ \n
43  *
44  * This code attempts to conform to version 0.7.0 of the standard.
45  *
46  * Notes:
47  *   > Validation of the thumb's embedded uri is a simple strcmp between our
48  *   > version of the escaped uri and the thumb's escaped uri. But not all uri
49  *   > escape functions escape the same set of chars, comparing the unescaped
50  *   > versions may be more accurate. \n
51  *   > Only Thumb::URI and Thumb::MTime are stored in a thumb at this time.
52  *     Storing the Size, Width, Height should probably be implemented.
53  */
54
55
56 #define THUMB_SIZE_NORMAL 128
57 #define THUMB_SIZE_LARGE  256
58
59 #define THUMB_MARKER_URI    "tEXt::Thumb::URI"
60 #define THUMB_MARKER_MTIME  "tEXt::Thumb::MTime"
61 #define THUMB_MARKER_SIZE   "tEXt::Thumb::Size"
62 #define THUMB_MARKER_WIDTH  "tEXt::Thumb::Image::Width"
63 #define THUMB_MARKER_HEIGHT "tEXt::Thumb::Image::Height"
64 #define THUMB_MARKER_APP    "tEXt::Software"
65
66 #define THUMB_PERMS_FOLDER 0700
67 #define THUMB_PERMS_THUMB  0600
68
69
70
71 /*
72  *-----------------------------------------------------------------------------
73  * thumbnail loader
74  *-----------------------------------------------------------------------------
75  */
76
77
78 static void thumb_loader_std_error_cb(ImageLoader *il, gpointer data);
79 static gint thumb_loader_std_setup(ThumbLoaderStd *tl, FileData *fd);
80
81
82 ThumbLoaderStd *thumb_loader_std_new(gint width, gint height)
83 {
84         ThumbLoaderStd *tl;
85
86         tl = g_new0(ThumbLoaderStd, 1);
87
88         tl->standard_loader = TRUE;
89         tl->requested_width = width;
90         tl->requested_height = height;
91         tl->cache_enable = options->thumbnails.enable_caching;
92
93         return tl;
94 }
95
96 void thumb_loader_std_set_callbacks(ThumbLoaderStd *tl,
97                                     ThumbLoaderStdFunc func_done,
98                                     ThumbLoaderStdFunc func_error,
99                                     ThumbLoaderStdFunc func_progress,
100                                     gpointer data)
101 {
102         if (!tl) return;
103
104         tl->func_done = func_done;
105         tl->func_error = func_error;
106         tl->func_progress = func_progress;
107         tl->data = data;
108 }
109
110 static void thumb_loader_std_reset(ThumbLoaderStd *tl)
111 {
112         image_loader_free(tl->il);
113         tl->il = NULL;
114
115         file_data_unref(tl->fd);
116         tl->fd = NULL;
117
118         g_free(tl->thumb_path);
119         tl->thumb_path = NULL;
120
121         g_free(tl->thumb_uri);
122         tl->thumb_uri = NULL;
123         tl->local_uri = NULL;
124
125         tl->thumb_path_local = FALSE;
126
127         tl->cache_hit = FALSE;
128
129         tl->source_mtime = 0;
130         tl->source_size = 0;
131         tl->source_mode = 0;
132
133         tl->progress = 0.0;
134 }
135
136 static gchar *thumb_std_cache_path(const gchar *path, const gchar *uri, gboolean local,
137                                    const gchar *cache_subfolder)
138 {
139         gchar *result = NULL;
140         gchar *md5_text;
141         guchar digest[16];
142         gchar *name;
143
144         if (!path || !uri || !cache_subfolder) return NULL;
145
146         md5_get_digest((guchar *)uri, strlen(uri), digest);
147         md5_text = md5_digest_to_text(digest);
148
149         if (!md5_text) return NULL;
150
151         name = g_strconcat(md5_text, THUMB_NAME_EXTENSION, NULL);
152
153         if (local)
154                 {
155                 gchar *base = remove_level_from_path(path);
156
157                 result = g_build_filename(base, THUMB_FOLDER_LOCAL, cache_subfolder, name, NULL);
158                 g_free(base);
159                 }
160         else
161                 {
162                 result = g_build_filename(get_thumbnails_standard_cache_dir(),
163                                                                                                         cache_subfolder, name, NULL);
164                 }
165
166         g_free(name);
167         g_free(md5_text);
168
169         return result;
170 }
171
172 static gchar *thumb_loader_std_cache_path(ThumbLoaderStd *tl, gboolean local, GdkPixbuf *pixbuf, gboolean fail)
173 {
174         const gchar *folder;
175         gint w, h;
176
177         if (!tl->fd || !tl->thumb_uri) return NULL;
178
179         if (pixbuf)
180                 {
181                 w = gdk_pixbuf_get_width(pixbuf);
182                 h = gdk_pixbuf_get_height(pixbuf);
183                 }
184         else
185                 {
186                 w = tl->requested_width;
187                 h = tl->requested_height;
188                 }
189
190         if (fail)
191                 {
192                 folder = THUMB_FOLDER_FAIL;
193                 }
194         else if (w > THUMB_SIZE_NORMAL || h > THUMB_SIZE_NORMAL)
195                 {
196                 folder = THUMB_FOLDER_LARGE;
197                 }
198         else
199                 {
200                 folder = THUMB_FOLDER_NORMAL;
201                 }
202
203         return thumb_std_cache_path(tl->fd->path,
204                                     (local) ?  tl->local_uri : tl->thumb_uri,
205                                     local, folder);
206 }
207
208 static gboolean thumb_loader_std_fail_check(ThumbLoaderStd *tl)
209 {
210         gchar *fail_path;
211         gboolean result = FALSE;
212
213         fail_path = thumb_loader_std_cache_path(tl, FALSE, NULL, TRUE);
214         if (isfile(fail_path))
215                 {
216                 GdkPixbuf *pixbuf;
217
218                 if (tl->cache_retry)
219                         {
220                         pixbuf = NULL;
221                         }
222                 else
223                         {
224                         gchar *pathl;
225
226                         pathl = path_from_utf8(fail_path);
227                         pixbuf = gdk_pixbuf_new_from_file(pathl, NULL);
228                         g_free(pathl);
229                         }
230
231                 if (pixbuf)
232                         {
233                         const gchar *mtime_str;
234
235                         mtime_str = gdk_pixbuf_get_option(pixbuf, THUMB_MARKER_MTIME);
236                         if (mtime_str && strtol(mtime_str, NULL, 10) == tl->source_mtime)
237                                 {
238                                 result = TRUE;
239                                 DEBUG_1("thumb fail valid: %s", tl->fd->path);
240                                 DEBUG_1("           thumb: %s", fail_path);
241                                 }
242
243                         g_object_unref(G_OBJECT(pixbuf));
244                         }
245
246                 if (!result) unlink_file(fail_path);
247                 }
248         g_free(fail_path);
249
250         return result;
251 }
252
253 static gboolean thumb_loader_std_validate(ThumbLoaderStd *tl, GdkPixbuf *pixbuf)
254 {
255         const gchar *valid_uri;
256         const gchar *uri;
257         const gchar *mtime_str;
258         time_t mtime;
259         gint w, h;
260
261         if (!pixbuf) return FALSE;
262
263         w = gdk_pixbuf_get_width(pixbuf);
264         h = gdk_pixbuf_get_height(pixbuf);
265
266         if (w != THUMB_SIZE_NORMAL && w != THUMB_SIZE_LARGE &&
267             h != THUMB_SIZE_NORMAL && h != THUMB_SIZE_LARGE) return FALSE;
268
269         valid_uri = (tl->thumb_path_local) ? tl->local_uri : tl->thumb_uri;
270
271         uri = gdk_pixbuf_get_option(pixbuf, THUMB_MARKER_URI);
272         mtime_str = gdk_pixbuf_get_option(pixbuf, THUMB_MARKER_MTIME);
273
274         if (!mtime_str || !uri || !valid_uri) return FALSE;
275         if (strcmp(uri, valid_uri) != 0) return FALSE;
276
277         mtime = strtol(mtime_str, NULL, 10);
278         if (tl->source_mtime != mtime) return FALSE;
279
280         return TRUE;
281 }
282
283 static void thumb_loader_std_save(ThumbLoaderStd *tl, GdkPixbuf *pixbuf)
284 {
285         gchar *base_path;
286         gchar *tmp_path;
287         gboolean fail;
288
289         if (!tl->cache_enable || tl->cache_hit) return;
290         if (tl->thumb_path) return;
291
292         if (!pixbuf)
293                 {
294                 /* local failures are not stored */
295                 if (tl->cache_local) return;
296
297                 pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8, 1, 1);
298                 fail = TRUE;
299                 }
300         else
301                 {
302                 g_object_ref(G_OBJECT(pixbuf));
303                 fail = FALSE;
304                 }
305
306         tl->thumb_path = thumb_loader_std_cache_path(tl, tl->cache_local, pixbuf, fail);
307         if (!tl->thumb_path)
308                 {
309                 g_object_unref(G_OBJECT(pixbuf));
310                 return;
311                 }
312         tl->thumb_path_local = tl->cache_local;
313
314         /* create thumbnail dir if needed */
315         base_path = remove_level_from_path(tl->thumb_path);
316         if (tl->cache_local)
317                 {
318                 if (!isdir(base_path))
319                         {
320                         struct stat st;
321                         gchar *source_base;
322
323                         source_base = remove_level_from_path(tl->fd->path);
324                         if (stat_utf8(source_base, &st))
325                                 {
326                                 recursive_mkdir_if_not_exists(base_path, st.st_mode);
327                                 }
328                         g_free(source_base);
329                         }
330                 }
331         else
332                 {
333                 recursive_mkdir_if_not_exists(base_path, THUMB_PERMS_FOLDER);
334                 }
335         g_free(base_path);
336
337         DEBUG_1("thumb saving: %s", tl->fd->path);
338         DEBUG_1("       saved: %s", tl->thumb_path);
339
340         /* save thumb, using a temp file then renaming into place */
341         tmp_path = unique_filename(tl->thumb_path, ".tmp", "_", 2);
342         if (tmp_path)
343                 {
344                 const gchar *mark_uri;
345                 gchar *mark_app;
346                 gchar *mark_mtime;
347                 gchar *pathl;
348                 gboolean success;
349
350                 mark_uri = (tl->cache_local) ? tl->local_uri :tl->thumb_uri;
351
352                 mark_app = g_strdup_printf("%s %s", GQ_APPNAME, VERSION);
353                 mark_mtime = g_strdup_printf("%llu", (unsigned long long)tl->source_mtime);
354                 pathl = path_from_utf8(tmp_path);
355                 success = gdk_pixbuf_save(pixbuf, pathl, "png", NULL,
356                                           THUMB_MARKER_URI, mark_uri,
357                                           THUMB_MARKER_MTIME, mark_mtime,
358                                           THUMB_MARKER_APP, mark_app,
359                                           NULL);
360                 if (success)
361                         {
362                         chmod(pathl, (tl->cache_local) ? tl->source_mode : THUMB_PERMS_THUMB);
363                         success = rename_file(tmp_path, tl->thumb_path);
364                         }
365
366                 g_free(pathl);
367
368                 g_free(mark_mtime);
369                 g_free(mark_app);
370
371                 g_free(tmp_path);
372                 if (!success)
373                         {
374                         DEBUG_1("thumb save failed: %s", tl->fd->path);
375                         DEBUG_1("            thumb: %s", tl->thumb_path);
376                         }
377
378                 }
379
380         g_object_unref(G_OBJECT(pixbuf));
381 }
382
383 static void thumb_loader_std_set_fallback(ThumbLoaderStd *tl)
384 {
385         if (tl->fd->thumb_pixbuf) g_object_unref(tl->fd->thumb_pixbuf);
386         tl->fd->thumb_pixbuf = pixbuf_fallback(tl->fd, tl->requested_width, tl->requested_height);
387 }
388
389
390 void thumb_loader_std_calibrate_pixbuf(FileData *fd, GdkPixbuf *pixbuf) {
391         ColorMan *cm = NULL;
392         ExifData *exif = NULL;
393         gint color_profile_from_image = COLOR_PROFILE_NONE;
394         ColorManProfileType input_type = COLOR_PROFILE_MEM;
395         ColorManProfileType screen_type;
396         const gchar *input_file = NULL;
397         guchar *profile = NULL;
398         guint profile_len;
399         gint sw, sh;
400
401         if (!options->thumbnails.use_color_management)
402                 {
403                 return;
404                 }
405
406         sw = gdk_pixbuf_get_width(pixbuf);
407         sh = gdk_pixbuf_get_height(pixbuf);
408
409         exif = exif_read_fd(fd);
410
411         if (exif)
412                 {
413                 if (g_strcmp0(fd->format_name, "heif") == 0)
414                         {
415                         profile = heif_color_profile(fd, &profile_len);
416                         }
417
418                 if (!profile)
419                         {
420                         profile = exif_get_color_profile(exif, &profile_len);
421                         }
422
423                 if (profile)
424                         {
425                         DEBUG_1("Found embedded color profile");
426                         color_profile_from_image = COLOR_PROFILE_MEM;
427                         }
428                 else
429                         {
430                         gchar *interop_index = exif_get_data_as_text(exif, "Exif.Iop.InteroperabilityIndex");
431
432                         if (interop_index)
433                                 {
434                                 /* Exif 2.21 specification */
435                                 if (!strcmp(interop_index, "R98"))
436                                         {
437                                         color_profile_from_image = COLOR_PROFILE_SRGB;
438                                         DEBUG_1("Found EXIF 2.21 ColorSpace of sRGB");
439                                         }
440                                 else if (!strcmp(interop_index, "R03"))
441                                         {
442                                         color_profile_from_image = COLOR_PROFILE_ADOBERGB;
443                                         DEBUG_1("Found EXIF 2.21 ColorSpace of AdobeRGB");
444                                         }
445                                 g_free(interop_index);
446                                 }
447                         else
448                                 {
449                                 gint cs;
450
451                                 /* ColorSpace == 1 specifies sRGB per EXIF 2.2 */
452                                 if (!exif_get_integer(exif, "Exif.Photo.ColorSpace", &cs)) cs = 0;
453                                 if (cs == 1)
454                                         {
455                                         color_profile_from_image = COLOR_PROFILE_SRGB;
456                                         DEBUG_1("Found EXIF 2.2 ColorSpace of sRGB");
457                                         }
458                                 else if (cs == 2)
459                                         {
460                                         /* non-standard way of specifying AdobeRGB (used by some software) */
461                                         color_profile_from_image = COLOR_PROFILE_ADOBERGB;
462                                         DEBUG_1("Found EXIF 2.2 ColorSpace of AdobeRGB");
463                                         }
464                                 }
465                         }
466
467                 if(color_profile_from_image != COLOR_PROFILE_NONE)
468                         {
469                                 // transform image, we always use sRGB as target for thumbnails
470                                 screen_type = COLOR_PROFILE_SRGB;
471
472                                 if (profile)
473                                         {
474                                         cm = color_man_new_embedded(NULL, pixbuf,
475                                                                         profile, profile_len,
476                                                                         screen_type, NULL, NULL, 0);
477                                         g_free(profile);
478                                         }
479                                 else
480                                         {
481                                         cm = color_man_new(NULL, pixbuf,
482                                                         input_type, input_file,
483                                                         screen_type, NULL, NULL, 0);
484                                         }
485
486                                 if(cm) {
487                                         color_man_correct_region(cm, cm->pixbuf, 0, 0, sw, sh);
488                                         g_free(cm);
489                                 }
490
491                         }
492                 exif_free_fd(fd, exif);
493                 }
494 }
495
496 static GdkPixbuf *thumb_loader_std_finish(ThumbLoaderStd *tl, GdkPixbuf *pixbuf, gboolean shrunk)
497 {
498         GdkPixbuf *pixbuf_thumb = NULL;
499         GdkPixbuf *result;
500         GdkPixbuf *rotated = NULL;
501         gint sw, sh;
502
503
504         if (!tl->cache_hit && options->image.exif_rotate_enable)
505                 {
506                 if (!tl->fd->exif_orientation)
507                         {
508                         if (g_strcmp0(tl->fd->format_name, "heif") != 0)
509                                 {
510                                 tl->fd->exif_orientation = metadata_read_int(tl->fd, ORIENTATION_KEY, EXIF_ORIENTATION_TOP_LEFT);
511                                 }
512                         else
513                                 {
514                                 tl->fd->exif_orientation = EXIF_ORIENTATION_TOP_LEFT;
515                                 }
516                         }
517
518                 if (tl->fd->exif_orientation != EXIF_ORIENTATION_TOP_LEFT)
519                         {
520                         rotated = pixbuf_apply_orientation(pixbuf, tl->fd->exif_orientation);
521                         pixbuf = rotated;
522                         }
523                 }
524
525         sw = gdk_pixbuf_get_width(pixbuf);
526         sh = gdk_pixbuf_get_height(pixbuf);
527
528         if (tl->cache_enable)
529                 {
530                 if (!tl->cache_hit)
531                         {
532                         gint cache_w, cache_h;
533
534                         if (tl->requested_width > THUMB_SIZE_NORMAL || tl->requested_height > THUMB_SIZE_NORMAL)
535                                 {
536                                 cache_w = cache_h = THUMB_SIZE_LARGE;
537                                 }
538                         else
539                                 {
540                                 cache_w = cache_h = THUMB_SIZE_NORMAL;
541                                 }
542
543                         if (sw > cache_w || sh > cache_h || shrunk)
544                                 {
545                                 gint thumb_w, thumb_h;
546                                 struct stat st;
547
548                                 if (pixbuf_scale_aspect(cache_w, cache_h, sw, sh,
549                                                                   &thumb_w, &thumb_h))
550                                         {
551                                         pixbuf_thumb = gdk_pixbuf_scale_simple(pixbuf, thumb_w, thumb_h,
552                                                                                (GdkInterpType)options->thumbnails.quality);
553                                         }
554                                 else
555                                         {
556                                         pixbuf_thumb = pixbuf;
557                                         g_object_ref(G_OBJECT(pixbuf_thumb));
558                                         }
559
560                                 /* do not save the thumbnail if the source file has changed meanwhile -
561                                    the thumbnail is most probably broken */
562                                 if (stat_utf8(tl->fd->path, &st) &&
563                                     tl->source_mtime == st.st_mtime &&
564                                     tl->source_size == st.st_size)
565                                         {
566                                         thumb_loader_std_save(tl, pixbuf_thumb);
567                                         }
568                                 }
569                         }
570                 else if (tl->cache_hit &&
571                          tl->cache_local && !tl->thumb_path_local)
572                         {
573                         /* A local cache save was requested, but a valid thumb is in $HOME,
574                          * so specifically save as a local thumbnail.
575                          */
576                         g_free(tl->thumb_path);
577                         tl->thumb_path = NULL;
578
579                         tl->cache_hit = FALSE;
580
581                         DEBUG_1("thumb copied: %s", tl->fd->path);
582
583                         thumb_loader_std_save(tl, pixbuf);
584                         }
585                 }
586
587         if (sw <= tl->requested_width && sh <= tl->requested_height)
588                 {
589                 result = pixbuf;
590                 g_object_ref(result);
591                 }
592         else
593                 {
594                 gint thumb_w, thumb_h;
595
596                 if (pixbuf_thumb)
597                         {
598                         pixbuf = pixbuf_thumb;
599                         sw = gdk_pixbuf_get_width(pixbuf);
600                         sh = gdk_pixbuf_get_height(pixbuf);
601                         }
602
603                 if (pixbuf_scale_aspect(tl->requested_width, tl->requested_height, sw, sh,
604                                                   &thumb_w, &thumb_h))
605                         {
606                         result = gdk_pixbuf_scale_simple(pixbuf, thumb_w, thumb_h,
607                                                          (GdkInterpType)options->thumbnails.quality);
608                         }
609                 else
610                         {
611                         result = pixbuf;
612                         g_object_ref(result);
613                         }
614                 }
615
616         // apply color correction, if required
617         thumb_loader_std_calibrate_pixbuf(tl->fd, result);
618
619         if (pixbuf_thumb) g_object_unref(pixbuf_thumb);
620         if (rotated) g_object_unref(rotated);
621
622         return result;
623 }
624
625 static gboolean thumb_loader_std_next_source(ThumbLoaderStd *tl, gboolean remove_broken)
626 {
627         image_loader_free(tl->il);
628         tl->il = NULL;
629
630         if (tl->thumb_path)
631                 {
632                 if (!tl->thumb_path_local && remove_broken)
633                         {
634                         DEBUG_1("thumb broken, unlinking: %s", tl->thumb_path);
635                         unlink_file(tl->thumb_path);
636                         }
637
638                 g_free(tl->thumb_path);
639                 tl->thumb_path = NULL;
640
641                 if (!tl->thumb_path_local)
642                         {
643                         tl->thumb_path = thumb_loader_std_cache_path(tl, TRUE, NULL, FALSE);
644                         if (isfile(tl->thumb_path))
645                                 {
646                                 FileData *fd = file_data_new_no_grouping(tl->thumb_path);
647                                 if (thumb_loader_std_setup(tl, fd))
648                                         {
649                                         file_data_unref(fd);
650                                         tl->thumb_path_local = TRUE;
651                                         return TRUE;
652                                         }
653                                 file_data_unref(fd);
654                                 }
655
656                         g_free(tl->thumb_path);
657                         tl->thumb_path = NULL;
658                         }
659
660                 if (thumb_loader_std_setup(tl, tl->fd)) return TRUE;
661                 }
662
663         thumb_loader_std_save(tl, NULL);
664         return FALSE;
665 }
666
667 static void thumb_loader_std_done_cb(ImageLoader *il, gpointer data)
668 {
669         ThumbLoaderStd *tl = static_cast<ThumbLoaderStd *>(data);
670         GdkPixbuf *pixbuf;
671
672         DEBUG_1("thumb image done: %s", tl->fd ? tl->fd->path : "???");
673         DEBUG_1("            from: %s", image_loader_get_fd(tl->il)->path);
674
675         pixbuf = image_loader_get_pixbuf(tl->il);
676         if (!pixbuf)
677                 {
678                 DEBUG_1("...but no pixbuf");
679                 thumb_loader_std_error_cb(il, data);
680                 return;
681                 }
682
683         if (tl->thumb_path && !thumb_loader_std_validate(tl, pixbuf))
684                 {
685                 if (thumb_loader_std_next_source(tl, TRUE)) return;
686
687                 if (tl->func_error) tl->func_error(tl, tl->data);
688                 return;
689                 }
690
691         tl->cache_hit = (tl->thumb_path != NULL);
692
693         if (tl->fd)
694                 {
695                 if (tl->fd->thumb_pixbuf) g_object_unref(tl->fd->thumb_pixbuf);
696                 tl->fd->thumb_pixbuf = thumb_loader_std_finish(tl, pixbuf, image_loader_get_shrunk(il));
697                 }
698
699         if (tl->func_done) tl->func_done(tl, tl->data);
700 }
701
702 static void thumb_loader_std_error_cb(ImageLoader *il, gpointer data)
703 {
704         ThumbLoaderStd *tl = static_cast<ThumbLoaderStd *>(data);
705
706         /* if at least some of the image is available, go to done */
707         if (image_loader_get_pixbuf(tl->il) != NULL)
708                 {
709                 thumb_loader_std_done_cb(il, data);
710                 return;
711                 }
712
713         DEBUG_1("thumb image error: %s", tl->fd->path);
714         DEBUG_1("             from: %s", image_loader_get_fd(tl->il)->path);
715
716         if (thumb_loader_std_next_source(tl, TRUE)) return;
717
718         thumb_loader_std_set_fallback(tl);
719
720         if (tl->func_error) tl->func_error(tl, tl->data);
721 }
722
723 static void thumb_loader_std_progress_cb(ImageLoader *UNUSED(il), gdouble percent, gpointer data)
724 {
725         ThumbLoaderStd *tl = static_cast<ThumbLoaderStd *>(data);
726
727         tl->progress = (gdouble)percent;
728
729         if (tl->func_progress) tl->func_progress(tl, tl->data);
730 }
731
732 static gboolean thumb_loader_std_setup(ThumbLoaderStd *tl, FileData *fd)
733 {
734         tl->il = image_loader_new(fd);
735         image_loader_set_priority(tl->il, G_PRIORITY_LOW);
736
737         /* this will speed up jpegs by up to 3x in some cases */
738         if (tl->requested_width <= THUMB_SIZE_NORMAL &&
739             tl->requested_height <= THUMB_SIZE_NORMAL)
740                 {
741                 image_loader_set_requested_size(tl->il, THUMB_SIZE_NORMAL, THUMB_SIZE_NORMAL);
742                 }
743         else
744                 {
745                 image_loader_set_requested_size(tl->il, THUMB_SIZE_LARGE, THUMB_SIZE_LARGE);
746                 }
747
748         g_signal_connect(G_OBJECT(tl->il), "error", (GCallback)thumb_loader_std_error_cb, tl);
749         if (tl->func_progress)
750                 {
751                 g_signal_connect(G_OBJECT(tl->il), "percent", (GCallback)thumb_loader_std_progress_cb, tl);
752                 }
753         g_signal_connect(G_OBJECT(tl->il), "done", (GCallback)thumb_loader_std_done_cb, tl);
754
755         if (image_loader_start(tl->il))
756                 {
757                 return TRUE;
758                 }
759
760         image_loader_free(tl->il);
761         tl->il = NULL;
762         return FALSE;
763 }
764
765 /*
766  * Note: Currently local_cache only specifies where to save a _new_ thumb, if
767  *       a valid existing thumb is found anywhere the local thumb will not be created.
768  */
769 void thumb_loader_std_set_cache(ThumbLoaderStd *tl, gboolean enable_cache, gboolean local, gboolean retry_failed)
770 {
771         if (!tl) return;
772
773         tl->cache_enable = enable_cache;
774         tl->cache_local = local;
775         tl->cache_retry = retry_failed;
776 }
777
778 gboolean thumb_loader_std_start(ThumbLoaderStd *tl, FileData *fd)
779 {
780         static gchar *thumb_cache = NULL;
781         struct stat st;
782
783         if (!tl || !fd) return FALSE;
784
785         thumb_loader_std_reset(tl);
786
787
788         tl->fd = file_data_ref(fd);
789         if (!stat_utf8(fd->path, &st) || (tl->fd->format_class != FORMAT_CLASS_IMAGE && tl->fd->format_class != FORMAT_CLASS_RAWIMAGE && tl->fd->format_class != FORMAT_CLASS_VIDEO && tl->fd->format_class != FORMAT_CLASS_COLLECTION && tl->fd->format_class != FORMAT_CLASS_DOCUMENT && !options->file_filter.disable))
790                 {
791                 thumb_loader_std_set_fallback(tl);
792                 return FALSE;
793                 }
794         tl->source_mtime = st.st_mtime;
795         tl->source_size = st.st_size;
796         tl->source_mode = st.st_mode;
797
798         if (!thumb_cache)
799                 {
800                 thumb_cache = g_strdup(get_thumbnails_standard_cache_dir());
801                 }
802
803         if (strncmp(tl->fd->path, thumb_cache, strlen(thumb_cache)) != 0)
804                 {
805                 gchar *pathl;
806
807                 pathl = path_from_utf8(fd->path);
808                 tl->thumb_uri = g_filename_to_uri(pathl, NULL, NULL);
809                 tl->local_uri = filename_from_path(tl->thumb_uri);
810                 g_free(pathl);
811                 }
812
813         if (tl->cache_enable)
814                 {
815                 gint found;
816
817                 tl->thumb_path = thumb_loader_std_cache_path(tl, FALSE, NULL, FALSE);
818                 tl->thumb_path_local = FALSE;
819
820                 found = isfile(tl->thumb_path);
821                 if (found)
822                         {
823                         FileData *fd = file_data_new_no_grouping(tl->thumb_path);
824                         if (thumb_loader_std_setup(tl, fd))
825                                 {
826                                 file_data_unref(fd);
827                                 return TRUE;
828                                 }
829                         file_data_unref(fd);
830                         }
831
832                 if (thumb_loader_std_fail_check(tl) ||
833                     !thumb_loader_std_next_source(tl, found))
834                         {
835                         thumb_loader_std_set_fallback(tl);
836                         return FALSE;
837                         }
838                 return TRUE;
839                 }
840
841         if (!thumb_loader_std_setup(tl, tl->fd))
842                 {
843                 thumb_loader_std_save(tl, NULL);
844                 thumb_loader_std_set_fallback(tl);
845                 return FALSE;
846                 }
847
848         return TRUE;
849 }
850
851 void thumb_loader_std_free(ThumbLoaderStd *tl)
852 {
853         if (!tl) return;
854
855         thumb_loader_std_reset(tl);
856         g_free(tl);
857 }
858
859 GdkPixbuf *thumb_loader_std_get_pixbuf(ThumbLoaderStd *tl)
860 {
861         GdkPixbuf *pixbuf;
862
863         if (tl && tl->fd && tl->fd->thumb_pixbuf)
864                 {
865                 pixbuf = tl->fd->thumb_pixbuf;
866                 g_object_ref(pixbuf);
867                 }
868         else
869                 {
870                 pixbuf = pixbuf_fallback(NULL, tl->requested_width, tl->requested_height);
871                 }
872
873         return pixbuf;
874 }
875
876
877 typedef struct _ThumbValidate ThumbValidate;
878 struct _ThumbValidate
879 {
880         ThumbLoaderStd *tl;
881         gchar *path;
882         gint days;
883
884         void (*func_valid)(const gchar *path, gboolean valid, gpointer data);
885         gpointer data;
886
887         guint idle_id; /* event source id */
888 };
889
890 static void thumb_loader_std_thumb_file_validate_free(ThumbValidate *tv)
891 {
892         thumb_loader_std_free(tv->tl);
893         g_free(tv->path);
894         g_free(tv);
895 }
896
897 void thumb_loader_std_thumb_file_validate_cancel(ThumbLoaderStd *tl)
898 {
899         ThumbValidate *tv;
900
901         if (!tl) return;
902
903         tv = static_cast<ThumbValidate *>(tl->data);
904
905         if (tv->idle_id)
906                 {
907                 g_source_remove(tv->idle_id);
908                 tv->idle_id = 0;
909                 }
910
911         thumb_loader_std_thumb_file_validate_free(tv);
912 }
913
914 static void thumb_loader_std_thumb_file_validate_finish(ThumbValidate *tv, gboolean valid)
915 {
916         if (tv->func_valid) tv->func_valid(tv->path, valid, tv->data);
917
918         thumb_loader_std_thumb_file_validate_free(tv);
919 }
920
921 static void thumb_loader_std_thumb_file_validate_done_cb(ThumbLoaderStd *UNUSED(tl), gpointer data)
922 {
923         ThumbValidate *tv = static_cast<ThumbValidate *>(data);
924         GdkPixbuf *pixbuf;
925         gboolean valid = FALSE;
926
927         /* get the original thumbnail pixbuf (unrotated, with original options)
928            this is called from image_loader done callback, so tv->tl->il must exist*/
929         pixbuf = image_loader_get_pixbuf(tv->tl->il);
930         if (pixbuf)
931                 {
932                 const gchar *uri;
933                 const gchar *mtime_str;
934
935                 uri = gdk_pixbuf_get_option(pixbuf, THUMB_MARKER_URI);
936                 mtime_str = gdk_pixbuf_get_option(pixbuf, THUMB_MARKER_MTIME);
937                 if (uri && mtime_str)
938                         {
939                         if (strncmp(uri, "file:", strlen("file:")) == 0)
940                                 {
941                                 struct stat st;
942                                 gchar *target;
943
944                                 target = g_filename_from_uri(uri, NULL, NULL);
945                                 if (stat(target, &st) == 0 &&
946                                     st.st_mtime == strtol(mtime_str, NULL, 10))
947                                         {
948                                         valid = TRUE;
949                                         }
950                                 g_free(target);
951                                 }
952                         else
953                                 {
954                                 struct stat st;
955
956                                 DEBUG_1("thumb uri foreign, doing day check: %s", uri);
957
958                                 if (stat_utf8(tv->path, &st))
959                                         {
960                                         time_t now;
961
962                                         now = time(NULL);
963                                         if (st.st_atime >= now - (time_t)tv->days * 24 * 60 * 60)
964                                                 {
965                                                 valid = TRUE;
966                                                 }
967                                         }
968                                 }
969                         }
970                 else
971                         {
972                         DEBUG_1("invalid image found in std cache: %s", tv->path);
973                         }
974                 }
975
976         thumb_loader_std_thumb_file_validate_finish(tv, valid);
977 }
978
979 static void thumb_loader_std_thumb_file_validate_error_cb(ThumbLoaderStd *UNUSED(tl), gpointer data)
980 {
981         ThumbValidate *tv = static_cast<ThumbValidate *>(data);
982
983         thumb_loader_std_thumb_file_validate_finish(tv, FALSE);
984 }
985
986 static gboolean thumb_loader_std_thumb_file_validate_idle_cb(gpointer data)
987 {
988         ThumbValidate *tv = static_cast<ThumbValidate *>(data);
989
990         tv->idle_id = 0;
991         thumb_loader_std_thumb_file_validate_finish(tv, FALSE);
992
993         return FALSE;
994 }
995
996 ThumbLoaderStd *thumb_loader_std_thumb_file_validate(const gchar *thumb_path, gint allowed_days,
997                                                      void (*func_valid)(const gchar *path, gboolean valid, gpointer data),
998                                                      gpointer data)
999 {
1000         ThumbValidate *tv;
1001
1002         tv = g_new0(ThumbValidate, 1);
1003
1004         tv->tl = thumb_loader_std_new(THUMB_SIZE_LARGE, THUMB_SIZE_LARGE);
1005         thumb_loader_std_set_callbacks(tv->tl,
1006                                        thumb_loader_std_thumb_file_validate_done_cb,
1007                                        thumb_loader_std_thumb_file_validate_error_cb,
1008                                        NULL,
1009                                        tv);
1010         thumb_loader_std_reset(tv->tl);
1011
1012         tv->path = g_strdup(thumb_path);
1013         tv->days = allowed_days;
1014         tv->func_valid = func_valid;
1015         tv->data = data;
1016
1017         FileData *fd = file_data_new_no_grouping(thumb_path);
1018         if (!thumb_loader_std_setup(tv->tl, fd))
1019                 {
1020                 tv->idle_id = g_idle_add(thumb_loader_std_thumb_file_validate_idle_cb, tv);
1021                 }
1022         else
1023                 {
1024                 tv->idle_id = 0;
1025                 }
1026
1027         file_data_unref(fd);
1028         return tv->tl;
1029 }
1030
1031 static void thumb_std_maint_remove_one(const gchar *source, const gchar *uri, gboolean local,
1032                                        const gchar *subfolder)
1033 {
1034         gchar *thumb_path;
1035
1036         thumb_path = thumb_std_cache_path(source,
1037                                           (local) ? filename_from_path(uri) : uri,
1038                                           local, subfolder);
1039         if (isfile(thumb_path))
1040                 {
1041                 DEBUG_1("thumb removing: %s", thumb_path);
1042                 unlink_file(thumb_path);
1043                 }
1044         g_free(thumb_path);
1045 }
1046
1047 /* this also removes local thumbnails (the source is gone so it makes sense) */
1048 void thumb_std_maint_removed(const gchar *source)
1049 {
1050         gchar *uri;
1051         gchar *sourcel;
1052
1053         sourcel = path_from_utf8(source);
1054         uri = g_filename_to_uri(sourcel, NULL, NULL);
1055         g_free(sourcel);
1056
1057         /* all this to remove a thumbnail? */
1058
1059         thumb_std_maint_remove_one(source, uri, FALSE, THUMB_FOLDER_NORMAL);
1060         thumb_std_maint_remove_one(source, uri, FALSE, THUMB_FOLDER_LARGE);
1061         thumb_std_maint_remove_one(source, uri, FALSE, THUMB_FOLDER_FAIL);
1062         thumb_std_maint_remove_one(source, uri, TRUE, THUMB_FOLDER_NORMAL);
1063         thumb_std_maint_remove_one(source, uri, TRUE, THUMB_FOLDER_LARGE);
1064
1065         g_free(uri);
1066 }
1067
1068 typedef struct _TMaintMove TMaintMove;
1069 struct _TMaintMove
1070 {
1071         gchar *source;
1072         gchar *dest;
1073
1074         ThumbLoaderStd *tl;
1075         gchar *source_uri;
1076         gchar *thumb_path;
1077
1078         gint pass;
1079 };
1080
1081 static GList *thumb_std_maint_move_list = NULL;
1082 static GList *thumb_std_maint_move_tail = NULL;
1083
1084
1085 static void thumb_std_maint_move_step(TMaintMove *tm);
1086 static gboolean thumb_std_maint_move_idle(gpointer data);
1087
1088
1089 static void thumb_std_maint_move_validate_cb(const gchar *UNUSED(path), gboolean UNUSED(valid), gpointer data)
1090 {
1091         TMaintMove *tm = static_cast<TMaintMove *>(data);
1092         GdkPixbuf *pixbuf;
1093
1094         /* get the original thumbnail pixbuf (unrotated, with original options)
1095            this is called from image_loader done callback, so tm->tl->il must exist*/
1096         pixbuf = image_loader_get_pixbuf(tm->tl->il);
1097         if (pixbuf)
1098                 {
1099                 const gchar *uri;
1100                 const gchar *mtime_str;
1101
1102                 uri = gdk_pixbuf_get_option(pixbuf, THUMB_MARKER_URI);
1103                 mtime_str = gdk_pixbuf_get_option(pixbuf, THUMB_MARKER_MTIME);
1104
1105                 if (uri && mtime_str && strcmp(uri, tm->source_uri) == 0)
1106                         {
1107                         gchar *pathl;
1108
1109                         /* The validation utility abuses ThumbLoader, and we
1110                          * abuse the utility just to load the thumbnail,
1111                          * but the loader needs to look sane for the save to complete.
1112                          */
1113
1114                         tm->tl->cache_enable = TRUE;
1115                         tm->tl->cache_hit = FALSE;
1116                         tm->tl->cache_local = FALSE;
1117                         file_data_unref(tm->tl->fd);
1118                         tm->tl->fd = file_data_new_group(tm->dest);
1119                         tm->tl->source_mtime = strtol(mtime_str, NULL, 10);
1120
1121                         pathl = path_from_utf8(tm->tl->fd->path);
1122                         g_free(tm->tl->thumb_uri);
1123                         tm->tl->thumb_uri = g_filename_to_uri(pathl, NULL, NULL);
1124                         tm->tl->local_uri = filename_from_path(tm->tl->thumb_uri);
1125                         g_free(pathl);
1126
1127                         g_free(tm->tl->thumb_path);
1128                         tm->tl->thumb_path = NULL;
1129                         tm->tl->thumb_path_local = FALSE;
1130
1131                         DEBUG_1("thumb move attempting save:");
1132
1133                         thumb_loader_std_save(tm->tl, pixbuf);
1134                         }
1135
1136                 DEBUG_1("thumb move unlink: %s", tm->thumb_path);
1137                 unlink_file(tm->thumb_path);
1138                 }
1139
1140         thumb_std_maint_move_step(tm);
1141 }
1142
1143 static void thumb_std_maint_move_step(TMaintMove *tm)
1144 {
1145         const gchar *folder;
1146
1147         tm->pass++;
1148         if (tm->pass > 2)
1149                 {
1150                 g_free(tm->source);
1151                 g_free(tm->dest);
1152                 g_free(tm->source_uri);
1153                 g_free(tm->thumb_path);
1154                 g_free(tm);
1155
1156                 if (thumb_std_maint_move_list)
1157                         {
1158                         g_idle_add_full(G_PRIORITY_LOW, thumb_std_maint_move_idle, NULL, NULL);
1159                         }
1160
1161                 return;
1162                 }
1163
1164         folder = (tm->pass == 1) ? THUMB_FOLDER_NORMAL : THUMB_FOLDER_LARGE;
1165
1166         g_free(tm->thumb_path);
1167         tm->thumb_path = thumb_std_cache_path(tm->source, tm->source_uri, FALSE, folder);
1168         tm->tl = thumb_loader_std_thumb_file_validate(tm->thumb_path, 0,
1169                                                       thumb_std_maint_move_validate_cb, tm);
1170 }
1171
1172 static gboolean thumb_std_maint_move_idle(gpointer UNUSED(data))
1173 {
1174         TMaintMove *tm;
1175         gchar *pathl;
1176
1177         if (!thumb_std_maint_move_list) return FALSE;
1178
1179         tm = static_cast<TMaintMove *>(thumb_std_maint_move_list->data);
1180
1181         thumb_std_maint_move_list = g_list_remove(thumb_std_maint_move_list, tm);
1182         if (!thumb_std_maint_move_list) thumb_std_maint_move_tail = NULL;
1183
1184         pathl = path_from_utf8(tm->source);
1185         tm->source_uri = g_filename_to_uri(pathl, NULL, NULL);
1186         g_free(pathl);
1187
1188         tm->pass = 0;
1189
1190         thumb_std_maint_move_step(tm);
1191
1192         return FALSE;
1193 }
1194
1195 /* This will schedule a move of the thumbnail for source image to dest when idle.
1196  * We do this so that file renaming or moving speed is not sacrificed by
1197  * moving the thumbnails at the same time because:
1198  *
1199  * This cache design requires the tedious task of loading the png thumbnails and saving them.
1200  *
1201  * The thumbnails are processed when the app is idle. If the app
1202  * exits early well too bad - they can simply be regenerated from scratch.
1203  */
1204 /** @FIXME This does not manage local thumbnails (fixme ?)
1205  */
1206 void thumb_std_maint_moved(const gchar *source, const gchar *dest)
1207 {
1208         TMaintMove *tm;
1209
1210         tm = g_new0(TMaintMove, 1);
1211         tm->source = g_strdup(source);
1212         tm->dest = g_strdup(dest);
1213
1214         if (!thumb_std_maint_move_list)
1215                 {
1216                 g_idle_add_full(G_PRIORITY_LOW, thumb_std_maint_move_idle, NULL, NULL);
1217                 }
1218
1219         if (thumb_std_maint_move_tail)
1220                 {
1221                 thumb_std_maint_move_tail = g_list_append(thumb_std_maint_move_tail, tm);
1222                 thumb_std_maint_move_tail = thumb_std_maint_move_tail->next;
1223                 }
1224         else
1225                 {
1226                 thumb_std_maint_move_list = g_list_append(thumb_std_maint_move_list, tm);
1227                 thumb_std_maint_move_tail = thumb_std_maint_move_list;
1228                 }
1229 }
1230 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */