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