6053c5556f16092057f1b069377549d15a9b53e2
[blender-staging.git] / source / blender / imbuf / intern / thumbs.c
1 /**
2  * $Id$ 
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version. 
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2007 Blender Foundation
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): Andrea Weikert.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 #include <stdio.h>
31
32 #include "BKE_global.h"
33 #include "BKE_utildefines.h"
34 #include "BLI_blenlib.h"
35 #include "MEM_guardedalloc.h"
36
37 #include "IMB_imbuf_types.h"
38 #include "IMB_imbuf.h"
39 #include "IMB_thumbs.h"
40 #include "IMB_imginfo.h"
41
42 #include "md5.h"
43
44 #include <ctype.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <time.h>
48 #include <sys/types.h>
49 #include <sys/stat.h>
50 #include <stdio.h>
51
52 #ifdef WIN32
53 #include <windows.h> /* need to include windows.h so _WIN32_IE is defined  */
54 #ifndef _WIN32_IE
55 #define _WIN32_IE 0x0400 /* minimal requirements for SHGetSpecialFolderPath on MINGW MSVC has this defined already */
56 #endif
57 #include <shlobj.h> /* for SHGetSpecialFolderPath, has to be done before BLI_winstuff because 'near' is disabled through BLI_windstuff */
58 #include <process.h> /* getpid */
59 #include <direct.h> /* chdir */
60 #include "BLI_winstuff.h"
61 #else
62 #include <unistd.h>
63 #endif
64
65 #define URI_MAX FILE_MAX*3 + 8
66
67 static int get_thumb_dir( char* dir , ThumbSize size)
68 {
69 #ifdef WIN32
70         /* yes, applications shouldn't store data there, but so does GIMP :)*/
71         SHGetSpecialFolderPath(0, dir, CSIDL_PROFILE, 0);
72 #else
73         char* home = getenv("HOME");
74         if (!home) return 0;
75         BLI_strncpy(dir, home, FILE_MAX);
76 #endif
77         switch(size) {
78                 case THB_NORMAL:
79                         strcat(dir, "/.thumbnails/normal/");
80                         break;
81                 case THB_LARGE:
82                         strcat(dir, "/.thumbnails/large/");
83                         break;
84                 case THB_FAIL:
85                         strcat(dir, "/.thumbnails/fail/blender/");
86                         break;
87                 default:
88                         return 0; /* unknown size */
89         }
90         return 1;
91 }
92
93 /** ----- begin of adapted code from glib ---
94  * The following code is adapted from function g_escape_uri_string from the gnome glib
95  * Source: http://svn.gnome.org/viewcvs/glib/trunk/glib/gconvert.c?view=markup
96  * released under the Gnu General Public License.
97  */
98 typedef enum {
99   UNSAFE_ALL        = 0x1,  /* Escape all unsafe characters   */
100   UNSAFE_ALLOW_PLUS = 0x2,  /* Allows '+'  */
101   UNSAFE_PATH       = 0x8,  /* Allows '/', '&', '=', ':', '@', '+', '$' and ',' */
102   UNSAFE_HOST       = 0x10, /* Allows '/' and ':' and '@' */
103   UNSAFE_SLASHES    = 0x20  /* Allows all characters except for '/' and '%' */
104 } UnsafeCharacterSet;
105
106 static const unsigned char acceptable[96] = {
107   /* A table of the ASCII chars from space (32) to DEL (127) */
108   /*      !    "    #    $    %    &    '    (    )    *    +    ,    -    .    / */ 
109   0x00,0x3F,0x20,0x20,0x28,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x2A,0x28,0x3F,0x3F,0x1C,
110   /* 0    1    2    3    4    5    6    7    8    9    :    ;    <    =    >    ? */
111   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x20,
112   /* @    A    B    C    D    E    F    G    H    I    J    K    L    M    N    O */
113   0x38,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
114   /* P    Q    R    S    T    U    V    W    X    Y    Z    [    \    ]    ^    _ */
115   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
116   /* `    a    b    c    d    e    f    g    h    i    j    k    l    m    n    o */
117   0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
118   /* p    q    r    s    t    u    v    w    x    y    z    {    |    }    ~  DEL */
119   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
120 };
121
122 static const char hex[17] = "0123456789abcdef";
123
124 /* Note: This escape function works on file: URIs, but if you want to
125  * escape something else, please read RFC-2396 */
126 void escape_uri_string (const char *string, char* escaped_string, int len,UnsafeCharacterSet mask)
127 {
128 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
129
130         const char *p;
131         char *q;
132         int c;
133         UnsafeCharacterSet use_mask;
134         use_mask = mask;
135
136         for (q = escaped_string, p = string; (*p != '\0') && len; p++) {
137                 c = (unsigned char) *p;
138                 len--;
139
140                 if (!ACCEPTABLE (c)) {
141                         *q++ = '%'; /* means hex coming */
142                         *q++ = hex[c >> 4];
143                         *q++ = hex[c & 15];
144                 } else {
145                         *q++ = *p;
146                 }
147         }
148   
149         *q = '\0';
150 }
151
152 void to_hex_char(char* hexbytes, const unsigned char* bytes, int len)
153 {
154         const unsigned char *p;
155         char *q;
156
157         for (q = hexbytes, p = bytes; len; p++) {
158                 const unsigned char c = (unsigned char) *p;
159                 len--;
160                 *q++ = hex[c >> 4];
161                 *q++ = hex[c & 15];
162         }
163 }
164
165 /** ----- end of adapted code from glib --- */
166
167 static int uri_from_filename( const char *dir, const char *file, char *uri )
168 {
169         char orig_uri[URI_MAX]; 
170         const char* dirstart = dir;
171         
172 #ifdef WIN32
173         {
174                 char vol[3];
175
176                 BLI_strncpy(orig_uri, "file:///", FILE_MAX);
177                 if (strlen(dir) < 2 && dir[1] != ':') {
178                         /* not a correct absolute path */
179                         return 0;
180                 }
181                 /* on windows, using always uppercase drive/volume letter in uri */
182                 vol[0] = (unsigned char)toupper(dir[0]);
183                 vol[1] = ':';
184                 vol[2] = '\0';
185                 strcat(orig_uri, vol);
186                 dirstart += 2;
187         }
188 #else
189         BLI_strncpy(orig_uri, "file://", FILE_MAX);
190 #endif
191         strcat(orig_uri, dirstart);
192         strcat(orig_uri, file);
193         BLI_char_switch(orig_uri, '\\', '/');
194         
195 #ifdef WITH_ICONV
196         {
197                 char uri_utf8[FILE_MAX*3+8];
198                 escape_uri_string(orig_uri, uri_utf8, FILE_MAX*3+8, UNSAFE_PATH);
199                 BLI_string_to_utf8(uri_utf8, uri, NULL);
200         }
201 #else 
202         escape_uri_string(orig_uri, uri, FILE_MAX*3+8, UNSAFE_PATH);
203 #endif
204         return 1;
205 }
206
207 static void thumbname_from_uri(const char* uri, char* thumb)
208 {
209         char hexdigest[33];
210         unsigned char digest[16];
211
212         md5_buffer( uri, strlen(uri), digest);
213         hexdigest[0] = '\0';
214         to_hex_char(hexdigest, digest, 16);
215         hexdigest[32] = '\0';
216         sprintf(thumb, "%s.png", hexdigest);
217 }
218
219 static int thumbpath_from_uri(const char* uri, char* path, ThumbSize size)
220 {
221         char tmppath[FILE_MAX];
222         int rv = 0;
223
224         if (get_thumb_dir(tmppath, size)) {
225                 char thumb[40];
226                 thumbname_from_uri(uri, thumb);
227                 BLI_snprintf(path, FILE_MAX, "%s%s", tmppath, thumb);
228                 rv = 1;
229         }
230         return rv;
231 }
232
233 void IMB_thumb_makedirs()
234 {
235         char tpath[FILE_MAX];
236         if (get_thumb_dir(tpath, THB_NORMAL)) {
237                 BLI_recurdir_fileops(tpath);
238         }
239         if (get_thumb_dir(tpath, THB_FAIL)) {
240                 BLI_recurdir_fileops(tpath);
241         }
242 }
243
244 /* create thumbnail for file and returns new imbuf for thumbnail */
245 ImBuf* IMB_thumb_create(const char* dir, const char* file, ThumbSize size, ThumbSource source)
246 {
247         ImBuf *img = 0;
248         char uri[URI_MAX];
249         char desc[URI_MAX+22];
250         char tpath[FILE_MAX];
251         char tdir[FILE_MAX];
252         char wdir[FILE_MAX];
253         char temp[FILE_MAX];
254         char mtime[40];
255         char cwidth[40];
256         char cheight[40];
257         char thumb[40];
258         short tsize = 128;
259         short ex, ey;
260         float scaledx, scaledy; 
261         struct stat info;
262
263         switch(size) {
264                 case THB_NORMAL:
265                         tsize = 128;
266                         break;
267                 case THB_LARGE:
268                         tsize = 256;
269                         break;
270                 case THB_FAIL:
271                         tsize = 0;
272                         break;
273                 default:
274                         return 0; /* unknown size */
275         }
276
277         uri_from_filename(dir, file,uri);
278         thumbname_from_uri(uri, thumb);
279         if (get_thumb_dir(tdir, size)) {
280                 BLI_snprintf(tpath, FILE_MAX, "%s%s", tdir, thumb);
281                 thumb[8] = '\0'; /* shorten for tempname, not needed anymore */
282                 BLI_snprintf(temp, FILE_MAX, "%sblender_%d_%s.png", tdir, abs(getpid()), thumb);
283                 if (strncmp(thumb, dir, strlen(dir)) == 0) {
284                         return NULL;
285                 }
286                 if (size == THB_FAIL) {
287                         img = IMB_allocImBuf(0,0,32, IB_rect | IB_imginfo, 0);
288                         if (!img) return 0;
289                 } else {
290                         if (THB_SOURCE_IMAGE == source) {
291                                 BLI_getwdN(wdir);
292                                 chdir(dir);
293                                 img = IMB_loadiffname(file, IB_rect | IB_imginfo);
294                                 if (img != NULL) {
295                                         stat(file, &info);
296                                         sprintf(mtime, "%ld", info.st_mtime);
297                                         sprintf(cwidth, "%d", img->x);
298                                         sprintf(cheight, "%d", img->y);
299                                         chdir(wdir);
300                                 }
301                         } else if (THB_SOURCE_MOVIE == source) {
302                                 struct anim * anim = NULL;
303                                 BLI_getwdN(wdir);
304                                 chdir(dir);
305                                 anim = IMB_open_anim(file, IB_rect | IB_imginfo);
306                                 if (anim != NULL) {
307                                         img = IMB_anim_absolute(anim, 0);
308                                         if (img == NULL) {
309                                                 printf("not an anim; %s\n", file);
310                                         } else {
311                                                 IMB_freeImBuf(img);
312                                                 img = IMB_anim_previewframe(anim);                                              
313                                         }
314                                         IMB_free_anim(anim);
315                                 }
316                                 stat(file, &info);
317                                 sprintf(mtime, "%ld", info.st_mtime);
318                                 chdir(wdir);
319                         }
320                         if (!img) return 0;             
321
322                         if (img->x > img->y) {
323                                 scaledx = (float)tsize;
324                                 scaledy =  ( (float)img->y/(float)img->x )*tsize;
325                         }
326                         else {
327                                 scaledy = (float)tsize;
328                                 scaledx =  ( (float)img->x/(float)img->y )*tsize;
329                         }
330                         ex = (short)scaledx;
331                         ey = (short)scaledy;
332                         
333                         IMB_scaleImBuf(img, ex, ey);
334                 }
335                 sprintf(desc, "Thumbnail for %s", uri);
336                 IMB_imginfo_change_field(img, "Description", desc);
337                 IMB_imginfo_change_field(img, "Software", "Blender");
338                 IMB_imginfo_change_field(img, "Thumb::URI", uri);
339                 IMB_imginfo_change_field(img, "Thumb::MTime", mtime);
340                 if (THB_SOURCE_IMAGE == source) {
341                         IMB_imginfo_change_field(img, "Thumb::Image::Width", cwidth);
342                         IMB_imginfo_change_field(img, "Thumb::Image::Height", cheight);
343                 }
344                 img->ftype = PNG;
345                 img->depth = 32;                
346                 if (IMB_saveiff(img, temp, IB_rect | IB_imginfo)) {
347 #ifndef WIN32
348                         chmod(temp, S_IRUSR | S_IWUSR);
349 #endif
350                         BLI_rename(temp, tpath);
351                 }
352
353                 return img;
354         }
355         return img;
356 }
357
358 /* read thumbnail for file and returns new imbuf for thumbnail */
359 ImBuf* IMB_thumb_read(const char* dir, const char* file, ThumbSize size)
360 {
361         char thumb[FILE_MAX];
362         char uri[FILE_MAX*3+8];
363         ImBuf *img = 0;
364
365         if (!uri_from_filename(dir, file,uri)) {
366                 return NULL;
367         }
368         if (thumbpath_from_uri(uri, thumb, size)) {             
369                 img = IMB_loadiffname(thumb, IB_rect | IB_imginfo);
370         }
371
372         return img;
373 }
374
375 /* delete all thumbs for the file */
376 void IMB_thumb_delete(const char* dir, const char* file, ThumbSize size)
377 {
378         char thumb[FILE_MAX];
379         char uri[FILE_MAX*3+8];
380
381         if (!uri_from_filename(dir, file,uri)) {
382                 return;
383         }
384         if (thumbpath_from_uri(uri, thumb, size)) {
385                 if (strncmp(thumb, dir, strlen(dir)) == 0) {
386                         return;
387                 }
388                 if (BLI_exists(thumb)) {
389                         BLI_delete(thumb, 0, 0);
390                 }
391         }
392 }
393
394
395 /* create the thumb if necessary and manage failed and old thumbs */
396 ImBuf* IMB_thumb_manage(const char* dir, const char* file, ThumbSize size, ThumbSource source)
397 {
398         char path[FILE_MAX];
399         char thumb[FILE_MAX];
400         char uri[FILE_MAX*3+8];
401         struct stat st;
402         ImBuf* img = NULL;
403
404         BLI_join_dirfile(path, dir, file);
405         if (stat(path, &st)) {
406                 return NULL;
407         }       
408         if (!uri_from_filename(dir, file,uri)) {
409                 return NULL;
410         }
411         if (thumbpath_from_uri(uri, thumb, THB_FAIL)) {
412                 /* failure thumb exists, don't try recreating */
413                 if (BLI_exists(thumb)) {
414                         return NULL;
415                 }
416         }
417
418         if (thumbpath_from_uri(uri, thumb, size)) {
419                 if (strncmp(thumb, dir, strlen(dir)) == 0) {
420                         img = IMB_loadiffname(path, IB_rect);
421                 } else {
422                         img = IMB_loadiffname(thumb, IB_rect | IB_imginfo);
423                         if (img) {
424                                 char mtime[40];
425                                 if (!IMB_imginfo_get_field(img, "Thumb::MTime", mtime, 40)) {
426                                         /* illegal thumb, forget it! */
427                                         IMB_freeImBuf(img);
428                                         img = 0;
429                                 } else {
430                                         time_t t = atol(mtime);
431                                         if (st.st_mtime != t) {
432                                                 /* recreate all thumbs */
433                                                 IMB_freeImBuf(img);
434                                                 img = 0;
435                                                 IMB_thumb_delete(dir, file, THB_NORMAL);
436                                                 IMB_thumb_delete(dir, file, THB_LARGE);
437                                                 IMB_thumb_delete(dir, file, THB_FAIL);
438                                                 img = IMB_thumb_create(dir, file, size, source);
439                                                 if(!img){
440                                                         /* thumb creation failed, write fail thumb */
441                                                         img = IMB_thumb_create(dir, file, THB_FAIL, source);
442                                                         if (img) {
443                                                                 /* we don't need failed thumb anymore */
444                                                                 IMB_freeImBuf(img);
445                                                                 img = 0;
446                                                         }
447                                                 }
448                                         }
449                                 }
450                         } else {
451                                 img = IMB_thumb_create(dir, file, size, source);
452                                 if(!img){
453                                         /* thumb creation failed, write fail thumb */
454                                         img = IMB_thumb_create(dir, file, THB_FAIL, source);
455                                         if (img) {
456                                                 /* we don't need failed thumb anymore */
457                                                 IMB_freeImBuf(img);
458                                                 img = 0;
459                                         }
460                                 }
461                         }
462                 }
463         }
464
465         return img;
466 }
467
468