Cleanup: spelling, indentation
[blender.git] / source / blender / windowmanager / intern / wm_files_link.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) 2007 Blender Foundation.
19  * All rights reserved.
20  *
21  * 
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/windowmanager/intern/wm_files_link.c
28  *  \ingroup wm
29  *
30  * Functions for dealing with append/link operators and helpers.
31  */
32
33
34 #include <float.h>
35 #include <string.h>
36 #include <ctype.h>
37 #include <stdio.h>
38 #include <stddef.h>
39 #include <assert.h>
40 #include <errno.h>
41
42 #include "MEM_guardedalloc.h"
43
44 #include "DNA_ID.h"
45 #include "DNA_screen_types.h"
46 #include "DNA_scene_types.h"
47 #include "DNA_windowmanager_types.h"
48
49
50
51 #include "BLI_blenlib.h"
52 #include "BLI_bitmap.h"
53 #include "BLI_linklist.h"
54 #include "BLI_math.h"
55 #include "BLI_memarena.h"
56 #include "BLI_utildefines.h"
57 #include "BLI_ghash.h"
58
59 #include "BLO_readfile.h"
60
61 #include "BKE_context.h"
62 #include "BKE_depsgraph.h"
63 #include "BKE_library.h"
64 #include "BKE_library_remap.h"
65 #include "BKE_global.h"
66 #include "BKE_main.h"
67 #include "BKE_report.h"
68 #include "BKE_scene.h"
69
70 #include "BKE_idcode.h"
71
72
73 #include "IMB_colormanagement.h"
74
75 #include "ED_screen.h"
76
77 #include "GPU_material.h"
78
79 #include "RNA_access.h"
80 #include "RNA_define.h"
81
82
83 #include "WM_api.h"
84 #include "WM_types.h"
85
86 #include "wm_files.h"
87
88 /* **************** link/append *************** */
89
90 static int wm_link_append_poll(bContext *C)
91 {
92         if (WM_operator_winactive(C)) {
93                 /* linking changes active object which is pretty useful in general,
94                  * but which totally confuses edit mode (i.e. it becoming not so obvious
95                  * to leave from edit mode and invalid tools in toolbar might be displayed)
96                  * so disable link/append when in edit mode (sergey) */
97                 if (CTX_data_edit_object(C))
98                         return 0;
99
100                 return 1;
101         }
102
103         return 0;
104 }
105
106 static int wm_link_append_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
107 {
108         if (RNA_struct_property_is_set(op->ptr, "filepath")) {
109                 return WM_operator_call_notest(C, op);
110         }
111         else {
112                 /* XXX TODO solve where to get last linked library from */
113                 if (G.lib[0] != '\0') {
114                         RNA_string_set(op->ptr, "filepath", G.lib);
115                 }
116                 else if (G.relbase_valid) {
117                         char path[FILE_MAX];
118                         BLI_strncpy(path, G.main->name, sizeof(G.main->name));
119                         BLI_parent_dir(path);
120                         RNA_string_set(op->ptr, "filepath", path);
121                 }
122                 WM_event_add_fileselect(C, op);
123                 return OPERATOR_RUNNING_MODAL;
124         }
125 }
126
127 static short wm_link_append_flag(wmOperator *op)
128 {
129         PropertyRNA *prop;
130         short flag = 0;
131
132         if (RNA_boolean_get(op->ptr, "autoselect"))
133                 flag |= FILE_AUTOSELECT;
134         if (RNA_boolean_get(op->ptr, "active_layer"))
135                 flag |= FILE_ACTIVELAY;
136         if ((prop = RNA_struct_find_property(op->ptr, "relative_path")) && RNA_property_boolean_get(op->ptr, prop))
137                 flag |= FILE_RELPATH;
138         if (RNA_boolean_get(op->ptr, "link"))
139                 flag |= FILE_LINK;
140         if (RNA_boolean_get(op->ptr, "instance_groups"))
141                 flag |= FILE_GROUP_INSTANCE;
142
143         return flag;
144 }
145
146 typedef struct WMLinkAppendDataItem {
147         char *name;
148         BLI_bitmap *libraries;  /* All libs (from WMLinkAppendData.libraries) to try to load this ID from. */
149         short idcode;
150
151         ID *new_id;
152         void *customdata;
153 } WMLinkAppendDataItem;
154
155 typedef struct WMLinkAppendData {
156         LinkNodePair libraries;
157         LinkNodePair items;
158         int num_libraries;
159         int num_items;
160         short flag;
161
162         /* Internal 'private' data */
163         MemArena *memarena;
164 } WMLinkAppendData;
165
166 static WMLinkAppendData *wm_link_append_data_new(const int flag)
167 {
168         MemArena *ma = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, __func__);
169         WMLinkAppendData *lapp_data = BLI_memarena_calloc(ma, sizeof(*lapp_data));
170
171         lapp_data->flag = flag;
172         lapp_data->memarena = ma;
173
174         return lapp_data;
175 }
176
177 static void wm_link_append_data_free(WMLinkAppendData *lapp_data)
178 {
179         BLI_memarena_free(lapp_data->memarena);
180 }
181
182 /* WARNING! *Never* call wm_link_append_data_library_add() after having added some items! */
183
184 static void wm_link_append_data_library_add(WMLinkAppendData *lapp_data, const char *libname)
185 {
186         size_t len = strlen(libname) + 1;
187         char *libpath = BLI_memarena_alloc(lapp_data->memarena, len);
188
189         BLI_strncpy(libpath, libname, len);
190         BLI_linklist_append_arena(&lapp_data->libraries, libpath, lapp_data->memarena);
191         lapp_data->num_libraries++;
192 }
193
194 static WMLinkAppendDataItem *wm_link_append_data_item_add(
195         WMLinkAppendData *lapp_data, const char *idname, const short idcode, void *customdata)
196 {
197         WMLinkAppendDataItem *item = BLI_memarena_alloc(lapp_data->memarena, sizeof(*item));
198         size_t len = strlen(idname) + 1;
199
200         item->name = BLI_memarena_alloc(lapp_data->memarena, len);
201         BLI_strncpy(item->name, idname, len);
202         item->idcode = idcode;
203         item->libraries = BLI_BITMAP_NEW_MEMARENA(lapp_data->memarena, lapp_data->num_libraries);
204
205         item->new_id = NULL;
206         item->customdata = customdata;
207
208         BLI_linklist_append_arena(&lapp_data->items, item, lapp_data->memarena);
209         lapp_data->num_items++;
210
211         return item;
212 }
213
214 static void wm_link_do(
215         WMLinkAppendData *lapp_data, ReportList *reports, Main *bmain, Scene *scene, View3D *v3d,
216         const bool use_placeholders, const bool force_indirect)
217 {
218         Main *mainl;
219         BlendHandle *bh;
220         Library *lib;
221
222         const int flag = lapp_data->flag;
223
224         LinkNode *liblink, *itemlink;
225         int lib_idx, item_idx;
226
227         BLI_assert(lapp_data->num_items && lapp_data->num_libraries);
228
229         for (lib_idx = 0, liblink = lapp_data->libraries.list; liblink; lib_idx++, liblink = liblink->next) {
230                 char *libname = liblink->link;
231
232                 bh = BLO_blendhandle_from_file(libname, reports);
233
234                 if (bh == NULL) {
235                         /* Unlikely since we just browsed it, but possible
236                          * Error reports will have been made by BLO_blendhandle_from_file() */
237                         continue;
238                 }
239
240                 /* here appending/linking starts */
241                 mainl = BLO_library_link_begin(bmain, &bh, libname);
242                 lib = mainl->curlib;
243                 BLI_assert(lib);
244                 UNUSED_VARS_NDEBUG(lib);
245
246                 if (mainl->versionfile < 250) {
247                         BKE_reportf(reports, RPT_WARNING,
248                                     "Linking or appending from a very old .blend file format (%d.%d), no animation conversion will "
249                                     "be done! You may want to re-save your lib file with current Blender",
250                                     mainl->versionfile, mainl->subversionfile);
251                 }
252
253                 /* For each lib file, we try to link all items belonging to that lib,
254                  * and tag those successful to not try to load them again with the other libs. */
255                 for (item_idx = 0, itemlink = lapp_data->items.list; itemlink; item_idx++, itemlink = itemlink->next) {
256                         WMLinkAppendDataItem *item = itemlink->link;
257                         ID *new_id;
258
259                         if (!BLI_BITMAP_TEST(item->libraries, lib_idx)) {
260                                 continue;
261                         }
262
263                         new_id = BLO_library_link_named_part_ex(
264                                      mainl, &bh, item->idcode, item->name, flag, scene, v3d, use_placeholders, force_indirect);
265
266                         if (new_id) {
267                                 /* If the link is successful, clear item's libs 'todo' flags.
268                                  * This avoids trying to link same item with other libraries to come. */
269                                 BLI_BITMAP_SET_ALL(item->libraries, false, lapp_data->num_libraries);
270                                 item->new_id = new_id;
271                         }
272                 }
273
274                 BLO_library_link_end(mainl, &bh, flag, scene, v3d);
275                 BLO_blendhandle_close(bh);
276         }
277 }
278
279 static int wm_link_append_exec(bContext *C, wmOperator *op)
280 {
281         Main *bmain = CTX_data_main(C);
282         Scene *scene = CTX_data_scene(C);
283         PropertyRNA *prop;
284         WMLinkAppendData *lapp_data;
285         char path[FILE_MAX_LIBEXTRA], root[FILE_MAXDIR], libname[FILE_MAX], relname[FILE_MAX];
286         char *group, *name;
287         int totfiles = 0;
288         short flag;
289
290         RNA_string_get(op->ptr, "filename", relname);
291         RNA_string_get(op->ptr, "directory", root);
292
293         BLI_join_dirfile(path, sizeof(path), root, relname);
294
295         /* test if we have a valid data */
296         if (!BLO_library_path_explode(path, libname, &group, &name)) {
297                 BKE_reportf(op->reports, RPT_ERROR, "'%s': not a library", path);
298                 return OPERATOR_CANCELLED;
299         }
300         else if (!group) {
301                 BKE_reportf(op->reports, RPT_ERROR, "'%s': nothing indicated", path);
302                 return OPERATOR_CANCELLED;
303         }
304         else if (BLI_path_cmp(bmain->name, libname) == 0) {
305                 BKE_reportf(op->reports, RPT_ERROR, "'%s': cannot use current file as library", path);
306                 return OPERATOR_CANCELLED;
307         }
308
309         /* check if something is indicated for append/link */
310         prop = RNA_struct_find_property(op->ptr, "files");
311         if (prop) {
312                 totfiles = RNA_property_collection_length(op->ptr, prop);
313                 if (totfiles == 0) {
314                         if (!name) {
315                                 BKE_reportf(op->reports, RPT_ERROR, "'%s': nothing indicated", path);
316                                 return OPERATOR_CANCELLED;
317                         }
318                 }
319         }
320         else if (!name) {
321                 BKE_reportf(op->reports, RPT_ERROR, "'%s': nothing indicated", path);
322                 return OPERATOR_CANCELLED;
323         }
324
325         flag = wm_link_append_flag(op);
326
327         /* sanity checks for flag */
328         if (scene && scene->id.lib) {
329                 BKE_reportf(op->reports, RPT_WARNING,
330                             "Scene '%s' is linked, instantiation of objects & groups is disabled", scene->id.name + 2);
331                 flag &= ~FILE_GROUP_INSTANCE;
332                 scene = NULL;
333         }
334
335         /* from here down, no error returns */
336
337         if (scene && RNA_boolean_get(op->ptr, "autoselect")) {
338                 BKE_scene_base_deselect_all(scene);
339         }
340         
341         /* tag everything, all untagged data can be made local
342          * its also generally useful to know what is new
343          *
344          * take extra care BKE_main_id_flag_all(bmain, LIB_TAG_PRE_EXISTING, false) is called after! */
345         BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, true);
346
347         /* We define our working data...
348          * Note that here, each item 'uses' one library, and only one. */
349         lapp_data = wm_link_append_data_new(flag);
350         if (totfiles != 0) {
351                 GHash *libraries = BLI_ghash_new(BLI_ghashutil_strhash_p, BLI_ghashutil_strcmp, __func__);
352                 int lib_idx = 0;
353
354                 RNA_BEGIN (op->ptr, itemptr, "files")
355                 {
356                         RNA_string_get(&itemptr, "name", relname);
357
358                         BLI_join_dirfile(path, sizeof(path), root, relname);
359
360                         if (BLO_library_path_explode(path, libname, &group, &name)) {
361                                 if (!group || !name) {
362                                         continue;
363                                 }
364
365                                 if (!BLI_ghash_haskey(libraries, libname)) {
366                                         BLI_ghash_insert(libraries, BLI_strdup(libname), SET_INT_IN_POINTER(lib_idx));
367                                         lib_idx++;
368                                         wm_link_append_data_library_add(lapp_data, libname);
369                                 }
370                         }
371                 }
372                 RNA_END;
373
374                 RNA_BEGIN (op->ptr, itemptr, "files")
375                 {
376                         RNA_string_get(&itemptr, "name", relname);
377
378                         BLI_join_dirfile(path, sizeof(path), root, relname);
379
380                         if (BLO_library_path_explode(path, libname, &group, &name)) {
381                                 WMLinkAppendDataItem *item;
382                                 if (!group || !name) {
383                                         printf("skipping %s\n", path);
384                                         continue;
385                                 }
386
387                                 lib_idx = GET_INT_FROM_POINTER(BLI_ghash_lookup(libraries, libname));
388
389                                 item = wm_link_append_data_item_add(lapp_data, name, BKE_idcode_from_name(group), NULL);
390                                 BLI_BITMAP_ENABLE(item->libraries, lib_idx);
391                         }
392                 }
393                 RNA_END;
394
395                 BLI_ghash_free(libraries, MEM_freeN, NULL);
396         }
397         else {
398                 WMLinkAppendDataItem *item;
399
400                 wm_link_append_data_library_add(lapp_data, libname);
401                 item = wm_link_append_data_item_add(lapp_data, name, BKE_idcode_from_name(group), NULL);
402                 BLI_BITMAP_ENABLE(item->libraries, 0);
403         }
404
405         /* XXX We'd need re-entrant locking on Main for this to work... */
406         /* BKE_main_lock(bmain); */
407
408         wm_link_do(lapp_data, op->reports, bmain, scene, CTX_wm_view3d(C), false, false);
409
410         /* BKE_main_unlock(bmain); */
411
412         /* mark all library linked objects to be updated */
413         BKE_main_lib_objects_recalc_all(bmain);
414         IMB_colormanagement_check_file_config(bmain);
415
416         /* append, rather than linking */
417         if ((flag & FILE_LINK) == 0) {
418                 const bool set_fake = RNA_boolean_get(op->ptr, "set_fake");
419                 const bool use_recursive = RNA_boolean_get(op->ptr, "use_recursive");
420
421                 if (use_recursive) {
422                         BKE_library_make_local(bmain, NULL, true, set_fake);
423                 }
424                 else {
425                         LinkNode *itemlink;
426                         GSet *done_libraries = BLI_gset_new_ex(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp,
427                                                                __func__, lapp_data->num_libraries);
428
429                         for (itemlink = lapp_data->items.list; itemlink; itemlink = itemlink->next) {
430                                 ID *new_id = ((WMLinkAppendDataItem *)(itemlink->link))->new_id;
431
432                                 if (new_id && !BLI_gset_haskey(done_libraries, new_id->lib)) {
433                                         BKE_library_make_local(bmain, new_id->lib, true, set_fake);
434                                         BLI_gset_insert(done_libraries, new_id->lib);
435                                 }
436                         }
437
438                         BLI_gset_free(done_libraries, NULL);
439                 }
440         }
441
442         wm_link_append_data_free(lapp_data);
443
444         /* important we unset, otherwise these object wont
445          * link into other scenes from this blend file */
446         BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, false);
447
448         /* recreate dependency graph to include new objects */
449         DAG_scene_relations_rebuild(bmain, scene);
450         
451         /* free gpu materials, some materials depend on existing objects, such as lamps so freeing correctly refreshes */
452         GPU_materials_free();
453
454         /* XXX TODO: align G.lib with other directory storage (like last opened image etc...) */
455         BLI_strncpy(G.lib, root, FILE_MAX);
456
457         WM_event_add_notifier(C, NC_WINDOW, NULL);
458
459         return OPERATOR_FINISHED;
460 }
461
462 static void wm_link_append_properties_common(wmOperatorType *ot, bool is_link)
463 {
464         PropertyRNA *prop;
465
466         /* better not save _any_ settings for this operator */
467         /* properties */
468         prop = RNA_def_boolean(ot->srna, "link", is_link,
469                                "Link", "Link the objects or datablocks rather than appending");
470         RNA_def_property_flag(prop, PROP_SKIP_SAVE | PROP_HIDDEN);
471         prop = RNA_def_boolean(ot->srna, "autoselect", true,
472                                "Select", "Select new objects");
473         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
474         prop = RNA_def_boolean(ot->srna, "active_layer", true,
475                                "Active Layer", "Put new objects on the active layer");
476         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
477         prop = RNA_def_boolean(ot->srna, "instance_groups", is_link,
478                                "Instance Groups", "Create Dupli-Group instances for each group");
479         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
480 }
481
482 void WM_OT_link(wmOperatorType *ot)
483 {
484         ot->name = "Link from Library";
485         ot->idname = "WM_OT_link";
486         ot->description = "Link from a Library .blend file";
487         
488         ot->invoke = wm_link_append_invoke;
489         ot->exec = wm_link_append_exec;
490         ot->poll = wm_link_append_poll;
491         
492         ot->flag |= OPTYPE_UNDO;
493
494         WM_operator_properties_filesel(
495                 ot, FILE_TYPE_FOLDER | FILE_TYPE_BLENDER | FILE_TYPE_BLENDERLIB, FILE_LOADLIB, FILE_OPENFILE,
496                 WM_FILESEL_FILEPATH | WM_FILESEL_DIRECTORY | WM_FILESEL_FILENAME | WM_FILESEL_RELPATH | WM_FILESEL_FILES,
497                 FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
498         
499         wm_link_append_properties_common(ot, true);
500 }
501
502 void WM_OT_append(wmOperatorType *ot)
503 {
504         ot->name = "Append from Library";
505         ot->idname = "WM_OT_append";
506         ot->description = "Append from a Library .blend file";
507
508         ot->invoke = wm_link_append_invoke;
509         ot->exec = wm_link_append_exec;
510         ot->poll = wm_link_append_poll;
511
512         ot->flag |= OPTYPE_UNDO;
513
514         WM_operator_properties_filesel(
515                 ot, FILE_TYPE_FOLDER | FILE_TYPE_BLENDER | FILE_TYPE_BLENDERLIB, FILE_LOADLIB, FILE_OPENFILE,
516                 WM_FILESEL_FILEPATH | WM_FILESEL_DIRECTORY | WM_FILESEL_FILENAME | WM_FILESEL_FILES,
517                 FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
518
519         wm_link_append_properties_common(ot, false);
520         RNA_def_boolean(ot->srna, "set_fake", false, "Fake User",
521                         "Set Fake User for appended items (except Objects and Groups)");
522         RNA_def_boolean(ot->srna, "use_recursive", true, "Localize All",
523                         "Localize all appended data, including those indirectly linked from other libraries");
524 }
525
526 /** \name Reload/relocate libraries.
527  *
528  * \{ */
529
530 static int wm_lib_relocate_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
531 {
532         Library *lib;
533         char lib_name[MAX_NAME];
534
535         RNA_string_get(op->ptr, "library", lib_name);
536         lib = (Library *)BKE_libblock_find_name_ex(CTX_data_main(C), ID_LI, lib_name);
537
538         if (lib) {
539                 if (lib->parent) {
540                         BKE_reportf(op->reports, RPT_ERROR_INVALID_INPUT,
541                                     "Cannot relocate indirectly linked library '%s'", lib->filepath);
542                         return OPERATOR_CANCELLED;
543                 }
544                 RNA_string_set(op->ptr, "filepath", lib->filepath);
545
546                 WM_event_add_fileselect(C, op);
547
548                 return OPERATOR_RUNNING_MODAL;
549         }
550
551         return OPERATOR_CANCELLED;
552 }
553
554 /* Note that IDs listed in lapp_data items *must* have been removed from bmain by caller. */
555 static void lib_relocate_do(Main *bmain, WMLinkAppendData *lapp_data, ReportList *reports, const bool do_reload)
556 {
557         ListBase *lbarray[MAX_LIBARRAY];
558         int lba_idx;
559
560         LinkNode *itemlink;
561         int item_idx;
562
563         BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, true);
564
565         /* We do not want any instanciation here! */
566         wm_link_do(lapp_data, reports, bmain, NULL, NULL, do_reload, do_reload);
567
568         BKE_main_lock(bmain);
569
570         /* We add back old id to bmain.
571          * We need to do this in a first, separated loop, otherwise some of those may not be handled by
572          * ID remapping, which means they would still reference old data to be deleted... */
573         for (item_idx = 0, itemlink = lapp_data->items.list; itemlink; item_idx++, itemlink = itemlink->next) {
574                 WMLinkAppendDataItem *item = itemlink->link;
575                 ID *old_id = item->customdata;
576
577                 BLI_assert(old_id);
578                 BLI_addtail(which_libbase(bmain, GS(old_id->name)), old_id);
579         }
580
581         /* Note that in reload case, we also want to replace indirect usages. */
582         const short remap_flags = ID_REMAP_SKIP_NEVER_NULL_USAGE | (do_reload ? 0 : ID_REMAP_SKIP_INDIRECT_USAGE);
583         for (item_idx = 0, itemlink = lapp_data->items.list; itemlink; item_idx++, itemlink = itemlink->next) {
584                 WMLinkAppendDataItem *item = itemlink->link;
585                 ID *old_id = item->customdata;
586                 ID *new_id = item->new_id;
587
588                 BLI_assert(old_id);
589                 if (do_reload) {
590                         /* Since we asked for placeholders in case of missing IDs, we expect to always get a valid one. */
591                         BLI_assert(new_id);
592                 }
593                 if (new_id) {
594 #ifdef PRINT_DEBUG
595                         printf("before remap, old_id users: %d, new_id users: %d\n", old_id->us, new_id->us);
596 #endif
597                         BKE_libblock_remap_locked(bmain, old_id, new_id, remap_flags);
598
599                         if (old_id->flag & LIB_FAKEUSER) {
600                                 id_fake_user_clear(old_id);
601                                 id_fake_user_set(new_id);
602                         }
603
604 #ifdef PRINT_DEBUG
605                         printf("after remap, old_id users: %d, new_id users: %d\n", old_id->us, new_id->us);
606 #endif
607
608                         /* In some cases, new_id might become direct link, remove parent of library in this case. */
609                         if (new_id->lib->parent && (new_id->tag & LIB_TAG_INDIRECT) == 0) {
610                                 if (do_reload) {
611                                         BLI_assert(0);  /* Should not happen in 'pure' reload case... */
612                                 }
613                                 new_id->lib->parent = NULL;
614                         }
615                 }
616
617                 if (old_id->us > 0 && new_id && old_id->lib == new_id->lib) {
618                         /* Note that this *should* not happen - but better be safe than sorry in this area, at least until we are
619                          * 100% sure this cannot ever happen.
620                          * Also, we can safely assume names were unique so far, so just replacing '.' by '~' should work,
621                          * but this does not totally rules out the possibility of name collision. */
622                         size_t len = strlen(old_id->name);
623                         size_t dot_pos;
624                         bool has_num = false;
625
626                         for (dot_pos = len; dot_pos--;) {
627                                 char c = old_id->name[dot_pos];
628                                 if (c == '.') {
629                                         break;
630                                 }
631                                 else if (c < '0' || c > '9') {
632                                         has_num = false;
633                                         break;
634                                 }
635                                 has_num = true;
636                         }
637
638                         if (has_num) {
639                                 old_id->name[dot_pos] = '~';
640                         }
641                         else {
642                                 len = MIN2(len, MAX_ID_NAME - 7);
643                                 BLI_strncpy(&old_id->name[len], "~000", 7);
644                         }
645
646                         id_sort_by_name(which_libbase(bmain, GS(old_id->name)), old_id);
647
648                         BKE_reportf(reports, RPT_WARNING,
649                                     "Lib Reload: Replacing all references to old datablock '%s' by reloaded one failed, "
650                                     "old one (%d remaining users) had to be kept and was renamed to '%s'",
651                                     new_id->name, old_id->us, old_id->name);
652                 }
653         }
654
655         BKE_main_unlock(bmain);
656
657         for (item_idx = 0, itemlink = lapp_data->items.list; itemlink; item_idx++, itemlink = itemlink->next) {
658                 WMLinkAppendDataItem *item = itemlink->link;
659                 ID *old_id = item->customdata;
660
661                 if (old_id->us == 0) {
662                         BKE_libblock_free(bmain, old_id);
663                 }
664         }
665
666         /* Some datablocks can get reloaded/replaced 'silently' because they are not linkable (shape keys e.g.),
667          * so we need another loop here to clear old ones if possible. */
668         lba_idx = set_listbasepointers(bmain, lbarray);
669         while (lba_idx--) {
670                 ID *id, *id_next;
671                 for (id  = lbarray[lba_idx]->first; id; id = id_next) {
672                         id_next = id->next;
673                         /* XXX That check may be a bit to generic/permissive? */
674                         if (id->lib && (id->flag & LIB_TAG_PRE_EXISTING) && id->us == 0) {
675                                 BKE_libblock_free(bmain, id);
676                         }
677                 }
678         }
679
680         /* Get rid of no more used libraries... */
681         BKE_main_id_tag_idcode(bmain, ID_LI, LIB_TAG_DOIT, true);
682         lba_idx = set_listbasepointers(bmain, lbarray);
683         while (lba_idx--) {
684                 ID *id;
685                 for (id = lbarray[lba_idx]->first; id; id = id->next) {
686                         if (id->lib) {
687                                 id->lib->id.tag &= ~LIB_TAG_DOIT;
688                         }
689                 }
690         }
691         Library *lib, *lib_next;
692         for (lib = which_libbase(bmain, ID_LI)->first; lib; lib = lib_next) {
693                 lib_next = lib->id.next;
694                 if (lib->id.tag & LIB_TAG_DOIT) {
695                         id_us_clear_real(&lib->id);
696                         if (lib->id.us == 0) {
697                                 BKE_libblock_free(bmain, (ID *)lib);
698                         }
699                 }
700         }
701 }
702
703 static int wm_lib_relocate_exec_do(bContext *C, wmOperator *op, bool do_reload)
704 {
705         Library *lib;
706         char lib_name[MAX_NAME];
707
708         RNA_string_get(op->ptr, "library", lib_name);
709         lib = (Library *)BKE_libblock_find_name_ex(CTX_data_main(C), ID_LI, lib_name);
710
711         if (lib) {
712                 Main *bmain = CTX_data_main(C);
713                 Scene *scene = CTX_data_scene(C);
714                 PropertyRNA *prop;
715                 WMLinkAppendData *lapp_data;
716
717                 ListBase *lbarray[MAX_LIBARRAY];
718                 int lba_idx;
719
720                 char path[FILE_MAX], root[FILE_MAXDIR], libname[FILE_MAX], relname[FILE_MAX];
721                 short flag = 0;
722
723                 if (RNA_boolean_get(op->ptr, "relative_path")) {
724                         flag |= FILE_RELPATH;
725                 }
726
727                 if (lib->parent && !do_reload) {
728                         BKE_reportf(op->reports, RPT_ERROR_INVALID_INPUT,
729                                     "Cannot relocate indirectly linked library '%s'", lib->filepath);
730                         return OPERATOR_CANCELLED;
731                 }
732
733                 RNA_string_get(op->ptr, "directory", root);
734                 RNA_string_get(op->ptr, "filename", libname);
735
736                 if (!BLO_has_bfile_extension(libname)) {
737                         BKE_report(op->reports, RPT_ERROR, "Not a library");
738                         return OPERATOR_CANCELLED;
739                 }
740
741                 BLI_join_dirfile(path, sizeof(path), root, libname);
742
743                 if (!BLI_exists(path)) {
744                         BKE_reportf(op->reports, RPT_ERROR_INVALID_INPUT,
745                                     "Trying to reload or relocate library '%s' to invalid path '%s'", lib->id.name, path);
746                         return OPERATOR_CANCELLED;
747                 }
748
749                 if (BLI_path_cmp(lib->filepath, path) == 0) {
750 #ifdef PRINT_DEBUG
751                         printf("We are supposed to reload '%s' lib (%d)...\n", lib->filepath, lib->id.us);
752 #endif
753
754                         do_reload = true;
755
756                         lapp_data = wm_link_append_data_new(flag);
757                         wm_link_append_data_library_add(lapp_data, path);
758                 }
759                 else {
760                         int totfiles = 0;
761
762 #ifdef PRINT_DEBUG
763                         printf("We are supposed to relocate '%s' lib to new '%s' one...\n", lib->filepath, libname);
764 #endif
765
766                         /* Check if something is indicated for relocate. */
767                         prop = RNA_struct_find_property(op->ptr, "files");
768                         if (prop) {
769                                 totfiles = RNA_property_collection_length(op->ptr, prop);
770                                 if (totfiles == 0) {
771                                         if (!libname[0]) {
772                                                 BKE_report(op->reports, RPT_ERROR, "Nothing indicated");
773                                                 return OPERATOR_CANCELLED;
774                                         }
775                                 }
776                         }
777
778                         lapp_data = wm_link_append_data_new(flag);
779
780                         if (totfiles) {
781                                 RNA_BEGIN (op->ptr, itemptr, "files")
782                                 {
783                                         RNA_string_get(&itemptr, "name", relname);
784
785                                         BLI_join_dirfile(path, sizeof(path), root, relname);
786
787                                         if (BLI_path_cmp(path, lib->filepath) == 0 || !BLO_has_bfile_extension(relname)) {
788                                                 continue;
789                                         }
790
791 #ifdef PRINT_DEBUG
792                                         printf("\t candidate new lib to reload datablocks from: %s\n", path);
793 #endif
794                                         wm_link_append_data_library_add(lapp_data, path);
795                                 }
796                                 RNA_END;
797                         }
798                         else {
799 #ifdef PRINT_DEBUG
800                                 printf("\t candidate new lib to reload datablocks from: %s\n", path);
801 #endif
802                                 wm_link_append_data_library_add(lapp_data, path);
803                         }
804                 }
805
806                 lba_idx = set_listbasepointers(bmain, lbarray);
807                 while (lba_idx--) {
808                         ID *id = lbarray[lba_idx]->first;
809                         const short idcode = id ? GS(id->name) : 0;
810
811                         if (!id || !BKE_idcode_is_linkable(idcode)) {
812                                 /* No need to reload non-linkable datatypes, those will get relinked with their 'users ID'. */
813                                 continue;
814                         }
815
816                         for (; id; id = id->next) {
817                                 if (id->lib == lib) {
818                                         WMLinkAppendDataItem *item;
819
820                                         /* We remove it from current Main, and add it to items to link... */
821                                         /* Note that non-linkable IDs (like e.g. shapekeys) are also explicitely linked here... */
822                                         BLI_remlink(lbarray[lba_idx], id);
823                                         item = wm_link_append_data_item_add(lapp_data, id->name + 2, idcode, id);
824                                         BLI_BITMAP_SET_ALL(item->libraries, true, lapp_data->num_libraries);
825
826 #ifdef PRINT_DEBUG
827                                         printf("\tdatablock to seek for: %s\n", id->name);
828 #endif
829                                 }
830                         }
831                 }
832
833                 lib_relocate_do(bmain, lapp_data, op->reports, do_reload);
834
835                 wm_link_append_data_free(lapp_data);
836
837                 BKE_main_lib_objects_recalc_all(bmain);
838                 IMB_colormanagement_check_file_config(bmain);
839
840                 /* important we unset, otherwise these object wont
841                  * link into other scenes from this blend file */
842                 BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, false);
843
844                 /* recreate dependency graph to include new objects */
845                 DAG_scene_relations_rebuild(bmain, scene);
846
847                 /* free gpu materials, some materials depend on existing objects, such as lamps so freeing correctly refreshes */
848                 GPU_materials_free();
849
850                 /* XXX TODO: align G.lib with other directory storage (like last opened image etc...) */
851                 BLI_strncpy(G.lib, root, FILE_MAX);
852
853                 WM_event_add_notifier(C, NC_WINDOW, NULL);
854
855                 return OPERATOR_FINISHED;
856         }
857
858         return OPERATOR_CANCELLED;
859 }
860
861 static int wm_lib_relocate_exec(bContext *C, wmOperator *op)
862 {
863         return wm_lib_relocate_exec_do(C, op, false);
864 }
865
866 void WM_OT_lib_relocate(wmOperatorType *ot)
867 {
868         PropertyRNA *prop;
869
870         ot->name = "Relocate Library";
871         ot->idname = "WM_OT_lib_relocate";
872         ot->description = "Relocate the given library to one or several others";
873
874         ot->invoke = wm_lib_relocate_invoke;
875         ot->exec = wm_lib_relocate_exec;
876
877         ot->flag |= OPTYPE_UNDO;
878
879         prop = RNA_def_string(ot->srna, "library", NULL, MAX_NAME, "Library", "Library to relocate");
880         RNA_def_property_flag(prop, PROP_HIDDEN);
881
882         WM_operator_properties_filesel(
883                     ot, FILE_TYPE_FOLDER | FILE_TYPE_BLENDER, FILE_BLENDER, FILE_OPENFILE,
884                     WM_FILESEL_FILEPATH | WM_FILESEL_DIRECTORY | WM_FILESEL_FILENAME | WM_FILESEL_FILES | WM_FILESEL_RELPATH,
885                     FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
886 }
887
888 static int wm_lib_reload_exec(bContext *C, wmOperator *op)
889 {
890         return wm_lib_relocate_exec_do(C, op, true);
891 }
892
893 void WM_OT_lib_reload(wmOperatorType *ot)
894 {
895         PropertyRNA *prop;
896
897         ot->name = "Reload Library";
898         ot->idname = "WM_OT_lib_reload";
899         ot->description = "Reload the given library";
900
901         ot->exec = wm_lib_reload_exec;
902
903         ot->flag |= OPTYPE_UNDO;
904
905         prop = RNA_def_string(ot->srna, "library", NULL, MAX_NAME, "Library", "Library to reload");
906         RNA_def_property_flag(prop, PROP_HIDDEN);
907
908         WM_operator_properties_filesel(
909                     ot, FILE_TYPE_FOLDER | FILE_TYPE_BLENDER, FILE_BLENDER, FILE_OPENFILE,
910                     WM_FILESEL_FILEPATH | WM_FILESEL_DIRECTORY | WM_FILESEL_FILENAME | WM_FILESEL_RELPATH,
911                     FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
912 }
913
914 /** \} */