Tighten checks around unlinkable datablocks becoming LIB_EXTERN.
[blender.git] / source / blender / blenkernel / intern / library.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/library.c
29  *  \ingroup bke
30  *
31  * Contains management of ID's and libraries
32  * allocate and free of all library data
33  */
34
35 #include <stdio.h>
36 #include <ctype.h>
37 #include <string.h>
38 #include <stdlib.h>
39 #include <stddef.h>
40 #include <assert.h>
41
42 #include "MEM_guardedalloc.h"
43
44 /* all types are needed here, in order to do memory operations */
45 #include "DNA_anim_types.h"
46 #include "DNA_armature_types.h"
47 #include "DNA_brush_types.h"
48 #include "DNA_camera_types.h"
49 #include "DNA_group_types.h"
50 #include "DNA_gpencil_types.h"
51 #include "DNA_ipo_types.h"
52 #include "DNA_key_types.h"
53 #include "DNA_lamp_types.h"
54 #include "DNA_lattice_types.h"
55 #include "DNA_linestyle_types.h"
56 #include "DNA_material_types.h"
57 #include "DNA_mesh_types.h"
58 #include "DNA_meta_types.h"
59 #include "DNA_movieclip_types.h"
60 #include "DNA_mask_types.h"
61 #include "DNA_node_types.h"
62 #include "DNA_object_types.h"
63 #include "DNA_scene_types.h"
64 #include "DNA_screen_types.h"
65 #include "DNA_speaker_types.h"
66 #include "DNA_sound_types.h"
67 #include "DNA_text_types.h"
68 #include "DNA_vfont_types.h"
69 #include "DNA_windowmanager_types.h"
70 #include "DNA_world_types.h"
71
72 #include "BLI_blenlib.h"
73 #include "BLI_utildefines.h"
74
75 #include "BLI_threads.h"
76 #include "BLT_translation.h"
77
78 #include "BKE_action.h"
79 #include "BKE_animsys.h"
80 #include "BKE_armature.h"
81 #include "BKE_bpath.h"
82 #include "BKE_brush.h"
83 #include "BKE_camera.h"
84 #include "BKE_context.h"
85 #include "BKE_curve.h"
86 #include "BKE_depsgraph.h"
87 #include "BKE_fcurve.h"
88 #include "BKE_font.h"
89 #include "BKE_global.h"
90 #include "BKE_group.h"
91 #include "BKE_gpencil.h"
92 #include "BKE_idcode.h"
93 #include "BKE_idprop.h"
94 #include "BKE_image.h"
95 #include "BKE_ipo.h"
96 #include "BKE_key.h"
97 #include "BKE_lamp.h"
98 #include "BKE_lattice.h"
99 #include "BKE_library.h"
100 #include "BKE_library_query.h"
101 #include "BKE_linestyle.h"
102 #include "BKE_mesh.h"
103 #include "BKE_material.h"
104 #include "BKE_main.h"
105 #include "BKE_mball.h"
106 #include "BKE_movieclip.h"
107 #include "BKE_mask.h"
108 #include "BKE_node.h"
109 #include "BKE_object.h"
110 #include "BKE_paint.h"
111 #include "BKE_particle.h"
112 #include "BKE_packedFile.h"
113 #include "BKE_speaker.h"
114 #include "BKE_sound.h"
115 #include "BKE_screen.h"
116 #include "BKE_scene.h"
117 #include "BKE_text.h"
118 #include "BKE_texture.h"
119 #include "BKE_world.h"
120
121 #include "DEG_depsgraph.h"
122
123 #include "RNA_access.h"
124
125 #include "IMB_imbuf.h"
126 #include "IMB_imbuf_types.h"
127
128 #ifdef WITH_PYTHON
129 #include "BPY_extern.h"
130 #endif
131
132 /* GS reads the memory pointed at in a specific ordering. 
133  * only use this definition, makes little and big endian systems
134  * work fine, in conjunction with MAKE_ID */
135
136 /* ************* general ************************ */
137
138
139 /* this has to be called from each make_local_* func, we could call
140  * from id_make_local() but then the make local functions would not be self
141  * contained.
142  * also note that the id _must_ have a library - campbell */
143 void BKE_id_lib_local_paths(Main *bmain, Library *lib, ID *id)
144 {
145         const char *bpath_user_data[2] = {bmain->name, lib->filepath};
146
147         BKE_bpath_traverse_id(bmain, id,
148                               BKE_bpath_relocate_visitor,
149                               BKE_BPATH_TRAVERSE_SKIP_MULTIFILE,
150                               (void *)bpath_user_data);
151 }
152
153 void id_lib_extern(ID *id)
154 {
155         if (id) {
156                 BLI_assert(BKE_idcode_is_linkable(GS(id->name)));
157                 if (id->flag & LIB_INDIRECT) {
158                         id->flag -= LIB_INDIRECT;
159                         id->flag |= LIB_EXTERN;
160                 }
161         }
162 }
163
164 /* ensure we have a real user */
165 void id_us_ensure_real(ID *id)
166 {
167         if (id) {
168                 const int limit = ID_FAKE_USERS(id);
169                 if (id->us <= limit) {
170                         if (id->us < limit) {
171                                 printf("ID user count error: %s (from '%s')\n", id->name, id->lib ? id->lib->filepath : "[Main]");
172                                 BLI_assert(0);
173                         }
174                         id->us = limit + 1;
175                 }
176         }
177 }
178
179 void id_us_plus(ID *id)
180 {
181         if (id) {
182                 BLI_assert(id->us >= 0);
183                 id->us++;
184                 id_lib_extern(id);
185         }
186 }
187
188 /* decrements the user count for *id. */
189 void id_us_min(ID *id)
190 {
191         if (id) {
192                 const int limit = ID_FAKE_USERS(id);
193                 if (id->us <= limit) {
194                         printf("ID user decrement error: %s (from '%s')\n", id->name, id->lib ? id->lib->filepath : "[Main]");
195                         BLI_assert(0);
196                         id->us = limit;
197                 }
198                 else {
199                         id->us--;
200                 }
201         }
202 }
203
204 void id_fake_user_set(ID *id)
205 {
206         if (id && !(id->flag & LIB_FAKEUSER)) {
207                 id->flag |= LIB_FAKEUSER;
208                 id_us_plus(id);
209         }
210 }
211
212 void id_fake_user_clear(ID *id)
213 {
214         if (id && (id->flag & LIB_FAKEUSER)) {
215                 id->flag &= ~LIB_FAKEUSER;
216                 id_us_min(id);
217         }
218 }
219
220 /* calls the appropriate make_local method for the block, unless test. Returns true
221  * if the block can be made local. */
222 bool id_make_local(ID *id, bool test)
223 {
224         if (id->flag & LIB_INDIRECT)
225                 return false;
226
227         switch (GS(id->name)) {
228                 case ID_SCE:
229                         return false; /* not implemented */
230                 case ID_LI:
231                         return false; /* can't be linked */
232                 case ID_OB:
233                         if (!test) BKE_object_make_local((Object *)id);
234                         return true;
235                 case ID_ME:
236                         if (!test) {
237                                 BKE_mesh_make_local((Mesh *)id);
238                                 BKE_key_make_local(((Mesh *)id)->key);
239                         }
240                         return true;
241                 case ID_CU:
242                         if (!test) {
243                                 BKE_curve_make_local((Curve *)id);
244                                 BKE_key_make_local(((Curve *)id)->key);
245                         }
246                         return true;
247                 case ID_MB:
248                         if (!test) BKE_mball_make_local((MetaBall *)id);
249                         return true;
250                 case ID_MA:
251                         if (!test) BKE_material_make_local((Material *)id);
252                         return true;
253                 case ID_TE:
254                         if (!test) BKE_texture_make_local((Tex *)id);
255                         return true;
256                 case ID_IM:
257                         if (!test) BKE_image_make_local((Image *)id);
258                         return true;
259                 case ID_LT:
260                         if (!test) {
261                                 BKE_lattice_make_local((Lattice *)id);
262                                 BKE_key_make_local(((Lattice *)id)->key);
263                         }
264                         return true;
265                 case ID_LA:
266                         if (!test) BKE_lamp_make_local((Lamp *)id);
267                         return true;
268                 case ID_CA:
269                         if (!test) BKE_camera_make_local((Camera *)id);
270                         return true;
271                 case ID_SPK:
272                         if (!test) BKE_speaker_make_local((Speaker *)id);
273                         return true;
274                 case ID_IP:
275                         return false; /* deprecated */
276                 case ID_KE:
277                         if (!test) BKE_key_make_local((Key *)id);
278                         return true;
279                 case ID_WO:
280                         if (!test) BKE_world_make_local((World *)id);
281                         return true;
282                 case ID_SCR:
283                         return false; /* can't be linked */
284                 case ID_VF:
285                         return false; /* not implemented */
286                 case ID_TXT:
287                         return false; /* not implemented */
288                 case ID_SO:
289                         return false; /* not implemented */
290                 case ID_GR:
291                         return false; /* not implemented */
292                 case ID_AR:
293                         if (!test) BKE_armature_make_local((bArmature *)id);
294                         return true;
295                 case ID_AC:
296                         if (!test) BKE_action_make_local((bAction *)id);
297                         return true;
298                 case ID_NT:
299                         if (!test) ntreeMakeLocal((bNodeTree *)id);
300                         return true;
301                 case ID_BR:
302                         if (!test) BKE_brush_make_local((Brush *)id);
303                         return true;
304                 case ID_PA:
305                         if (!test) BKE_particlesettings_make_local((ParticleSettings *)id);
306                         return true;
307                 case ID_WM:
308                         return false; /* can't be linked */
309                 case ID_GD:
310                         return false; /* not implemented */
311                 case ID_LS:
312                         return false; /* not implemented */
313         }
314
315         return false;
316 }
317
318 /**
319  * Invokes the appropriate copy method for the block and returns the result in
320  * newid, unless test. Returns true if the block can be copied.
321  */
322 bool id_copy(ID *id, ID **newid, bool test)
323 {
324         if (!test) *newid = NULL;
325
326         /* conventions:
327          * - make shallow copy, only this ID block
328          * - id.us of the new ID is set to 1 */
329         switch (GS(id->name)) {
330                 case ID_SCE:
331                         return false;  /* can't be copied from here */
332                 case ID_LI:
333                         return false;  /* can't be copied from here */
334                 case ID_OB:
335                         if (!test) *newid = (ID *)BKE_object_copy((Object *)id);
336                         return true;
337                 case ID_ME:
338                         if (!test) *newid = (ID *)BKE_mesh_copy((Mesh *)id);
339                         return true;
340                 case ID_CU:
341                         if (!test) *newid = (ID *)BKE_curve_copy((Curve *)id);
342                         return true;
343                 case ID_MB:
344                         if (!test) *newid = (ID *)BKE_mball_copy((MetaBall *)id);
345                         return true;
346                 case ID_MA:
347                         if (!test) *newid = (ID *)BKE_material_copy((Material *)id);
348                         return true;
349                 case ID_TE:
350                         if (!test) *newid = (ID *)BKE_texture_copy((Tex *)id);
351                         return true;
352                 case ID_IM:
353                         if (!test) *newid = (ID *)BKE_image_copy(G.main, (Image *)id);
354                         return true;
355                 case ID_LT:
356                         if (!test) *newid = (ID *)BKE_lattice_copy((Lattice *)id);
357                         return true;
358                 case ID_LA:
359                         if (!test) *newid = (ID *)BKE_lamp_copy((Lamp *)id);
360                         return true;
361                 case ID_SPK:
362                         if (!test) *newid = (ID *)BKE_speaker_copy((Speaker *)id);
363                         return true;
364                 case ID_CA:
365                         if (!test) *newid = (ID *)BKE_camera_copy((Camera *)id);
366                         return true;
367                 case ID_IP:
368                         return false;  /* deprecated */
369                 case ID_KE:
370                         if (!test) *newid = (ID *)BKE_key_copy((Key *)id);
371                         return true;
372                 case ID_WO:
373                         if (!test) *newid = (ID *)BKE_world_copy((World *)id);
374                         return true;
375                 case ID_SCR:
376                         return false;  /* can't be copied from here */
377                 case ID_VF:
378                         return false;  /* not implemented */
379                 case ID_TXT:
380                         if (!test) *newid = (ID *)BKE_text_copy(G.main, (Text *)id);
381                         return true;
382                 case ID_SO:
383                         return false;  /* not implemented */
384                 case ID_GR:
385                         if (!test) *newid = (ID *)BKE_group_copy((Group *)id);
386                         return true;
387                 case ID_AR:
388                         if (!test) *newid = (ID *)BKE_armature_copy((bArmature *)id);
389                         return true;
390                 case ID_AC:
391                         if (!test) *newid = (ID *)BKE_action_copy((bAction *)id);
392                         return true;
393                 case ID_NT:
394                         if (!test) *newid = (ID *)ntreeCopyTree((bNodeTree *)id);
395                         return true;
396                 case ID_BR:
397                         if (!test) *newid = (ID *)BKE_brush_copy((Brush *)id);
398                         return true;
399                 case ID_PA:
400                         if (!test) *newid = (ID *)BKE_particlesettings_copy((ParticleSettings *)id);
401                         return true;
402                 case ID_WM:
403                         return false;  /* can't be copied from here */
404                 case ID_GD:
405                         if (!test) *newid = (ID *)gpencil_data_duplicate((bGPdata *)id, false);
406                         return true;
407                 case ID_MSK:
408                         if (!test) *newid = (ID *)BKE_mask_copy((Mask *)id);
409                         return true;
410                 case ID_LS:
411                         if (!test) *newid = (ID *)BKE_linestyle_copy(G.main, (FreestyleLineStyle *)id);
412                         return true;
413         }
414         
415         return false;
416 }
417
418 bool id_unlink(ID *id, int test)
419 {
420         Main *mainlib = G.main;
421         short type = GS(id->name);
422
423         switch (type) {
424                 case ID_TXT:
425                         if (test) return true;
426                         BKE_text_unlink(mainlib, (Text *)id);
427                         break;
428                 case ID_GR:
429                         if (test) return true;
430                         BKE_group_unlink(mainlib, (Group *)id);
431                         break;
432                 case ID_OB:
433                         if (test) return true;
434                         BKE_object_unlink(mainlib, (Object *)id);
435                         break;
436         }
437
438         if (id->us == 0) {
439                 if (test) return true;
440
441                 BKE_libblock_free(mainlib, id);
442
443                 return true;
444         }
445
446         return false;
447 }
448
449 bool id_single_user(bContext *C, ID *id, PointerRNA *ptr, PropertyRNA *prop)
450 {
451         ID *newid = NULL;
452         PointerRNA idptr;
453         
454         if (id) {
455                 /* if property isn't editable, we're going to have an extra block hanging around until we save */
456                 if (RNA_property_editable(ptr, prop)) {
457                         if (id_copy(id, &newid, false) && newid) {
458                                 /* copy animation actions too */
459                                 BKE_animdata_copy_id_action(id);
460                                 /* us is 1 by convention, but RNA_property_pointer_set
461                                  * will also increment it, so set it to zero */
462                                 newid->us = 0;
463                                 
464                                 /* assign copy */
465                                 RNA_id_pointer_create(newid, &idptr);
466                                 RNA_property_pointer_set(ptr, prop, idptr);
467                                 RNA_property_update(C, ptr, prop);
468                                 
469                                 return true;
470                         }
471                 }
472         }
473         
474         return false;
475 }
476
477 ListBase *which_libbase(Main *mainlib, short type)
478 {
479         switch (type) {
480                 case ID_SCE:
481                         return &(mainlib->scene);
482                 case ID_LI:
483                         return &(mainlib->library);
484                 case ID_OB:
485                         return &(mainlib->object);
486                 case ID_ME:
487                         return &(mainlib->mesh);
488                 case ID_CU:
489                         return &(mainlib->curve);
490                 case ID_MB:
491                         return &(mainlib->mball);
492                 case ID_MA:
493                         return &(mainlib->mat);
494                 case ID_TE:
495                         return &(mainlib->tex);
496                 case ID_IM:
497                         return &(mainlib->image);
498                 case ID_LT:
499                         return &(mainlib->latt);
500                 case ID_LA:
501                         return &(mainlib->lamp);
502                 case ID_CA:
503                         return &(mainlib->camera);
504                 case ID_IP:
505                         return &(mainlib->ipo);
506                 case ID_KE:
507                         return &(mainlib->key);
508                 case ID_WO:
509                         return &(mainlib->world);
510                 case ID_SCR:
511                         return &(mainlib->screen);
512                 case ID_VF:
513                         return &(mainlib->vfont);
514                 case ID_TXT:
515                         return &(mainlib->text);
516                 case ID_SPK:
517                         return &(mainlib->speaker);
518                 case ID_SO:
519                         return &(mainlib->sound);
520                 case ID_GR:
521                         return &(mainlib->group);
522                 case ID_AR:
523                         return &(mainlib->armature);
524                 case ID_AC:
525                         return &(mainlib->action);
526                 case ID_NT:
527                         return &(mainlib->nodetree);
528                 case ID_BR:
529                         return &(mainlib->brush);
530                 case ID_PA:
531                         return &(mainlib->particle);
532                 case ID_WM:
533                         return &(mainlib->wm);
534                 case ID_GD:
535                         return &(mainlib->gpencil);
536                 case ID_MC:
537                         return &(mainlib->movieclip);
538                 case ID_MSK:
539                         return &(mainlib->mask);
540                 case ID_LS:
541                         return &(mainlib->linestyle);
542                 case ID_PAL:
543                         return &(mainlib->palettes);
544                 case ID_PC:
545                         return &(mainlib->paintcurves);
546         }
547         return NULL;
548 }
549
550 /* Flag all ids in listbase */
551 void BKE_main_id_flag_listbase(ListBase *lb, const short flag, const bool value)
552 {
553         ID *id;
554         if (value) {
555                 for (id = lb->first; id; id = id->next) id->flag |= flag;
556         }
557         else {
558                 const short nflag = ~flag;
559                 for (id = lb->first; id; id = id->next) id->flag &= nflag;
560         }
561 }
562
563 /* Flag all ids in listbase */
564 void BKE_main_id_flag_all(Main *bmain, const short flag, const bool value)
565 {
566         ListBase *lbarray[MAX_LIBARRAY];
567         int a;
568         a = set_listbasepointers(bmain, lbarray);
569         while (a--) {
570                 BKE_main_id_flag_listbase(lbarray[a], flag, value);
571         }
572 }
573
574 void BKE_main_lib_objects_recalc_all(Main *bmain)
575 {
576         Object *ob;
577
578         /* flag for full recalc */
579         for (ob = bmain->object.first; ob; ob = ob->id.next) {
580                 if (ob->id.lib) {
581                         DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
582                 }
583         }
584
585         DAG_id_type_tag(bmain, ID_OB);
586 }
587
588 /**
589  * puts into array *lb pointers to all the ListBase structs in main,
590  * and returns the number of them as the function result. This is useful for
591  * generic traversal of all the blocks in a Main (by traversing all the
592  * lists in turn), without worrying about block types.
593  *
594  * \note MAX_LIBARRAY define should match this code */
595 int set_listbasepointers(Main *main, ListBase **lb)
596 {
597         int a = 0;
598
599         /* BACKWARDS! also watch order of free-ing! (mesh<->mat), first items freed last.
600          * This is important because freeing data decreases usercounts of other datablocks,
601          * if this data is its self freed it can crash. */
602         lb[a++] = &(main->library);  /* Libraries may be accessed from pretty much any other ID... */
603         lb[a++] = &(main->ipo);
604         lb[a++] = &(main->action); /* moved here to avoid problems when freeing with animato (aligorith) */
605         lb[a++] = &(main->key);
606         lb[a++] = &(main->gpencil); /* referenced by nodes, objects, view, scene etc, before to free after. */
607         lb[a++] = &(main->nodetree);
608         lb[a++] = &(main->image);
609         lb[a++] = &(main->tex);
610         lb[a++] = &(main->mat);
611         lb[a++] = &(main->vfont);
612         
613         /* Important!: When adding a new object type,
614          * the specific data should be inserted here 
615          */
616
617         lb[a++] = &(main->armature);
618
619         lb[a++] = &(main->mesh);
620         lb[a++] = &(main->curve);
621         lb[a++] = &(main->mball);
622
623         lb[a++] = &(main->latt);
624         lb[a++] = &(main->lamp);
625         lb[a++] = &(main->camera);
626
627         lb[a++] = &(main->text);
628         lb[a++] = &(main->sound);
629         lb[a++] = &(main->group);
630         lb[a++] = &(main->palettes);
631         lb[a++] = &(main->paintcurves);
632         lb[a++] = &(main->brush);
633         lb[a++] = &(main->particle);
634         lb[a++] = &(main->speaker);
635
636         lb[a++] = &(main->world);
637         lb[a++] = &(main->movieclip);
638         lb[a++] = &(main->screen);
639         lb[a++] = &(main->object);
640         lb[a++] = &(main->linestyle); /* referenced by scenes */
641         lb[a++] = &(main->scene);
642         lb[a++] = &(main->wm);
643         lb[a++] = &(main->mask);
644         
645         lb[a] = NULL;
646
647         BLI_assert(a + 1 == MAX_LIBARRAY);
648
649         return a;
650 }
651
652 /* *********** ALLOC AND FREE *****************
653  *
654  * BKE_libblock_free(ListBase *lb, ID *id )
655  * provide a list-basis and datablock, but only ID is read
656  *
657  * void *BKE_libblock_alloc(ListBase *lb, type, name)
658  * inserts in list and returns a new ID
659  *
660  * **************************** */
661
662 /**
663  * Allocates and returns memory of the right size for the specified block type,
664  * initialized to zero.
665  */
666 void *BKE_libblock_alloc_notest(short type)
667 {
668         ID *id = NULL;
669         
670         switch (type) {
671                 case ID_SCE:
672                         id = MEM_callocN(sizeof(Scene), "scene");
673                         break;
674                 case ID_LI:
675                         id = MEM_callocN(sizeof(Library), "library");
676                         break;
677                 case ID_OB:
678                         id = MEM_callocN(sizeof(Object), "object");
679                         break;
680                 case ID_ME:
681                         id = MEM_callocN(sizeof(Mesh), "mesh");
682                         break;
683                 case ID_CU:
684                         id = MEM_callocN(sizeof(Curve), "curve");
685                         break;
686                 case ID_MB:
687                         id = MEM_callocN(sizeof(MetaBall), "mball");
688                         break;
689                 case ID_MA:
690                         id = MEM_callocN(sizeof(Material), "mat");
691                         break;
692                 case ID_TE:
693                         id = MEM_callocN(sizeof(Tex), "tex");
694                         break;
695                 case ID_IM:
696                         id = MEM_callocN(sizeof(Image), "image");
697                         break;
698                 case ID_LT:
699                         id = MEM_callocN(sizeof(Lattice), "latt");
700                         break;
701                 case ID_LA:
702                         id = MEM_callocN(sizeof(Lamp), "lamp");
703                         break;
704                 case ID_CA:
705                         id = MEM_callocN(sizeof(Camera), "camera");
706                         break;
707                 case ID_IP:
708                         id = MEM_callocN(sizeof(Ipo), "ipo");
709                         break;
710                 case ID_KE:
711                         id = MEM_callocN(sizeof(Key), "key");
712                         break;
713                 case ID_WO:
714                         id = MEM_callocN(sizeof(World), "world");
715                         break;
716                 case ID_SCR:
717                         id = MEM_callocN(sizeof(bScreen), "screen");
718                         break;
719                 case ID_VF:
720                         id = MEM_callocN(sizeof(VFont), "vfont");
721                         break;
722                 case ID_TXT:
723                         id = MEM_callocN(sizeof(Text), "text");
724                         break;
725                 case ID_SPK:
726                         id = MEM_callocN(sizeof(Speaker), "speaker");
727                         break;
728                 case ID_SO:
729                         id = MEM_callocN(sizeof(bSound), "sound");
730                         break;
731                 case ID_GR:
732                         id = MEM_callocN(sizeof(Group), "group");
733                         break;
734                 case ID_AR:
735                         id = MEM_callocN(sizeof(bArmature), "armature");
736                         break;
737                 case ID_AC:
738                         id = MEM_callocN(sizeof(bAction), "action");
739                         break;
740                 case ID_NT:
741                         id = MEM_callocN(sizeof(bNodeTree), "nodetree");
742                         break;
743                 case ID_BR:
744                         id = MEM_callocN(sizeof(Brush), "brush");
745                         break;
746                 case ID_PA:
747                         id = MEM_callocN(sizeof(ParticleSettings), "ParticleSettings");
748                         break;
749                 case ID_WM:
750                         id = MEM_callocN(sizeof(wmWindowManager), "Window manager");
751                         break;
752                 case ID_GD:
753                         id = MEM_callocN(sizeof(bGPdata), "Grease Pencil");
754                         break;
755                 case ID_MC:
756                         id = MEM_callocN(sizeof(MovieClip), "Movie Clip");
757                         break;
758                 case ID_MSK:
759                         id = MEM_callocN(sizeof(Mask), "Mask");
760                         break;
761                 case ID_LS:
762                         id = MEM_callocN(sizeof(FreestyleLineStyle), "Freestyle Line Style");
763                         break;
764                 case ID_PAL:
765                         id = MEM_callocN(sizeof(Palette), "Palette");
766                         break;
767                 case ID_PC:
768                         id = MEM_callocN(sizeof(PaintCurve), "Paint Curve");
769                         break;
770         }
771         return id;
772 }
773
774 /**
775  * Allocates and returns a block of the specified type, with the specified name
776  * (adjusted as necessary to ensure uniqueness), and appended to the specified list.
777  * The user count is set to 1, all other content (apart from name and links) being
778  * initialized to zero.
779  */
780 void *BKE_libblock_alloc(Main *bmain, short type, const char *name)
781 {
782         ID *id = NULL;
783         ListBase *lb = which_libbase(bmain, type);
784         
785         id = BKE_libblock_alloc_notest(type);
786         if (id) {
787                 BKE_main_lock(bmain);
788                 BLI_addtail(lb, id);
789                 id->us = 1;
790                 id->icon_id = 0;
791                 *( (short *)id->name) = type;
792                 new_id(lb, id, name);
793                 /* alphabetic insertion: is in new_id */
794                 BKE_main_unlock(bmain);
795         }
796         DAG_id_type_tag(bmain, type);
797         return id;
798 }
799
800 /**
801  * Initialize an ID of given type, such that it has valid 'empty' data.
802  * ID is assumed to be just calloc'ed.
803  */
804 void BKE_libblock_init_empty(ID *id)
805 {
806         /* Note that only ID types that are not valid when filled of zero should have a callback here. */
807         switch (GS(id->name)) {
808                 case ID_SCE:
809                         BKE_scene_init((Scene *)id);
810                         break;
811                 case ID_LI:
812                         /* Nothing to do. */
813                         break;
814                 case ID_OB:
815                 {
816                         Object *ob = (Object *)id;
817                         ob->type = OB_EMPTY;
818                         BKE_object_init(ob);
819                         break;
820                 }
821                 case ID_ME:
822                         BKE_mesh_init((Mesh *)id);
823                         break;
824                 case ID_CU:
825                         BKE_curve_init((Curve *)id);
826                         break;
827                 case ID_MB:
828                         BKE_mball_init((MetaBall *)id);
829                         break;
830                 case ID_MA:
831                         BKE_material_init((Material *)id);
832                         break;
833                 case ID_TE:
834                         BKE_texture_default((Tex *)id);
835                         break;
836                 case ID_IM:
837                         /* Image is a bit complicated, for now assume NULLified im is OK. */
838                         break;
839                 case ID_LT:
840                         BKE_lattice_init((Lattice *)id);
841                         break;
842                 case ID_LA:
843                         BKE_lamp_init((Lamp *)id);
844                         break;
845                 case ID_SPK:
846                         BKE_speaker_init((Speaker *)id);
847                         break;
848                 case ID_CA:
849                         BKE_camera_init((Camera *)id);
850                         break;
851                 case ID_IP:
852                         /* Should not be needed - animation from lib pre-2.5 is broken anyway. */
853                         BLI_assert(0);
854                         break;
855                 case ID_KE:
856                         /* Shapekeys are a complex topic too - they depend on their 'user' data type...
857                          * They are not linkable, though, so it should never reach here anyway. */
858                         BLI_assert(0);
859                         break;
860                 case ID_WO:
861                         BKE_world_init((World *)id);
862                         break;
863                 case ID_SCR:
864                         /* Nothing to do. */
865                         break;
866                 case ID_VF:
867                         BKE_vfont_init((VFont *)id);
868                         break;
869                 case ID_TXT:
870                         BKE_text_init((Text *)id);
871                         break;
872                 case ID_SO:
873                         /* Another fuzzy case, think NULLified content is OK here... */
874                         break;
875                 case ID_GR:
876                         /* Nothing to do. */
877                         break;
878                 case ID_AR:
879                         /* Nothing to do. */
880                         break;
881                 case ID_AC:
882                         /* Nothing to do. */
883                         break;
884                 case ID_NT:
885                         ntreeInitDefault((bNodeTree *)id);
886                         break;
887                 case ID_BR:
888                         BKE_brush_init((Brush *)id);
889                         break;
890                 case ID_PA:
891                         /* Nothing to do. */
892                         break;
893                 case ID_PC:
894                         /* Nothing to do. */
895                         break;
896                 case ID_WM:
897                         /* We should never reach this. */
898                         BLI_assert(0);
899                         break;
900                 case ID_GD:
901                         /* Nothing to do. */
902                         break;
903                 case ID_MSK:
904                         /* Nothing to do. */
905                         break;
906                 case ID_LS:
907                         BKE_linestyle_init((FreestyleLineStyle *)id);
908                         break;
909         }
910 }
911
912 /* by spec, animdata is first item after ID */
913 /* and, trust that BKE_animdata_from_id() will only find AnimData for valid ID-types */
914 static void id_copy_animdata(ID *id, const bool do_action)
915 {
916         AnimData *adt = BKE_animdata_from_id(id);
917         
918         if (adt) {
919                 IdAdtTemplate *iat = (IdAdtTemplate *)id;
920                 iat->adt = BKE_animdata_copy(iat->adt, do_action); /* could be set to false, need to investigate */
921         }
922 }
923
924 /* material nodes use this since they are not treated as libdata */
925 void BKE_libblock_copy_data(ID *id, const ID *id_from, const bool do_action)
926 {
927         if (id_from->properties)
928                 id->properties = IDP_CopyProperty(id_from->properties);
929
930         /* the duplicate should get a copy of the animdata */
931         id_copy_animdata(id, do_action);
932 }
933
934 /* used everywhere in blenkernel */
935 void *BKE_libblock_copy_ex(Main *bmain, ID *id)
936 {
937         ID *idn;
938         size_t idn_len;
939
940         idn = BKE_libblock_alloc(bmain, GS(id->name), id->name + 2);
941
942         assert(idn != NULL);
943
944         idn_len = MEM_allocN_len(idn);
945         if ((int)idn_len - (int)sizeof(ID) > 0) { /* signed to allow neg result */
946                 const char *cp = (const char *)id;
947                 char *cpn = (char *)idn;
948
949                 memcpy(cpn + sizeof(ID), cp + sizeof(ID), idn_len - sizeof(ID));
950         }
951         
952         id->newid = idn;
953         idn->flag |= LIB_NEW;
954
955         BKE_libblock_copy_data(idn, id, false);
956         
957         return idn;
958 }
959
960 void *BKE_libblock_copy_nolib(ID *id, const bool do_action)
961 {
962         ID *idn;
963         size_t idn_len;
964
965         idn = BKE_libblock_alloc_notest(GS(id->name));
966         assert(idn != NULL);
967
968         BLI_strncpy(idn->name, id->name, sizeof(idn->name));
969
970         idn_len = MEM_allocN_len(idn);
971         if ((int)idn_len - (int)sizeof(ID) > 0) { /* signed to allow neg result */
972                 const char *cp = (const char *)id;
973                 char *cpn = (char *)idn;
974
975                 memcpy(cpn + sizeof(ID), cp + sizeof(ID), idn_len - sizeof(ID));
976         }
977
978         id->newid = idn;
979         idn->flag |= LIB_NEW;
980         idn->us = 1;
981
982         BKE_libblock_copy_data(idn, id, do_action);
983
984         return idn;
985 }
986
987 void *BKE_libblock_copy(ID *id)
988 {
989         return BKE_libblock_copy_ex(G.main, id);
990 }
991
992 static bool id_relink_looper(void *UNUSED(user_data), ID **id_pointer, const int cd_flag)
993 {
994         ID *id = *id_pointer;
995         if (id) {
996                 /* See: NEW_ID macro */
997                 if (id->newid) {
998                         BKE_library_update_ID_link_user(id->newid, id, cd_flag);
999                         *id_pointer = id->newid;
1000                 }
1001                 else if (id->flag & LIB_NEW) {
1002                         id->flag &= ~LIB_NEW;
1003                         BKE_libblock_relink(id);
1004                 }
1005         }
1006         return true;
1007 }
1008
1009 void BKE_libblock_relink(ID *id)
1010 {
1011         if (id->lib)
1012                 return;
1013
1014         BKE_library_foreach_ID_link(id, id_relink_looper, NULL, 0);
1015 }
1016
1017 static void BKE_library_free(Library *lib)
1018 {
1019         if (lib->packedfile)
1020                 freePackedFile(lib->packedfile);
1021 }
1022
1023 static BKE_library_free_window_manager_cb free_windowmanager_cb = NULL;
1024
1025 void BKE_library_callback_free_window_manager_set(BKE_library_free_window_manager_cb func)
1026 {
1027         free_windowmanager_cb = func;
1028 }
1029
1030 static BKE_library_free_notifier_reference_cb free_notifier_reference_cb = NULL;
1031
1032 void BKE_library_callback_free_notifier_reference_set(BKE_library_free_notifier_reference_cb func)
1033 {
1034         free_notifier_reference_cb = func;
1035 }
1036
1037 static BKE_library_free_editor_id_reference_cb free_editor_id_reference_cb = NULL;
1038
1039 void BKE_library_callback_free_editor_id_reference_set(BKE_library_free_editor_id_reference_cb func)
1040 {
1041         free_editor_id_reference_cb = func;
1042 }
1043
1044 static void animdata_dtar_clear_cb(ID *UNUSED(id), AnimData *adt, void *userdata)
1045 {
1046         ChannelDriver *driver;
1047         FCurve *fcu;
1048
1049         /* find the driver this belongs to and update it */
1050         for (fcu = adt->drivers.first; fcu; fcu = fcu->next) {
1051                 driver = fcu->driver;
1052                 
1053                 if (driver) {
1054                         DriverVar *dvar;
1055                         for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
1056                                 DRIVER_TARGETS_USED_LOOPER(dvar) 
1057                                 {
1058                                         if (dtar->id == userdata)
1059                                                 dtar->id = NULL;
1060                                 }
1061                                 DRIVER_TARGETS_LOOPER_END
1062                         }
1063                 }
1064         }
1065 }
1066
1067 void BKE_libblock_free_data(Main *bmain, ID *id)
1068 {
1069         if (id->properties) {
1070                 IDP_FreeProperty(id->properties);
1071                 MEM_freeN(id->properties);
1072         }
1073         
1074         /* this ID may be a driver target! */
1075         BKE_animdata_main_cb(bmain, animdata_dtar_clear_cb, (void *)id);
1076 }
1077
1078 /* used in headerbuttons.c image.c mesh.c screen.c sound.c and library.c */
1079 void BKE_libblock_free_ex(Main *bmain, void *idv, bool do_id_user)
1080 {
1081         ID *id = idv;
1082         short type = GS(id->name);
1083         ListBase *lb = which_libbase(bmain, type);
1084
1085         DAG_id_type_tag(bmain, type);
1086
1087 #ifdef WITH_PYTHON
1088         BPY_id_release(id);
1089 #endif
1090
1091         switch (type) {    /* GetShort from util.h */
1092                 case ID_SCE:
1093                         BKE_scene_free((Scene *)id);
1094                         break;
1095                 case ID_LI:
1096                         BKE_library_free((Library *)id);
1097                         break;
1098                 case ID_OB:
1099                         BKE_object_free_ex((Object *)id, do_id_user);
1100                         break;
1101                 case ID_ME:
1102                         BKE_mesh_free((Mesh *)id, 1);
1103                         break;
1104                 case ID_CU:
1105                         BKE_curve_free((Curve *)id);
1106                         break;
1107                 case ID_MB:
1108                         BKE_mball_free((MetaBall *)id);
1109                         break;
1110                 case ID_MA:
1111                         BKE_material_free((Material *)id);
1112                         break;
1113                 case ID_TE:
1114                         BKE_texture_free((Tex *)id);
1115                         break;
1116                 case ID_IM:
1117                         BKE_image_free((Image *)id);
1118                         break;
1119                 case ID_LT:
1120                         BKE_lattice_free((Lattice *)id);
1121                         break;
1122                 case ID_LA:
1123                         BKE_lamp_free((Lamp *)id);
1124                         break;
1125                 case ID_CA:
1126                         BKE_camera_free((Camera *) id);
1127                         break;
1128                 case ID_IP:
1129                         BKE_ipo_free((Ipo *)id);
1130                         break;
1131                 case ID_KE:
1132                         BKE_key_free((Key *)id);
1133                         break;
1134                 case ID_WO:
1135                         BKE_world_free((World *)id);
1136                         break;
1137                 case ID_SCR:
1138                         BKE_screen_free((bScreen *)id);
1139                         break;
1140                 case ID_VF:
1141                         BKE_vfont_free((VFont *)id);
1142                         break;
1143                 case ID_TXT:
1144                         BKE_text_free((Text *)id);
1145                         break;
1146                 case ID_SPK:
1147                         BKE_speaker_free((Speaker *)id);
1148                         break;
1149                 case ID_SO:
1150                         BKE_sound_free((bSound *)id);
1151                         break;
1152                 case ID_GR:
1153                         BKE_group_free((Group *)id);
1154                         break;
1155                 case ID_AR:
1156                         BKE_armature_free((bArmature *)id);
1157                         break;
1158                 case ID_AC:
1159                         BKE_action_free((bAction *)id);
1160                         break;
1161                 case ID_NT:
1162                         ntreeFreeTree_ex((bNodeTree *)id, do_id_user);
1163                         break;
1164                 case ID_BR:
1165                         BKE_brush_free((Brush *)id);
1166                         break;
1167                 case ID_PA:
1168                         BKE_particlesettings_free((ParticleSettings *)id);
1169                         break;
1170                 case ID_WM:
1171                         if (free_windowmanager_cb)
1172                                 free_windowmanager_cb(NULL, (wmWindowManager *)id);
1173                         break;
1174                 case ID_GD:
1175                         BKE_gpencil_free((bGPdata *)id);
1176                         break;
1177                 case ID_MC:
1178                         BKE_movieclip_free((MovieClip *)id);
1179                         break;
1180                 case ID_MSK:
1181                         BKE_mask_free(bmain, (Mask *)id);
1182                         break;
1183                 case ID_LS:
1184                         BKE_linestyle_free((FreestyleLineStyle *)id);
1185                         break;
1186                 case ID_PAL:
1187                         BKE_palette_free((Palette *)id);
1188                         break;
1189                 case ID_PC:
1190                         BKE_paint_curve_free((PaintCurve *)id);
1191                         break;
1192         }
1193
1194         /* avoid notifying on removed data */
1195         BKE_main_lock(bmain);
1196
1197         if (free_notifier_reference_cb) {
1198                 free_notifier_reference_cb(id);
1199         }
1200
1201         if (free_editor_id_reference_cb) {
1202                 free_editor_id_reference_cb(id);
1203         }
1204
1205         BLI_remlink(lb, id);
1206
1207         BKE_libblock_free_data(bmain, id);
1208         BKE_main_unlock(bmain);
1209
1210         MEM_freeN(id);
1211 }
1212
1213 void BKE_libblock_free(Main *bmain, void *idv)
1214 {
1215         BKE_libblock_free_ex(bmain, idv, true);
1216 }
1217
1218 void BKE_libblock_free_us(Main *bmain, void *idv)      /* test users */
1219 {
1220         ID *id = idv;
1221         
1222         id_us_min(id);
1223
1224         if (id->us == 0) {
1225                 switch (GS(id->name)) {
1226                         case ID_OB:
1227                                 BKE_object_unlink(bmain, (Object *)id);
1228                                 break;
1229                 }
1230                 
1231                 BKE_libblock_free(bmain, id);
1232         }
1233 }
1234
1235 Main *BKE_main_new(void)
1236 {
1237         Main *bmain = MEM_callocN(sizeof(Main), "new main");
1238         bmain->eval_ctx = DEG_evaluation_context_new(DAG_EVAL_VIEWPORT);
1239         bmain->lock = MEM_mallocN(sizeof(SpinLock), "main lock");
1240         BLI_spin_init((SpinLock *)bmain->lock);
1241         return bmain;
1242 }
1243
1244 void BKE_main_free(Main *mainvar)
1245 {
1246         /* also call when reading a file, erase all, etc */
1247         ListBase *lbarray[MAX_LIBARRAY];
1248         int a;
1249
1250         MEM_SAFE_FREE(mainvar->blen_thumb);
1251
1252         a = set_listbasepointers(mainvar, lbarray);
1253         while (a--) {
1254                 ListBase *lb = lbarray[a];
1255                 ID *id;
1256                 
1257                 while ( (id = lb->first) ) {
1258 #if 1
1259                         BKE_libblock_free_ex(mainvar, id, false);
1260 #else
1261                         /* errors freeing ID's can be hard to track down,
1262                          * enable this so valgrind will give the line number in its error log */
1263                         switch (a) {
1264                                 case   0: BKE_libblock_free_ex(mainvar, id, false); break;
1265                                 case   1: BKE_libblock_free_ex(mainvar, id, false); break;
1266                                 case   2: BKE_libblock_free_ex(mainvar, id, false); break;
1267                                 case   3: BKE_libblock_free_ex(mainvar, id, false); break;
1268                                 case   4: BKE_libblock_free_ex(mainvar, id, false); break;
1269                                 case   5: BKE_libblock_free_ex(mainvar, id, false); break;
1270                                 case   6: BKE_libblock_free_ex(mainvar, id, false); break;
1271                                 case   7: BKE_libblock_free_ex(mainvar, id, false); break;
1272                                 case   8: BKE_libblock_free_ex(mainvar, id, false); break;
1273                                 case   9: BKE_libblock_free_ex(mainvar, id, false); break;
1274                                 case  10: BKE_libblock_free_ex(mainvar, id, false); break;
1275                                 case  11: BKE_libblock_free_ex(mainvar, id, false); break;
1276                                 case  12: BKE_libblock_free_ex(mainvar, id, false); break;
1277                                 case  13: BKE_libblock_free_ex(mainvar, id, false); break;
1278                                 case  14: BKE_libblock_free_ex(mainvar, id, false); break;
1279                                 case  15: BKE_libblock_free_ex(mainvar, id, false); break;
1280                                 case  16: BKE_libblock_free_ex(mainvar, id, false); break;
1281                                 case  17: BKE_libblock_free_ex(mainvar, id, false); break;
1282                                 case  18: BKE_libblock_free_ex(mainvar, id, false); break;
1283                                 case  19: BKE_libblock_free_ex(mainvar, id, false); break;
1284                                 case  20: BKE_libblock_free_ex(mainvar, id, false); break;
1285                                 case  21: BKE_libblock_free_ex(mainvar, id, false); break;
1286                                 case  22: BKE_libblock_free_ex(mainvar, id, false); break;
1287                                 case  23: BKE_libblock_free_ex(mainvar, id, false); break;
1288                                 case  24: BKE_libblock_free_ex(mainvar, id, false); break;
1289                                 case  25: BKE_libblock_free_ex(mainvar, id, false); break;
1290                                 case  26: BKE_libblock_free_ex(mainvar, id, false); break;
1291                                 case  27: BKE_libblock_free_ex(mainvar, id, false); break;
1292                                 case  28: BKE_libblock_free_ex(mainvar, id, false); break;
1293                                 case  29: BKE_libblock_free_ex(mainvar, id, false); break;
1294                                 case  30: BKE_libblock_free_ex(mainvar, id, false); break;
1295                                 case  31: BKE_libblock_free_ex(mainvar, id, false); break;
1296                                 case  32: BKE_libblock_free_ex(mainvar, id, false); break;
1297                                 case  33: BKE_libblock_free_ex(mainvar, id, false); break;
1298                                 default:
1299                                         BLI_assert(0);
1300                                         break;
1301                         }
1302 #endif
1303                 }
1304         }
1305
1306         BLI_spin_end((SpinLock *)mainvar->lock);
1307         MEM_freeN(mainvar->lock);
1308         DEG_evaluation_context_free(mainvar->eval_ctx);
1309         MEM_freeN(mainvar);
1310 }
1311
1312 void BKE_main_lock(struct Main *bmain)
1313 {
1314         BLI_spin_lock((SpinLock *) bmain->lock);
1315 }
1316
1317 void BKE_main_unlock(struct Main *bmain)
1318 {
1319         BLI_spin_unlock((SpinLock *) bmain->lock);
1320 }
1321
1322 /**
1323  * Generates a raw .blend file thumbnail data from given image.
1324  *
1325  * \param bmain If not NULL, also store generated data in this Main.
1326  * \param img ImBuf image to generate thumbnail data from.
1327  * \return The generated .blend file raw thumbnail data.
1328  */
1329 BlendThumbnail *BKE_main_thumbnail_from_imbuf(Main *bmain, ImBuf *img)
1330 {
1331         BlendThumbnail *data = NULL;
1332
1333         if (bmain) {
1334                 MEM_SAFE_FREE(bmain->blen_thumb);
1335         }
1336
1337         if (img) {
1338                 const size_t sz = BLEN_THUMB_MEMSIZE(img->x, img->y);
1339                 data = MEM_mallocN(sz, __func__);
1340
1341                 IMB_rect_from_float(img);  /* Just in case... */
1342                 data->width = img->x;
1343                 data->height = img->y;
1344                 memcpy(data->rect, img->rect, sz - sizeof(*data));
1345         }
1346
1347         if (bmain) {
1348                 bmain->blen_thumb = data;
1349         }
1350         return data;
1351 }
1352
1353 /**
1354  * Generates an image from raw .blend file thumbnail \a data.
1355  *
1356  * \param bmain Use this bmain->blen_thumb data if given \a data is NULL.
1357  * \param data Raw .blend file thumbnail data.
1358  * \return An ImBuf from given data, or NULL if invalid.
1359  */
1360 ImBuf *BKE_main_thumbnail_to_imbuf(Main *bmain, BlendThumbnail *data)
1361 {
1362         ImBuf *img = NULL;
1363
1364         if (!data && bmain) {
1365                 data = bmain->blen_thumb;
1366         }
1367
1368         if (data) {
1369                 /* Note: we cannot use IMB_allocFromBuffer(), since it tries to dupalloc passed buffer, which will fail
1370                  *       here (we do not want to pass the first two ints!). */
1371                 img = IMB_allocImBuf((unsigned int)data->width, (unsigned int)data->height, 32, IB_rect | IB_metadata);
1372                 memcpy(img->rect, data->rect, BLEN_THUMB_MEMSIZE(data->width, data->height) - sizeof(*data));
1373         }
1374
1375         return img;
1376 }
1377
1378 /**
1379  * Generates an empty (black) thumbnail for given Main.
1380  */
1381 void BKE_main_thumbnail_create(struct Main *bmain)
1382 {
1383         MEM_SAFE_FREE(bmain->blen_thumb);
1384
1385         bmain->blen_thumb = MEM_callocN(BLEN_THUMB_MEMSIZE(BLEN_THUMB_SIZE, BLEN_THUMB_SIZE), __func__);
1386         bmain->blen_thumb->width = BLEN_THUMB_SIZE;
1387         bmain->blen_thumb->height = BLEN_THUMB_SIZE;
1388 }
1389
1390 /* ***************** ID ************************ */
1391 ID *BKE_libblock_find_name_ex(struct Main *bmain, const short type, const char *name)
1392 {
1393         ListBase *lb = which_libbase(bmain, type);
1394         BLI_assert(lb != NULL);
1395         return BLI_findstring(lb, name, offsetof(ID, name) + 2);
1396 }
1397 ID *BKE_libblock_find_name(const short type, const char *name)
1398 {
1399         return BKE_libblock_find_name_ex(G.main, type, name);
1400 }
1401
1402
1403 void id_sort_by_name(ListBase *lb, ID *id)
1404 {
1405         ID *idtest;
1406         
1407         /* insert alphabetically */
1408         if (lb->first != lb->last) {
1409                 BLI_remlink(lb, id);
1410                 
1411                 idtest = lb->first;
1412                 while (idtest) {
1413                         if (BLI_strcasecmp(idtest->name, id->name) > 0 || (idtest->lib && !id->lib)) {
1414                                 BLI_insertlinkbefore(lb, idtest, id);
1415                                 break;
1416                         }
1417                         idtest = idtest->next;
1418                 }
1419                 /* as last */
1420                 if (idtest == NULL) {
1421                         BLI_addtail(lb, id);
1422                 }
1423         }
1424         
1425 }
1426
1427 /**
1428  * Check to see if there is an ID with the same name as 'name'.
1429  * Returns the ID if so, if not, returns NULL
1430  */
1431 static ID *is_dupid(ListBase *lb, ID *id, const char *name)
1432 {
1433         ID *idtest = NULL;
1434         
1435         for (idtest = lb->first; idtest; idtest = idtest->next) {
1436                 /* if idtest is not a lib */ 
1437                 if (id != idtest && idtest->lib == NULL) {
1438                         /* do not test alphabetic! */
1439                         /* optimized */
1440                         if (idtest->name[2] == name[0]) {
1441                                 if (STREQ(name, idtest->name + 2)) break;
1442                         }
1443                 }
1444         }
1445         
1446         return idtest;
1447 }
1448
1449 /**
1450  * Check to see if an ID name is already used, and find a new one if so.
1451  * Return true if created a new name (returned in name).
1452  *
1453  * Normally the ID that's being check is already in the ListBase, so ID *id
1454  * points at the new entry.  The Python Library module needs to know what
1455  * the name of a datablock will be before it is appended; in this case ID *id
1456  * id is NULL
1457  */
1458
1459 static bool check_for_dupid(ListBase *lb, ID *id, char *name)
1460 {
1461         ID *idtest;
1462         int nr = 0, a, left_len;
1463 #define MAX_IN_USE 64
1464         bool in_use[MAX_IN_USE];
1465         /* to speed up finding unused numbers within [1 .. MAX_IN_USE - 1] */
1466
1467         char left[MAX_ID_NAME + 8], leftest[MAX_ID_NAME + 8];
1468
1469         while (true) {
1470
1471                 /* phase 1: id already exists? */
1472                 idtest = is_dupid(lb, id, name);
1473
1474                 /* if there is no double, done */
1475                 if (idtest == NULL) return false;
1476
1477                 /* we have a dup; need to make a new name */
1478                 /* quick check so we can reuse one of first MAX_IN_USE - 1 ids if vacant */
1479                 memset(in_use, false, sizeof(in_use));
1480
1481                 /* get name portion, number portion ("name.number") */
1482                 left_len = BLI_split_name_num(left, &nr, name, '.');
1483
1484                 /* if new name will be too long, truncate it */
1485                 if (nr > 999 && left_len > (MAX_ID_NAME - 8)) {  /* assumption: won't go beyond 9999 */
1486                         left[MAX_ID_NAME - 8] = 0;
1487                         left_len = MAX_ID_NAME - 8;
1488                 }
1489                 else if (left_len > (MAX_ID_NAME - 7)) {
1490                         left[MAX_ID_NAME - 7] = 0;
1491                         left_len = MAX_ID_NAME - 7;
1492                 }
1493
1494                 for (idtest = lb->first; idtest; idtest = idtest->next) {
1495                         int nrtest;
1496                         if ( (id != idtest) &&
1497                              (idtest->lib == NULL) &&
1498                              (*name == *(idtest->name + 2)) &&
1499                              STREQLEN(name, idtest->name + 2, left_len) &&
1500                              (BLI_split_name_num(leftest, &nrtest, idtest->name + 2, '.') == left_len)
1501                              )
1502                         {
1503                                 /* will get here at least once, otherwise is_dupid call above would have returned NULL */
1504                                 if (nrtest < MAX_IN_USE)
1505                                         in_use[nrtest] = true;  /* mark as used */
1506                                 if (nr <= nrtest)
1507                                         nr = nrtest + 1;    /* track largest unused */
1508                         }
1509                 }
1510                 /* At this point, 'nr' will typically be at least 1. (but not always) */
1511                 // BLI_assert(nr >= 1);
1512
1513                 /* decide which value of nr to use */
1514                 for (a = 0; a < MAX_IN_USE; a++) {
1515                         if (a >= nr) break;  /* stop when we've checked up to biggest */  /* redundant check */
1516                         if (!in_use[a]) { /* found an unused value */
1517                                 nr = a;
1518                                 /* can only be zero if all potential duplicate names had
1519                                  * nonzero numeric suffixes, which means name itself has
1520                                  * nonzero numeric suffix (else no name conflict and wouldn't
1521                                  * have got here), which means name[left_len] is not a null */
1522                                 break;
1523                         }
1524                 }
1525                 /* At this point, nr is either the lowest unused number within [0 .. MAX_IN_USE - 1],
1526                  * or 1 greater than the largest used number if all those low ones are taken.
1527                  * We can't be bothered to look for the lowest unused number beyond (MAX_IN_USE - 1). */
1528
1529                 /* If the original name has no numeric suffix, 
1530                  * rather than just chopping and adding numbers, 
1531                  * shave off the end chars until we have a unique name.
1532                  * Check the null terminators match as well so we don't get Cube.000 -> Cube.00 */
1533                 if (nr == 0 && name[left_len] == '\0') {
1534                         int len;
1535                         /* FIXME: this code will never be executed, because either nr will be
1536                          * at least 1, or name will not end at left_len! */
1537                         BLI_assert(0);
1538
1539                         len = left_len - 1;
1540                         idtest = is_dupid(lb, id, name);
1541                         
1542                         while (idtest && len > 1) {
1543                                 name[len--] = '\0';
1544                                 idtest = is_dupid(lb, id, name);
1545                         }
1546                         if (idtest == NULL) return true;
1547                         /* otherwise just continue and use a number suffix */
1548                 }
1549                 
1550                 if (nr > 999 && left_len > (MAX_ID_NAME - 8)) {
1551                         /* this would overflow name buffer */
1552                         left[MAX_ID_NAME - 8] = 0;
1553                         /* left_len = MAX_ID_NAME - 8; */ /* for now this isn't used again */
1554                         memcpy(name, left, sizeof(char) * (MAX_ID_NAME - 7));
1555                         continue;
1556                 }
1557                 /* this format specifier is from hell... */
1558                 BLI_snprintf(name, sizeof(id->name) - 2, "%s.%.3d", left, nr);
1559
1560                 return true;
1561         }
1562
1563 #undef MAX_IN_USE
1564 }
1565
1566 /*
1567  * Only for local blocks: external en indirect blocks already have a
1568  * unique ID.
1569  *
1570  * return true: created a new name
1571  */
1572
1573 bool new_id(ListBase *lb, ID *id, const char *tname)
1574 {
1575         bool result;
1576         char name[MAX_ID_NAME - 2];
1577
1578         /* if library, don't rename */
1579         if (id->lib)
1580                 return false;
1581
1582         /* if no libdata given, look up based on ID */
1583         if (lb == NULL)
1584                 lb = which_libbase(G.main, GS(id->name));
1585
1586         /* if no name given, use name of current ID
1587          * else make a copy (tname args can be const) */
1588         if (tname == NULL)
1589                 tname = id->name + 2;
1590
1591         BLI_strncpy(name, tname, sizeof(name));
1592
1593         if (name[0] == '\0') {
1594                 /* disallow empty names */
1595                 BLI_strncpy(name, DATA_(ID_FALLBACK_NAME), sizeof(name));
1596         }
1597         else {
1598                 /* disallow non utf8 chars,
1599                  * the interface checks for this but new ID's based on file names don't */
1600                 BLI_utf8_invalid_strip(name, strlen(name));
1601         }
1602
1603         result = check_for_dupid(lb, id, name);
1604         strcpy(id->name + 2, name);
1605
1606         /* This was in 2.43 and previous releases
1607          * however all data in blender should be sorted, not just duplicate names
1608          * sorting should not hurt, but noting just incase it alters the way other
1609          * functions work, so sort every time */
1610 #if 0
1611         if (result)
1612                 id_sort_by_name(lb, id);
1613 #endif
1614
1615         id_sort_by_name(lb, id);
1616         
1617         return result;
1618 }
1619
1620 /**
1621  * Pull an ID out of a library (make it local). Only call this for IDs that
1622  * don't have other library users.
1623  */
1624 void id_clear_lib_data(Main *bmain, ID *id)
1625 {
1626         bNodeTree *ntree = NULL;
1627
1628         BKE_id_lib_local_paths(bmain, id->lib, id);
1629
1630         id_fake_user_clear(id);
1631
1632         id->lib = NULL;
1633         id->flag = LIB_LOCAL;
1634         new_id(which_libbase(bmain, GS(id->name)), id, NULL);
1635
1636         /* internal bNodeTree blocks inside ID types below
1637          * also stores id->lib, make sure this stays in sync.
1638          */
1639         ntree = ntreeFromID(id);
1640
1641         if (ntree) {
1642                 ntree->id.lib = NULL;
1643         }
1644
1645         if (GS(id->name) == ID_OB) {
1646                 Object *object = (Object *)id;
1647                 if (object->proxy_from != NULL) {
1648                         object->proxy_from->proxy = NULL;
1649                         object->proxy_from->proxy_group = NULL;
1650                 }
1651                 object->proxy = object->proxy_from = object->proxy_group = NULL;
1652         }
1653 }
1654
1655 /* next to indirect usage in read/writefile also in editobject.c scene.c */
1656 void BKE_main_id_clear_newpoins(Main *bmain)
1657 {
1658         ListBase *lbarray[MAX_LIBARRAY];
1659         ID *id;
1660         int a;
1661
1662         a = set_listbasepointers(bmain, lbarray);
1663         while (a--) {
1664                 id = lbarray[a]->first;
1665                 while (id) {
1666                         id->newid = NULL;
1667                         id->flag &= ~LIB_NEW;
1668                         id = id->next;
1669                 }
1670         }
1671 }
1672
1673 static void lib_indirect_test_id(ID *id, Library *lib)
1674 {
1675 #define LIBTAG(a)   if (a && a->id.lib) { a->id.flag &= ~LIB_INDIRECT; a->id.flag |= LIB_EXTERN; } (void)0
1676         
1677         if (id->lib) {
1678                 /* datablocks that were indirectly related are now direct links
1679                  * without this, appending data that has a link to other data will fail to write */
1680                 if (lib && id->lib->parent == lib) {
1681                         id_lib_extern(id);
1682                 }
1683                 return;
1684         }
1685         
1686         if (GS(id->name) == ID_OB) {
1687                 Object *ob = (Object *)id;
1688                 Mesh *me;
1689
1690                 int a;
1691
1692 #if 0   /* XXX OLD ANIMSYS, NLASTRIPS ARE NO LONGER USED */
1693                 /* XXX old animation system! -------------------------------------- */
1694                 {
1695                         bActionStrip *strip;
1696                         for (strip = ob->nlastrips.first; strip; strip = strip->next) {
1697                                 LIBTAG(strip->object);
1698                                 LIBTAG(strip->act);
1699                                 LIBTAG(strip->ipo);
1700                         }
1701                 }
1702                 /* XXX: new animation system needs something like this? */
1703 #endif
1704
1705                 for (a = 0; a < ob->totcol; a++) {
1706                         LIBTAG(ob->mat[a]);
1707                 }
1708         
1709                 LIBTAG(ob->dup_group);
1710                 LIBTAG(ob->proxy);
1711                 
1712                 me = ob->data;
1713                 LIBTAG(me);
1714         }
1715
1716 #undef LIBTAG
1717 }
1718
1719 void BKE_main_id_tag_listbase(ListBase *lb, const bool tag)
1720 {
1721         ID *id;
1722         if (tag) {
1723                 for (id = lb->first; id; id = id->next) {
1724                         id->flag |= LIB_DOIT;
1725                 }
1726         }
1727         else {
1728                 for (id = lb->first; id; id = id->next) {
1729                         id->flag &= ~LIB_DOIT;
1730                 }
1731         }
1732 }
1733
1734 void BKE_main_id_tag_idcode(struct Main *mainvar, const short type, const bool tag)
1735 {
1736         ListBase *lb = which_libbase(mainvar, type);
1737
1738         BKE_main_id_tag_listbase(lb, tag);
1739 }
1740
1741 void BKE_main_id_tag_all(struct Main *mainvar, const bool tag)
1742 {
1743         ListBase *lbarray[MAX_LIBARRAY];
1744         int a;
1745
1746         a = set_listbasepointers(mainvar, lbarray);
1747         while (a--) {
1748                 BKE_main_id_tag_listbase(lbarray[a], tag);
1749         }
1750 }
1751
1752 /* if lib!=NULL, only all from lib local
1753  * bmain is almost certainly G.main */
1754 void BKE_library_make_local(Main *bmain, Library *lib, bool untagged_only)
1755 {
1756         ListBase *lbarray[MAX_LIBARRAY];
1757         ID *id, *idn;
1758         int a;
1759
1760         a = set_listbasepointers(bmain, lbarray);
1761         while (a--) {
1762                 id = lbarray[a]->first;
1763                 
1764                 while (id) {
1765                         id->newid = NULL;
1766                         idn = id->next;      /* id is possibly being inserted again */
1767                         
1768                         /* The check on the second line (LIB_PRE_EXISTING) is done so its
1769                          * possible to tag data you don't want to be made local, used for
1770                          * appending data, so any libdata already linked wont become local
1771                          * (very nasty to discover all your links are lost after appending)  
1772                          * */
1773                         if (id->flag & (LIB_EXTERN | LIB_INDIRECT | LIB_NEW) &&
1774                             ((untagged_only == false) || !(id->flag & LIB_PRE_EXISTING)))
1775                         {
1776                                 if (lib == NULL || id->lib == lib) {
1777                                         if (id->lib) {
1778                                                 /* for Make Local > All we should be calling id_make_local,
1779                                                  * but doing that breaks append (see #36003 and #36006), we
1780                                                  * we should make it work with all datablocks and id.us==0 */
1781                                                 id_clear_lib_data(bmain, id); /* sets 'id->flag' */
1782
1783                                                 /* why sort alphabetically here but not in
1784                                                  * id_clear_lib_data() ? - campbell */
1785                                                 id_sort_by_name(lbarray[a], id);
1786                                         }
1787                                         else {
1788                                                 id->flag &= ~(LIB_EXTERN | LIB_INDIRECT | LIB_NEW);
1789                                         }
1790                                 }
1791                         }
1792                         id = idn;
1793                 }
1794         }
1795
1796         a = set_listbasepointers(bmain, lbarray);
1797         while (a--) {
1798                 for (id = lbarray[a]->first; id; id = id->next)
1799                         lib_indirect_test_id(id, lib);
1800         }
1801 }
1802
1803
1804 void test_idbutton(char *name)
1805 {
1806         /* called from buttons: when name already exists: call new_id */
1807         ListBase *lb;
1808         ID *idtest;
1809         
1810
1811         lb = which_libbase(G.main, GS(name));
1812         if (lb == NULL) return;
1813         
1814         /* search for id */
1815         idtest = BLI_findstring(lb, name + 2, offsetof(ID, name) + 2);
1816
1817         if (idtest && !new_id(lb, idtest, name + 2)) {
1818                 id_sort_by_name(lb, idtest);
1819         }
1820 }
1821
1822 /**
1823  * Sets the name of a block to name, suitably adjusted for uniqueness.
1824  */
1825 void rename_id(ID *id, const char *name)
1826 {
1827         ListBase *lb;
1828
1829         BLI_strncpy(id->name + 2, name, sizeof(id->name) - 2);
1830         lb = which_libbase(G.main, GS(id->name));
1831         
1832         new_id(lb, id, name);
1833 }
1834
1835 /**
1836  * Returns in name the name of the block, with a 3-character prefix prepended
1837  * indicating whether it comes from a library, has a fake user, or no users.
1838  */
1839 void name_uiprefix_id(char *name, const ID *id)
1840 {
1841         name[0] = id->lib ? (ID_MISSING(id) ? 'M' : 'L') : ' ';
1842         name[1] = (id->flag & LIB_FAKEUSER) ? 'F' : ((id->us == 0) ? '0' : ' ');
1843         name[2] = ' ';
1844
1845         strcpy(name + 3, id->name + 2);
1846 }
1847
1848 void BKE_library_filepath_set(Library *lib, const char *filepath)
1849 {
1850         /* in some cases this is used to update the absolute path from the
1851          * relative */
1852         if (lib->name != filepath) {
1853                 BLI_strncpy(lib->name, filepath, sizeof(lib->name));
1854         }
1855
1856         BLI_strncpy(lib->filepath, filepath, sizeof(lib->filepath));
1857
1858         /* not essential but set filepath is an absolute copy of value which
1859          * is more useful if its kept in sync */
1860         if (BLI_path_is_rel(lib->filepath)) {
1861                 /* note that the file may be unsaved, in this case, setting the
1862                  * filepath on an indirectly linked path is not allowed from the
1863                  * outliner, and its not really supported but allow from here for now
1864                  * since making local could cause this to be directly linked - campbell
1865                  */
1866                 const char *basepath = lib->parent ? lib->parent->filepath : G.main->name;
1867                 BLI_path_abs(lib->filepath, basepath);
1868         }
1869 }