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