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