Merged changes in the trunk up to revision 44612.
[blender.git] / source / blender / blenlib / intern / bpath.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Campbell barton, Alex Fraser
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenlib/intern/bpath.c
29  *  \ingroup bli
30  */
31
32 /* TODO,
33  * currently there are some cases we dont support.
34  * - passing output paths to the visitor?, like render out.
35  * - passing sequence strips with many images.
36  * - passing directory paths - visitors dont know which path is a dir or a file.
37  * */
38
39 #include <sys/stat.h>
40
41 #include <string.h>
42 #include <assert.h>
43
44 /* path/file handeling stuff */
45 #ifndef WIN32
46   #include <dirent.h>
47   #include <unistd.h>
48 #else
49   #include <io.h>
50   #include "BLI_winstuff.h"
51 #endif
52
53 #include "MEM_guardedalloc.h"
54
55 #include "DNA_brush_types.h"
56 #include "DNA_image_types.h"
57 #include "DNA_mesh_types.h"
58 #include "DNA_modifier_types.h"
59 #include "DNA_movieclip_types.h"
60 #include "DNA_object_fluidsim.h"
61 #include "DNA_object_force.h"
62 #include "DNA_object_types.h"
63 #include "DNA_particle_types.h"
64 #include "DNA_sequence_types.h"
65 #include "DNA_sound_types.h"
66 #include "DNA_text_types.h"
67 #include "DNA_texture_types.h"
68 #include "DNA_vfont_types.h"
69 #include "DNA_scene_types.h"
70 #include "DNA_smoke_types.h"
71 #include "DNA_freestyle_types.h"
72
73 #include "BLI_blenlib.h"
74 #include "BLI_bpath.h"
75 #include "BLI_utildefines.h"
76
77 #include "BKE_library.h"
78 #include "BKE_main.h"
79 #include "BKE_report.h"
80 #include "BKE_sequencer.h"
81 #include "BKE_utildefines.h"
82 #include "BKE_image.h" /* so we can check the image's type */
83
84 static int checkMissingFiles_visit_cb(void *userdata, char *UNUSED(path_dst), const char *path_src)
85 {
86         ReportList *reports= (ReportList *)userdata;
87
88         if (!BLI_exists(path_src)) {
89                 BKE_reportf(reports, RPT_WARNING, "Path Not Found \"%s\"", path_src);
90         }
91
92         return FALSE;
93 }
94
95 /* high level function */
96 void checkMissingFiles(Main *bmain, ReportList *reports)
97 {
98         bpath_traverse_main(bmain, checkMissingFiles_visit_cb, BPATH_TRAVERSE_ABS, reports);
99 }
100
101 typedef struct BPathRemap_Data
102 {
103         const char *basedir;
104         ReportList *reports;
105
106         int count_tot;
107         int count_changed;
108         int count_failed;
109 } BPathRemap_Data;
110
111 static int makeFilesRelative_visit_cb(void *userdata, char *path_dst, const char *path_src)
112 {
113         BPathRemap_Data *data= (BPathRemap_Data *)userdata;
114
115         data->count_tot++;
116
117         if(strncmp(path_src, "//", 2)==0) {
118                 return FALSE; /* already relative */
119         }
120         else {
121                 strcpy(path_dst, path_src);
122                 BLI_path_rel(path_dst, data->basedir);
123                 if (strncmp(path_dst, "//", 2)==0) {
124                         data->count_changed++;
125                 }
126                 else {
127                         BKE_reportf(data->reports, RPT_WARNING, "Path cant be made relative \"%s\"", path_src);
128                         data->count_failed++;
129                 }
130                 return TRUE;
131         }
132 }
133
134 void makeFilesRelative(Main *bmain, const char *basedir, ReportList *reports)
135 {
136         BPathRemap_Data data= {NULL};
137
138         if(basedir[0] == '\0') {
139                 printf("%s: basedir='', this is a bug\n", __func__);
140                 return;
141         }
142
143         data.basedir= basedir;
144         data.reports= reports;
145
146         bpath_traverse_main(bmain, makeFilesRelative_visit_cb, 0, (void *)&data);
147
148         BKE_reportf(reports, data.count_failed ? RPT_WARNING : RPT_INFO,
149                     "Total files %d|Changed %d|Failed %d",
150                     data.count_tot, data.count_changed, data.count_failed);
151 }
152
153 static int makeFilesAbsolute_visit_cb(void *userdata, char *path_dst, const char *path_src)
154 {
155         BPathRemap_Data *data= (BPathRemap_Data *)userdata;
156
157         data->count_tot++;
158
159         if(strncmp(path_src, "//", 2)!=0) {
160                 return FALSE; /* already absolute */
161         }
162         else {
163                 strcpy(path_dst, path_src);
164                 BLI_path_abs(path_dst, data->basedir);
165                 if (strncmp(path_dst, "//", 2)!=0) {
166                         data->count_changed++;
167                 }
168                 else {
169                         BKE_reportf(data->reports, RPT_WARNING, "Path cant be made absolute \"%s\"", path_src);
170                         data->count_failed++;
171                 }
172                 return TRUE;
173         }
174 }
175
176 /* similar to makeFilesRelative - keep in sync! */
177 void makeFilesAbsolute(Main *bmain, const char *basedir, ReportList *reports)
178 {
179         BPathRemap_Data data= {NULL};
180
181         if(basedir[0] == '\0') {
182                 printf("%s: basedir='', this is a bug\n", __func__);
183                 return;
184         }
185
186         data.basedir= basedir;
187         data.reports= reports;
188
189         bpath_traverse_main(bmain, makeFilesAbsolute_visit_cb, 0, (void *)&data);
190
191         BKE_reportf(reports, data.count_failed ? RPT_WARNING : RPT_INFO,
192                     "Total files %d|Changed %d|Failed %d",
193                     data.count_tot, data.count_changed, data.count_failed);
194 }
195
196
197 /* find this file recursively, use the biggest file so thumbnails dont get used by mistake
198  * - dir: subdir to search
199  * - filename: set this filename
200  * - filesize: filesize for the file
201  *
202  * return found: 1/0.
203  */
204 #define MAX_RECUR 16
205 static int findFileRecursive(char *filename_new,
206                              const char *dirname,
207                              const char *filename,
208                              int *filesize,
209                              int *recur_depth)
210 {
211         /* file searching stuff */
212         DIR *dir;
213         struct dirent *de;
214         struct stat status;
215         char path[FILE_MAX];
216         int size;
217         int found = FALSE;
218
219         filename_new[0] = '\0';
220
221         dir= opendir(dirname);
222
223         if (dir==NULL)
224                 return found;
225
226         if (*filesize == -1)
227                 *filesize= 0; /* dir opened fine */
228
229         while ((de= readdir(dir)) != NULL) {
230
231                 if (strcmp(".", de->d_name)==0 || strcmp("..", de->d_name)==0)
232                         continue;
233
234                 BLI_join_dirfile(path, sizeof(path), dirname, de->d_name);
235
236                 if (stat(path, &status) != 0)
237                         continue; /* cant stat, dont bother with this file, could print debug info here */
238
239                 if (S_ISREG(status.st_mode)) { /* is file */
240                         if (strncmp(filename, de->d_name, FILE_MAX)==0) { /* name matches */
241                                 /* open the file to read its size */
242                                 size= status.st_size;
243                                 if ((size > 0) && (size > *filesize)) { /* find the biggest file */
244                                         *filesize= size;
245                                         BLI_strncpy(filename_new, path, FILE_MAX);
246                                         found = TRUE;
247                                 }
248                         }
249                 }
250                 else if (S_ISDIR(status.st_mode)) { /* is subdir */
251                         if (*recur_depth <= MAX_RECUR) {
252                                 (*recur_depth)++;
253                                 found |= findFileRecursive(filename_new, path, filename, filesize, recur_depth);
254                                 (*recur_depth)--;
255                         }
256                 }
257         }
258         closedir(dir);
259         return found;
260 }
261
262 typedef struct BPathFind_Data
263 {
264         const char *basedir;
265         char searchdir[FILE_MAX];
266         ReportList *reports;
267 } BPathFind_Data;
268
269 static int findMissingFiles_visit_cb(void *userdata, char *path_dst, const char *path_src)
270 {
271         BPathFind_Data *data= (BPathFind_Data *)userdata;
272         char filename_new[FILE_MAX];
273
274         int filesize= -1;
275         int recur_depth= 0;
276         int found;
277
278         found = findFileRecursive(filename_new,
279                                   data->searchdir, BLI_path_basename((char *)path_src),
280                                   &filesize, &recur_depth);
281
282         if (filesize == -1) { /* could not open dir */
283                 BKE_reportf(data->reports, RPT_WARNING,
284                             "Could open directory \"%s\"",
285                             BLI_path_basename(data->searchdir));
286                 return FALSE;
287         }
288         else if (found == FALSE) {
289                 BKE_reportf(data->reports, RPT_WARNING,
290                             "Could not find \"%s\" in \"%s\"",
291                             BLI_path_basename((char *)path_src), data->searchdir);
292                 return FALSE;
293         }
294         else {
295                 BLI_strncpy(path_dst, filename_new, FILE_MAX);
296                 return TRUE;
297         }
298 }
299
300 void findMissingFiles(Main *bmain, const char *searchpath, ReportList *reports)
301 {
302         struct BPathFind_Data data= {NULL};
303
304         data.reports= reports;
305         BLI_split_dir_part(searchpath, data.searchdir, sizeof(data.searchdir));
306
307         bpath_traverse_main(bmain, findMissingFiles_visit_cb, 0, (void *)&data);
308 }
309
310 /* Run a visitor on a string, replacing the contents of the string as needed. */
311 static int rewrite_path_fixed(char *path, BPathVisitor visit_cb, const char *absbase, void *userdata)
312 {
313         char path_src_buf[FILE_MAX];
314         const char *path_src;
315         char path_dst[FILE_MAX];
316
317         if (absbase) {
318                 BLI_strncpy(path_src_buf, path, sizeof(path_src_buf));
319                 BLI_path_abs(path_src_buf, absbase);
320                 path_src= path_src_buf;
321         }
322         else {
323                 path_src= path;
324         }
325
326         if (visit_cb(userdata, path_dst, path_src)) {
327                 BLI_strncpy(path, path_dst, FILE_MAX);
328                 return TRUE;
329         }
330         else {
331                 return FALSE;
332         }
333 }
334
335 static int rewrite_path_fixed_dirfile(char path_dir[FILE_MAXDIR],
336                                       char path_file[FILE_MAXFILE],
337                                       BPathVisitor visit_cb,
338                                       const char *absbase,
339                                       void *userdata)
340 {
341         char path_src[FILE_MAX];
342         char path_dst[FILE_MAX];
343
344         BLI_join_dirfile(path_src, sizeof(path_src), path_dir, path_file);
345
346         if (absbase) {
347                 BLI_path_abs(path_src, absbase);
348         }
349
350         if (visit_cb(userdata, path_dst, (const char *)path_src)) {
351                 BLI_split_dirfile(path_dst, path_dir, path_file, FILE_MAXDIR, FILE_MAXFILE);
352                 return TRUE;
353         }
354         else {
355                 return FALSE;
356         }
357 }
358
359 static int rewrite_path_alloc(char **path, BPathVisitor visit_cb, const char *absbase, void *userdata)
360 {
361         char path_src_buf[FILE_MAX];
362         const char *path_src;
363         char path_dst[FILE_MAX];
364
365         if (absbase) {
366                 BLI_strncpy(path_src_buf, *path, sizeof(path_src_buf));
367                 BLI_path_abs(path_src_buf, absbase);
368                 path_src= path_src_buf;
369         }
370         else {
371                 path_src= *path;
372         }
373
374         if (visit_cb(userdata, path_dst, path_src)) {
375                 MEM_freeN((*path));
376                 (*path)= BLI_strdup(path_dst);
377                 return TRUE;
378         }
379         else {
380                 return FALSE;
381         }
382 }
383
384 /* Run visitor function 'visit' on all paths contained in 'id'. */
385 void bpath_traverse_id(Main *bmain, ID *id, BPathVisitor visit_cb, const int flag, void *bpath_user_data)
386 {
387         Image *ima;
388         const char *absbase= (flag & BPATH_TRAVERSE_ABS) ? ID_BLEND_PATH(bmain, id) : NULL;
389
390         if ((flag & BPATH_TRAVERSE_SKIP_LIBRARY) && id->lib) {
391                 return;
392         }
393
394         switch(GS(id->name)) {
395         case ID_IM:
396                 ima= (Image *)id;
397                 if (ima->packedfile == NULL || (flag & BPATH_TRAVERSE_SKIP_PACKED) == 0) {
398                         if (ELEM3(ima->source, IMA_SRC_FILE, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE)) {
399                                 rewrite_path_fixed(ima->name, visit_cb, absbase, bpath_user_data);
400                         }
401                 }
402                 break;
403         case ID_BR:
404                 {
405                         Brush *brush= (Brush *)id;
406                         if (brush->icon_filepath[0]) {
407                                 rewrite_path_fixed(brush->icon_filepath, visit_cb, absbase, bpath_user_data);
408                         }
409                 }
410                 break;
411         case ID_OB:
412
413 #define BPATH_TRAVERSE_POINTCACHE(ptcaches)                                    \
414         {                                                                          \
415                 PointCache *cache;                                                     \
416                 for(cache= (ptcaches).first; cache; cache= cache->next) {              \
417                         if(cache->flag & PTCACHE_DISK_CACHE) {                             \
418                                 rewrite_path_fixed(cache->path,                                \
419                                                    visit_cb,                                   \
420                                                    absbase,                                    \
421                                                    bpath_user_data);                           \
422                         }                                                                  \
423                 }                                                                      \
424         }                                                                          \
425
426
427                 {
428                         Object *ob= (Object *)id;
429                         ModifierData *md;
430                         ParticleSystem *psys;
431
432
433                         /* do via modifiers instead */
434 #if 0
435                         if (ob->fluidsimSettings) {
436                                 rewrite_path_fixed(ob->fluidsimSettings->surfdataPath, visit_cb, absbase, bpath_user_data);
437                         }
438 #endif
439
440                         for (md= ob->modifiers.first; md; md= md->next) {
441                                 if (md->type == eModifierType_Fluidsim) {
442                                         FluidsimModifierData *fluidmd= (FluidsimModifierData *)md;
443                                         if (fluidmd->fss) {
444                                                 rewrite_path_fixed(fluidmd->fss->surfdataPath, visit_cb, absbase, bpath_user_data);
445                                         }
446                                 }
447                                 else if (md->type == eModifierType_Smoke) {
448                                         SmokeModifierData *smd= (SmokeModifierData *)md;
449                                         if(smd->type & MOD_SMOKE_TYPE_DOMAIN) {
450                                                 BPATH_TRAVERSE_POINTCACHE(smd->domain->ptcaches[0]);
451                                         }
452                                 }
453                                 else if (md->type==eModifierType_Cloth) {
454                                         ClothModifierData *clmd= (ClothModifierData*) md;
455                                         BPATH_TRAVERSE_POINTCACHE(clmd->ptcaches);
456                                 }
457                                 else if (md->type==eModifierType_Ocean) {
458                                         OceanModifierData *omd= (OceanModifierData*) md;
459                                         rewrite_path_fixed(omd->cachepath, visit_cb, absbase, bpath_user_data);
460                                 }
461                         }
462
463                         if (ob->soft) {
464                                 BPATH_TRAVERSE_POINTCACHE(ob->soft->ptcaches);
465                         }
466
467                         for (psys= ob->particlesystem.first; psys; psys= psys->next) {
468                                 BPATH_TRAVERSE_POINTCACHE(psys->ptcaches);
469                         }
470                 }
471
472 #undef BPATH_TRAVERSE_POINTCACHE
473
474                 break;
475         case ID_SO:
476                 {
477                         bSound *sound= (bSound *)id;
478                         if (sound->packedfile == NULL || (flag & BPATH_TRAVERSE_SKIP_PACKED) == 0) {
479                                 rewrite_path_fixed(sound->name, visit_cb, absbase, bpath_user_data);
480                         }
481                 }
482                 break;
483         case ID_TXT:
484                 if (((Text*)id)->name) {
485                         rewrite_path_alloc(&((Text *)id)->name, visit_cb, absbase, bpath_user_data);
486                 }
487                 break;
488         case ID_VF:
489                 {
490                         VFont *vf= (VFont *)id;
491                         if (vf->packedfile == NULL || (flag & BPATH_TRAVERSE_SKIP_PACKED) == 0) {
492                                 if (strcmp(vf->name, FO_BUILTIN_NAME) != 0) {
493                                         rewrite_path_fixed(((VFont *)id)->name, visit_cb, absbase, bpath_user_data);
494                                 }
495                         }
496                 }
497                 break;
498         case ID_TE:
499                 {
500                         Tex *tex = (Tex *)id;
501                         if (tex->plugin) {
502                                 /* FIXME: rewrite_path assumes path length of FILE_MAX, but
503                                            tex->plugin->name is 160. ... is this field even a path? */
504                                 //rewrite_path(tex->plugin->name, visit_cb, bpath_user_data);
505                         }
506                         if (tex->type == TEX_VOXELDATA && TEX_VD_IS_SOURCE_PATH(tex->vd->file_format)) {
507                                 rewrite_path_fixed(tex->vd->source_path, visit_cb, absbase, bpath_user_data);
508                         }
509                 }
510                 break;
511
512         case ID_SCE:
513                 {
514                         Scene *scene= (Scene *)id;
515                         SceneRenderLayer *srl= scene->r.layers.first;
516                         if (scene->ed) {
517                                 Sequence *seq;
518
519                                 SEQ_BEGIN(scene->ed, seq) {
520                                         if (SEQ_HAS_PATH(seq)) {
521                                                 if (ELEM(seq->type, SEQ_MOVIE, SEQ_SOUND)) {
522                                                         rewrite_path_fixed_dirfile(seq->strip->dir, seq->strip->stripdata->name,
523                                                                                    visit_cb, absbase, bpath_user_data);
524                                                 }
525                                                 else if (seq->type == SEQ_IMAGE) {
526                                                         /* might want an option not to loop over all strips */
527                                                         StripElem *se= seq->strip->stripdata;
528                                                         int len= MEM_allocN_len(se) / sizeof(*se);
529                                                         int i;
530
531                                                         if (flag & BPATH_TRAVERSE_SKIP_MULTIFILE) {
532                                                                 /* only operate on one path */
533                                                                 len= MIN2(1, len);
534                                                         }
535
536                                                         for(i= 0; i < len; i++, se++) {
537                                                                 rewrite_path_fixed_dirfile(seq->strip->dir, se->name,
538                                                                                            visit_cb, absbase, bpath_user_data);
539                                                         }
540                                                 }
541                                                 else {
542                                                         /* simple case */
543                                                         rewrite_path_fixed(seq->strip->dir, visit_cb, absbase, bpath_user_data);
544                                                 }
545                                         }
546                                         else if (seq->plugin) {
547                                                 rewrite_path_fixed(seq->plugin->name, visit_cb, absbase, bpath_user_data);
548                                         }
549
550                                 }
551                                 SEQ_END
552                         }
553                         for(; srl; srl= srl->next) {
554                                 FreestyleModuleConfig* module= srl->freestyleConfig.modules.first;
555                                 for (; module; module= module->next) {
556                                         rewrite_path_fixed(module->module_path, visit_cb, absbase, bpath_user_data);
557                                 }
558                         }
559                 }
560                 break;
561         case ID_ME:
562                 {
563                         Mesh *me= (Mesh *)id;
564                         if (me->fdata.external) {
565                                 rewrite_path_fixed(me->fdata.external->filename, visit_cb, absbase, bpath_user_data);
566                         }
567                 }
568                 break;
569         case ID_LI:
570                 {
571                         Library *lib= (Library *)id;
572                         if(rewrite_path_fixed(lib->name, visit_cb, absbase, bpath_user_data)) {
573                                 BKE_library_filepath_set(lib, lib->name);
574                         }
575                 }
576                 break;
577         case ID_MC:
578                 {
579                         MovieClip *clip= (MovieClip *)id;
580                         rewrite_path_fixed(clip->name, visit_cb, absbase, bpath_user_data);
581                 }
582                 break;
583         default:
584                 /* Nothing to do for other IDs that don't contain file paths. */
585                 break;
586         }
587 }
588
589 void bpath_traverse_id_list(Main *bmain, ListBase *lb, BPathVisitor visit_cb, const int flag, void *bpath_user_data)
590 {
591         ID *id;
592         for(id= lb->first; id; id= id->next) {
593                 bpath_traverse_id(bmain, id, visit_cb, flag, bpath_user_data);
594         }
595 }
596
597 void bpath_traverse_main(Main *bmain, BPathVisitor visit_cb, const int flag, void *bpath_user_data)
598 {
599         ListBase *lbarray[MAX_LIBARRAY];
600         int a= set_listbasepointers(bmain, lbarray);
601         while(a--) bpath_traverse_id_list(bmain, lbarray[a], visit_cb, flag, bpath_user_data);
602 }
603
604 /* Rewrites a relative path to be relative to the main file - unless the path is
605    absolute, in which case it is not altered. */
606 int bpath_relocate_visitor(void *pathbase_v, char *path_dst, const char *path_src)
607 {
608         /* be sure there is low chance of the path being too short */
609         char filepath[(FILE_MAXDIR * 2) + FILE_MAXFILE];
610         const char *base_new= ((char **)pathbase_v)[0];
611         const char *base_old= ((char **)pathbase_v)[1];
612
613         if (strncmp(base_old, "//", 2) == 0) {
614                 printf("%s: error, old base path '%s' is not absolute.\n",
615                        __func__, base_old);
616                 return FALSE;
617         }
618
619         /* Make referenced file absolute. This would be a side-effect of
620            BLI_cleanup_file, but we do it explicitely so we know if it changed. */
621         BLI_strncpy(filepath, path_src, FILE_MAX);
622         if (BLI_path_abs(filepath, base_old)) {
623                 /* Path was relative and is now absolute. Remap.
624                  * Important BLI_cleanup_dir runs before the path is made relative
625                  * because it wont work for paths that start with "//../" */
626                 BLI_cleanup_file(base_new, filepath);
627                 BLI_path_rel(filepath, base_new);
628                 BLI_strncpy(path_dst, filepath, FILE_MAX);
629                 return TRUE;
630         }
631         else {
632                 /* Path was not relative to begin with. */
633                 return FALSE;
634         }
635 }