Fix for movie clips weren't remapped properly on file save
[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
72 #include "BLI_blenlib.h"
73 #include "BLI_bpath.h"
74 #include "BLI_utildefines.h"
75
76 #include "BKE_library.h"
77 #include "BKE_main.h"
78 #include "BKE_report.h"
79 #include "BKE_sequencer.h"
80 #include "BKE_utildefines.h"
81 #include "BKE_image.h" /* so we can check the image's type */
82
83 static int checkMissingFiles_visit_cb(void *userdata, char *UNUSED(path_dst), const char *path_src)
84 {
85         ReportList *reports= (ReportList *)userdata;
86
87         if (!BLI_exists(path_src)) {
88                 BKE_reportf(reports, RPT_WARNING, "Path Not Found \"%s\"", path_src);
89         }
90
91         return FALSE;
92 }
93
94 /* high level function */
95 void checkMissingFiles(Main *bmain, ReportList *reports)
96 {
97         bpath_traverse_main(bmain, checkMissingFiles_visit_cb, BPATH_TRAVERSE_ABS, reports);
98 }
99
100 typedef struct BPathRemap_Data
101 {
102         const char *basedir;
103         ReportList *reports;
104
105         int count_tot;
106         int count_changed;
107         int count_failed;
108 } BPathRemap_Data;
109
110 static int makeFilesRelative_visit_cb(void *userdata, char *path_dst, const char *path_src)
111 {
112         BPathRemap_Data *data= (BPathRemap_Data *)userdata;
113
114         data->count_tot++;
115
116         if(strncmp(path_src, "//", 2)==0) {
117                 return FALSE; /* already relative */
118         }
119         else {
120                 strcpy(path_dst, path_src);
121                 BLI_path_rel(path_dst, data->basedir);
122                 if (strncmp(path_dst, "//", 2)==0) {
123                         data->count_changed++;
124                 }
125                 else {
126                         BKE_reportf(data->reports, RPT_WARNING, "Path cant be made relative \"%s\"", path_src);
127                         data->count_failed++;
128                 }
129                 return TRUE;
130         }
131 }
132
133 void makeFilesRelative(Main *bmain, const char *basedir, ReportList *reports)
134 {
135         BPathRemap_Data data= {NULL};
136
137         if(basedir[0] == '\0') {
138                 printf("%s: basedir='', this is a bug\n", __func__);
139                 return;
140         }
141
142         data.basedir= basedir;
143         data.reports= reports;
144
145         bpath_traverse_main(bmain, makeFilesRelative_visit_cb, 0, (void *)&data);
146
147         BKE_reportf(reports, data.count_failed ? RPT_WARNING : RPT_INFO,
148                     "Total files %d|Changed %d|Failed %d",
149                     data.count_tot, data.count_changed, data.count_failed);
150 }
151
152 static int makeFilesAbsolute_visit_cb(void *userdata, char *path_dst, const char *path_src)
153 {
154         BPathRemap_Data *data= (BPathRemap_Data *)userdata;
155
156         data->count_tot++;
157
158         if(strncmp(path_src, "//", 2)!=0) {
159                 return FALSE; /* already absolute */
160         }
161         else {
162                 strcpy(path_dst, path_src);
163                 BLI_path_abs(path_dst, data->basedir);
164                 if (strncmp(path_dst, "//", 2)!=0) {
165                         data->count_changed++;
166                 }
167                 else {
168                         BKE_reportf(data->reports, RPT_WARNING, "Path cant be made absolute \"%s\"", path_src);
169                         data->count_failed++;
170                 }
171                 return TRUE;
172         }
173 }
174
175 /* similar to makeFilesRelative - keep in sync! */
176 void makeFilesAbsolute(Main *bmain, const char *basedir, ReportList *reports)
177 {
178         BPathRemap_Data data= {NULL};
179
180         if(basedir[0] == '\0') {
181                 printf("%s: basedir='', this is a bug\n", __func__);
182                 return;
183         }
184
185         data.basedir= basedir;
186         data.reports= reports;
187
188         bpath_traverse_main(bmain, makeFilesAbsolute_visit_cb, 0, (void *)&data);
189
190         BKE_reportf(reports, data.count_failed ? RPT_WARNING : RPT_INFO,
191                     "Total files %d|Changed %d|Failed %d",
192                     data.count_tot, data.count_changed, data.count_failed);
193 }
194
195
196 /* find this file recursively, use the biggest file so thumbnails dont get used by mistake
197  - dir: subdir to search
198  - filename: set this filename
199  - filesize: filesize for the file
200 */
201 #define MAX_RECUR 16
202 static int findFileRecursive(char *filename_new, const char *dirname, const char *filename, int *filesize, int *recur_depth)
203 {
204         /* file searching stuff */
205         DIR *dir;
206         struct dirent *de;
207         struct stat status;
208         char path[FILE_MAX];
209         int size;
210
211         dir= opendir(dirname);
212
213         if (dir==NULL)
214                 return 0;
215
216         if (*filesize == -1)
217                 *filesize= 0; /* dir opened fine */
218
219         while ((de= readdir(dir)) != NULL) {
220
221                 if (strcmp(".", de->d_name)==0 || strcmp("..", de->d_name)==0)
222                         continue;
223
224                 BLI_join_dirfile(path, sizeof(path), dirname, de->d_name);
225
226                 if (stat(path, &status) != 0)
227                         continue; /* cant stat, dont bother with this file, could print debug info here */
228
229                 if (S_ISREG(status.st_mode)) { /* is file */
230                         if (strncmp(filename, de->d_name, FILE_MAX)==0) { /* name matches */
231                                 /* open the file to read its size */
232                                 size= status.st_size;
233                                 if ((size > 0) && (size > *filesize)) { /* find the biggest file */
234                                         *filesize= size;
235                                         BLI_strncpy(filename_new, path, FILE_MAX);
236                                 }
237                         }
238                 }
239                 else if (S_ISDIR(status.st_mode)) { /* is subdir */
240                         if (*recur_depth <= MAX_RECUR) {
241                                 (*recur_depth)++;
242                                 findFileRecursive(filename_new, path, filename, filesize, recur_depth);
243                                 (*recur_depth)--;
244                         }
245                 }
246         }
247         closedir(dir);
248         return 1;
249 }
250
251 typedef struct BPathFind_Data
252 {
253         const char *basedir;
254         char searchdir[FILE_MAX];
255         ReportList *reports;
256 } BPathFind_Data;
257
258 static int findMissingFiles_visit_cb(void *userdata, char *path_dst, const char *path_src)
259 {
260         BPathFind_Data *data= (BPathFind_Data *)userdata;
261         char filename_new[FILE_MAX];
262
263         int filesize= -1;
264         int recur_depth= 0;
265
266         findFileRecursive(filename_new,
267                           data->searchdir, BLI_path_basename((char *)path_src),
268                           &filesize, &recur_depth);
269
270         if (filesize == -1) { /* could not open dir */
271                 BKE_reportf(data->reports, RPT_WARNING,
272                             "Could not find \"%s\" in \"%s\"",
273                             BLI_path_basename((char *)path_src), data->searchdir);
274                 return FALSE;
275         }
276         else {
277                 strcpy(path_dst, filename_new);
278                 return TRUE;
279         }
280 }
281
282 void findMissingFiles(Main *bmain, const char *searchpath, ReportList *reports)
283 {
284         struct BPathFind_Data data= {NULL};
285
286         data.reports= reports;
287         BLI_split_dir_part(searchpath, data.searchdir, sizeof(data.searchdir));
288
289         bpath_traverse_main(bmain, findMissingFiles_visit_cb, 0, (void *)&data);
290 }
291
292 /* Run a visitor on a string, replacing the contents of the string as needed. */
293 static int rewrite_path_fixed(char *path, BPathVisitor visit_cb, const char *absbase, void *userdata)
294 {
295         char path_src_buf[FILE_MAX];
296         const char *path_src;
297         char path_dst[FILE_MAX];
298
299         if (absbase) {
300                 BLI_strncpy(path_src_buf, path, sizeof(path_src_buf));
301                 BLI_path_abs(path_src_buf, absbase);
302                 path_src= path_src_buf;
303         }
304         else {
305                 path_src= path;
306         }
307
308         if (visit_cb(userdata, path_dst, path_src)) {
309                 BLI_strncpy(path, path_dst, FILE_MAX);
310                 return TRUE;
311         }
312         else {
313                 return FALSE;
314         }
315 }
316
317 static int rewrite_path_fixed_dirfile(char path_dir[FILE_MAXDIR], char path_file[FILE_MAXFILE], BPathVisitor visit_cb, const char *absbase, void *userdata)
318 {
319         char path_src[FILE_MAX];
320         char path_dst[FILE_MAX];
321
322         BLI_join_dirfile(path_src, sizeof(path_src), path_dir, path_file);
323
324         if (absbase) {
325                 BLI_path_abs(path_src, absbase);
326         }
327
328         if (visit_cb(userdata, path_dst, (const char *)path_src)) {
329                 BLI_split_dirfile(path_dst, path_dir, path_file, FILE_MAXDIR, FILE_MAXFILE);
330                 return TRUE;
331         }
332         else {
333                 return FALSE;
334         }
335 }
336
337 static int rewrite_path_alloc(char **path, BPathVisitor visit_cb, const char *absbase, void *userdata)
338 {
339         char path_src_buf[FILE_MAX];
340         const char *path_src;
341         char path_dst[FILE_MAX];
342
343         if (absbase) {
344                 BLI_strncpy(path_src_buf, *path, sizeof(path_src_buf));
345                 BLI_path_abs(path_src_buf, absbase);
346                 path_src= path_src_buf;
347         }
348         else {
349                 path_src= *path;
350         }
351
352         if (visit_cb(userdata, path_dst, path_src)) {
353                 MEM_freeN((*path));
354                 (*path)= BLI_strdup(path_dst);
355                 return TRUE;
356         }
357         else {
358                 return FALSE;
359         }
360 }
361
362 /* Run visitor function 'visit' on all paths contained in 'id'. */
363 void bpath_traverse_id(Main *bmain, ID *id, BPathVisitor visit_cb, const int flag, void *bpath_user_data)
364 {
365         Image *ima;
366         const char *absbase= (flag & BPATH_TRAVERSE_ABS) ? ID_BLEND_PATH(bmain, id) : NULL;
367
368         if ((flag & BPATH_TRAVERSE_SKIP_LIBRARY) && id->lib) {
369                 return;
370         }
371
372         switch(GS(id->name)) {
373         case ID_IM:
374                 ima= (Image *)id;
375                 if (ima->packedfile == NULL || (flag & BPATH_TRAVERSE_SKIP_PACKED) == 0) {
376                         if (ELEM3(ima->source, IMA_SRC_FILE, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE)) {
377                                 rewrite_path_fixed(ima->name, visit_cb, absbase, bpath_user_data);
378                         }
379                 }
380                 break;
381         case ID_BR:
382                 {
383                         Brush *brush= (Brush *)id;
384                         if (brush->icon_filepath[0]) {
385                                 rewrite_path_fixed(brush->icon_filepath, visit_cb, absbase, bpath_user_data);
386                         }
387                 }
388                 break;
389         case ID_OB:
390
391 #define BPATH_TRAVERSE_POINTCACHE(ptcaches)                                    \
392         {                                                                          \
393                 PointCache *cache;                                                     \
394                 for(cache= (ptcaches).first; cache; cache= cache->next) {              \
395                         if(cache->flag & PTCACHE_DISK_CACHE) {                             \
396                                 rewrite_path_fixed(cache->path,                                \
397                                                    visit_cb,                                   \
398                                                    absbase,                                    \
399                                                    bpath_user_data);                           \
400                         }                                                                  \
401                 }                                                                      \
402         }                                                                          \
403
404
405                 {
406                         Object *ob= (Object *)id;
407                         ModifierData *md;
408                         ParticleSystem *psys;
409
410
411                         /* do via modifiers instead */
412 #if 0
413                         if (ob->fluidsimSettings) {
414                                 rewrite_path_fixed(ob->fluidsimSettings->surfdataPath, visit_cb, absbase, bpath_user_data);
415                         }
416 #endif
417
418                         for (md= ob->modifiers.first; md; md= md->next) {
419                                 if (md->type == eModifierType_Fluidsim) {
420                                         FluidsimModifierData *fluidmd= (FluidsimModifierData *)md;
421                                         if (fluidmd->fss) {
422                                                 rewrite_path_fixed(fluidmd->fss->surfdataPath, visit_cb, absbase, bpath_user_data);
423                                         }
424                                 }
425                                 else if (md->type == eModifierType_Smoke) {
426                                         SmokeModifierData *smd= (SmokeModifierData *)md;
427                                         if(smd->type & MOD_SMOKE_TYPE_DOMAIN) {
428                                                 BPATH_TRAVERSE_POINTCACHE(smd->domain->ptcaches[0]);
429                                         }
430                                 }
431                                 else if (md->type==eModifierType_Cloth) {
432                                         ClothModifierData *clmd= (ClothModifierData*) md;
433                                         BPATH_TRAVERSE_POINTCACHE(clmd->ptcaches);
434                                 }
435                                 else if (md->type==eModifierType_Ocean) {
436                                         OceanModifierData *omd= (OceanModifierData*) md;
437                                         rewrite_path_fixed(omd->cachepath, visit_cb, absbase, bpath_user_data);
438                                 }
439                         }
440
441                         if (ob->soft) {
442                                 BPATH_TRAVERSE_POINTCACHE(ob->soft->ptcaches);
443                         }
444
445                         for (psys= ob->particlesystem.first; psys; psys= psys->next) {
446                                 BPATH_TRAVERSE_POINTCACHE(psys->ptcaches);
447                         }
448                 }
449
450 #undef BPATH_TRAVERSE_POINTCACHE
451
452                 break;
453         case ID_SO:
454                 {
455                         bSound *sound= (bSound *)id;
456                         if (sound->packedfile == NULL || (flag & BPATH_TRAVERSE_SKIP_PACKED) == 0) {
457                                 rewrite_path_fixed(sound->name, visit_cb, absbase, bpath_user_data);
458                         }
459                 }
460                 break;
461         case ID_TXT:
462                 if (((Text*)id)->name) {
463                         rewrite_path_alloc(&((Text *)id)->name, visit_cb, absbase, bpath_user_data);
464                 }
465                 break;
466         case ID_VF:
467                 {
468                         VFont *vf= (VFont *)id;
469                         if (vf->packedfile == NULL || (flag & BPATH_TRAVERSE_SKIP_PACKED) == 0) {
470                                 if (strcmp(vf->name, FO_BUILTIN_NAME) != 0) {
471                                         rewrite_path_fixed(((VFont *)id)->name, visit_cb, absbase, bpath_user_data);
472                                 }
473                         }
474                 }
475                 break;
476         case ID_TE:
477                 {
478                         Tex *tex = (Tex *)id;
479                         if (tex->plugin) {
480                                 /* FIXME: rewrite_path assumes path length of FILE_MAX, but
481                                            tex->plugin->name is 160. ... is this field even a path? */
482                                 //rewrite_path(tex->plugin->name, visit_cb, bpath_user_data);
483                         }
484                         if (tex->type == TEX_VOXELDATA && TEX_VD_IS_SOURCE_PATH(tex->vd->file_format)) {
485                                 rewrite_path_fixed(tex->vd->source_path, visit_cb, absbase, bpath_user_data);
486                         }
487                 }
488                 break;
489
490         case ID_SCE:
491                 {
492                         Scene *scene= (Scene *)id;
493                         if (scene->ed) {
494                                 Sequence *seq;
495
496                                 SEQ_BEGIN(scene->ed, seq) {
497                                         if (SEQ_HAS_PATH(seq)) {
498                                                 if (ELEM(seq->type, SEQ_MOVIE, SEQ_SOUND)) {
499                                                         rewrite_path_fixed_dirfile(seq->strip->dir, seq->strip->stripdata->name, visit_cb, absbase, bpath_user_data);
500                                                 }
501                                                 else if (seq->type == SEQ_IMAGE) {
502                                                         /* might want an option not to loop over all strips */
503                                                         StripElem *se= seq->strip->stripdata;
504                                                         int len= MEM_allocN_len(se) / sizeof(*se);
505                                                         int i;
506
507                                                         if (flag & BPATH_TRAVERSE_SKIP_MULTIFILE) {
508                                                                 /* only operate on one path */
509                                                                 len= MIN2(1, len);
510                                                         }
511
512                                                         for(i= 0; i < len; i++, se++) {
513                                                                 rewrite_path_fixed_dirfile(seq->strip->dir, se->name, visit_cb, absbase, bpath_user_data);
514                                                         }
515                                                 }
516                                                 else {
517                                                         /* simple case */
518                                                         rewrite_path_fixed(seq->strip->dir, visit_cb, absbase, bpath_user_data);
519                                                 }
520                                         }
521                                         else if (seq->plugin) {
522                                                 rewrite_path_fixed(seq->plugin->name, visit_cb, absbase, bpath_user_data);
523                                         }
524
525                                 }
526                                 SEQ_END
527                         }
528                 }
529                 break;
530         case ID_ME:
531                 {
532                         Mesh *me= (Mesh *)id;
533                         if (me->fdata.external) {
534                                 rewrite_path_fixed(me->fdata.external->filename, visit_cb, absbase, bpath_user_data);
535                         }
536                 }
537                 break;
538         case ID_LI:
539                 {
540                         Library *lib= (Library *)id;
541                         if(rewrite_path_fixed(lib->name, visit_cb, absbase, bpath_user_data)) {
542                                 BKE_library_filepath_set(lib, lib->name);
543                         }
544                 }
545                 break;
546         case ID_MC:
547                 {
548                         MovieClip *clip= (MovieClip *)id;
549                         rewrite_path_fixed(clip->name, visit_cb, absbase, bpath_user_data);
550                 }
551                 break;
552         default:
553                 /* Nothing to do for other IDs that don't contain file paths. */
554                 break;
555         }
556 }
557
558 void bpath_traverse_id_list(Main *bmain, ListBase *lb, BPathVisitor visit_cb, const int flag, void *bpath_user_data)
559 {
560         ID *id;
561         for(id= lb->first; id; id= id->next) {
562                 bpath_traverse_id(bmain, id, visit_cb, flag, bpath_user_data);
563         }
564 }
565
566 void bpath_traverse_main(Main *bmain, BPathVisitor visit_cb, const int flag, void *bpath_user_data)
567 {
568         ListBase *lbarray[MAX_LIBARRAY];
569         int a= set_listbasepointers(bmain, lbarray);
570         while(a--) bpath_traverse_id_list(bmain, lbarray[a], visit_cb, flag, bpath_user_data);
571 }
572
573 /* Rewrites a relative path to be relative to the main file - unless the path is
574    absolute, in which case it is not altered. */
575 int bpath_relocate_visitor(void *pathbase_v, char *path_dst, const char *path_src)
576 {
577         /* be sure there is low chance of the path being too short */
578         char filepath[(FILE_MAXDIR * 2) + FILE_MAXFILE];
579         const char *base_new= ((char **)pathbase_v)[0];
580         const char *base_old= ((char **)pathbase_v)[1];
581
582         if (strncmp(base_old, "//", 2) == 0) {
583                 printf("%s: error, old base path '%s' is not absolute.\n",
584                        __func__, base_old);
585                 return FALSE;
586         }
587
588         /* Make referenced file absolute. This would be a side-effect of
589            BLI_cleanup_file, but we do it explicitely so we know if it changed. */
590         BLI_strncpy(filepath, path_src, FILE_MAX);
591         if (BLI_path_abs(filepath, base_old)) {
592                 /* Path was relative and is now absolute. Remap.
593                  * Important BLI_cleanup_dir runs before the path is made relative
594                  * because it wont work for paths that start with "//../" */
595                 BLI_cleanup_file(base_new, filepath);
596                 BLI_path_rel(filepath, base_new);
597                 BLI_strncpy(path_dst, filepath, FILE_MAX);
598                 return TRUE;
599         }
600         else {
601                 /* Path was not relative to begin with. */
602                 return FALSE;
603         }
604 }