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