svn merge -r36583:36603 https://svn.blender.org/svnroot/bf-blender/trunk/blender
[blender.git] / source / blender / python / intern / bpy_library.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * Contributor(s): Campbell Barton
21  *
22  * ***** END GPL LICENSE BLOCK *****
23  */
24
25 /** \file blender/python/intern/bpy_library.c
26  *  \ingroup pythonintern
27  */
28
29 #include <Python.h>
30 #include <stddef.h>
31
32 #include "BLO_readfile.h"
33
34 #include "BKE_global.h"
35 #include "BKE_main.h"
36 #include "BKE_library.h"
37 #include "BKE_idcode.h"
38 #include "BKE_report.h"
39
40 #include "BLI_utildefines.h"
41 #include "BLI_string.h"
42 #include "BLI_linklist.h"
43 #include "BLI_path_util.h"
44 #include "BLI_listbase.h"
45
46 #include "DNA_space_types.h" /* FILE_LINK, FILE_RELPATH */
47
48 #include "bpy_util.h"
49
50 typedef struct {
51         PyObject_HEAD /* required python macro   */
52         /* collection iterator spesific parts */
53         char relpath[FILE_MAX];
54         char abspath[FILE_MAX]; /* absolute path */
55         BlendHandle *blo_handle;
56         int flag;
57         PyObject *dict;
58 } BPy_Library;
59
60 static PyObject *bpy_lib_load(PyObject *self, PyObject *args, PyObject *kwds);
61 static PyObject *bpy_lib_enter(BPy_Library *self, PyObject *args);
62 static PyObject *bpy_lib_exit(BPy_Library *self, PyObject *args);
63 static PyObject *bpy_lib_dir(BPy_Library *self);
64
65 static PyMethodDef bpy_lib_methods[]= {
66         {"__enter__", (PyCFunction)bpy_lib_enter, METH_NOARGS},
67         {"__exit__", (PyCFunction)bpy_lib_exit, METH_VARARGS},
68         {"__dir__", (PyCFunction)bpy_lib_dir, METH_NOARGS},
69         {NULL}           /* sentinel */
70 };
71
72 static void bpy_lib_dealloc(BPy_Library *self)
73 {
74         Py_XDECREF(self->dict);
75         Py_TYPE(self)->tp_free(self);
76 }
77
78
79 static PyTypeObject bpy_lib_Type= {
80         PyVarObject_HEAD_INIT(NULL, 0)
81         "bpy_lib",              /* tp_name */
82         sizeof(BPy_Library),                    /* tp_basicsize */
83         0,                                                      /* tp_itemsize */
84         /* methods */
85         (destructor)bpy_lib_dealloc,/* tp_dealloc */
86         NULL,                       /* printfunc tp_print; */
87         NULL,                                           /* getattrfunc tp_getattr; */
88         NULL,                       /* setattrfunc tp_setattr; */
89         NULL,                                           /* tp_compare */ /* DEPRECATED in python 3.0! */
90         NULL,                                           /* tp_repr */
91
92         /* Method suites for standard classes */
93
94         NULL,                                           /* PyNumberMethods *tp_as_number; */
95         NULL,                                           /* PySequenceMethods *tp_as_sequence; */
96         NULL,                                           /* PyMappingMethods *tp_as_mapping; */
97
98         /* More standard operations (here for binary compatibility) */
99
100         NULL,                                           /* hashfunc tp_hash; */
101         NULL,                       /* ternaryfunc tp_call; */
102         NULL,                       /* reprfunc tp_str; */
103
104         /* will only use these if this is a subtype of a py class */
105         NULL /*PyObject_GenericGetAttr is assigned later */,    /* getattrofunc tp_getattro; */
106         NULL,                                           /* setattrofunc tp_setattro; */
107
108         /* Functions to access object as input/output buffer */
109         NULL,                       /* PyBufferProcs *tp_as_buffer; */
110
111   /*** Flags to define presence of optional/expanded features ***/
112         Py_TPFLAGS_DEFAULT,         /* long tp_flags; */
113
114         NULL,                                           /*  char *tp_doc;  Documentation string */
115   /*** Assigned meaning in release 2.0 ***/
116         /* call function for all accessible objects */
117         NULL,                       /* traverseproc tp_traverse; */
118
119         /* delete references to contained objects */
120         NULL,                       /* inquiry tp_clear; */
121
122   /***  Assigned meaning in release 2.1 ***/
123   /*** rich comparisons ***/
124         NULL, /* subclassed */          /* richcmpfunc tp_richcompare; */
125
126   /***  weak reference enabler ***/
127         0,
128   /*** Added in release 2.2 ***/
129         /*   Iterators */
130         NULL,                                           /* getiterfunc tp_iter; */
131         NULL,                       /* iternextfunc tp_iternext; */
132
133   /*** Attribute descriptor and subclassing stuff ***/
134         bpy_lib_methods,                        /* struct PyMethodDef *tp_methods; */
135         NULL,                       /* struct PyMemberDef *tp_members; */
136         NULL,                                   /* struct PyGetSetDef *tp_getset; */
137         NULL,                       /* struct _typeobject *tp_base; */
138         NULL,                       /* PyObject *tp_dict; */
139         NULL,                       /* descrgetfunc tp_descr_get; */
140         NULL,                       /* descrsetfunc tp_descr_set; */
141         offsetof(BPy_Library, dict),/* long tp_dictoffset; */
142         NULL,                       /* initproc tp_init; */
143         NULL,                       /* allocfunc tp_alloc; */
144         NULL,                                           /* newfunc tp_new; */
145         /*  Low-level free-memory routine */
146         NULL,                       /* freefunc tp_free;  */
147         /* For PyObject_IS_GC */
148         NULL,                       /* inquiry tp_is_gc;  */
149         NULL,                                           /* PyObject *tp_bases; */
150         /* method resolution order */
151         NULL,                       /* PyObject *tp_mro;  */
152         NULL,                       /* PyObject *tp_cache; */
153         NULL,                       /* PyObject *tp_subclasses; */
154         NULL,                       /* PyObject *tp_weaklist; */
155         NULL
156 };
157
158 static char bpy_lib_load_doc[] =
159 ".. method:: load(filepath, link=False, relative=False)\n"
160 "\n"
161 "   Returns a context manager which exposes 2 library objects on entering.\n"
162 "   Each object has attributes matching bpy.data which are lists of strings to be linked.\n"
163 "\n"
164 "   :arg filepath: The path to a blend file.\n"
165 "   :type filepath: string\n"
166 "   :arg link: When False reference to the original file is lost.\n"
167 "   :type link: bool\n"
168 "   :arg relative: When True the path is stored relative to the open blend file.\n"
169 "   :type relative: bool\n"
170 ;
171 static PyObject *bpy_lib_load(PyObject *UNUSED(self), PyObject *args, PyObject *kwds)
172 {
173         static const char *kwlist[]= {"filepath", "link", "relative", NULL};
174         BPy_Library *ret;
175         const char* filename= NULL;
176         int is_rel= 0, is_link= 0;
177
178         if(!PyArg_ParseTupleAndKeywords(args, kwds, "s|ii:load", (char **)kwlist, &filename, &is_link, &is_rel))
179                 return NULL;
180
181         ret= PyObject_New(BPy_Library, &bpy_lib_Type);
182
183         BLI_strncpy(ret->relpath, filename, sizeof(ret->relpath));
184         BLI_strncpy(ret->abspath, filename, sizeof(ret->abspath));
185         BLI_path_abs(ret->abspath, G.main->name);
186
187         ret->blo_handle= NULL;
188         ret->flag=      (is_link ? FILE_LINK : 0) |
189                                 (is_rel ? FILE_RELPATH : 0);
190
191         ret->dict= PyDict_New();
192
193         return (PyObject *)ret;
194 }
195
196 static PyObject *_bpy_names(BPy_Library *self, int blocktype)
197 {
198         PyObject *list;
199         LinkNode *l, *names;
200         int totnames;
201
202         names= BLO_blendhandle_get_datablock_names(self->blo_handle, blocktype, &totnames);
203
204         if(names) {
205                 int counter= 0;
206                 list= PyList_New(totnames);
207                 for(l= names; l; l= l->next) {
208                         PyList_SET_ITEM(list, counter, PyUnicode_FromString((char * )l->link));
209                         counter++;
210                 }
211                 BLI_linklist_free(names, free); /* free linklist *and* each node's data */
212         }
213         else {
214                 list= PyList_New(0);
215         }
216
217         return list;
218 }
219
220 static PyObject *bpy_lib_enter(BPy_Library *self, PyObject *UNUSED(args))
221 {
222         PyObject *ret;
223         BPy_Library *self_from;
224         PyObject *from_dict= PyDict_New();
225         ReportList reports;
226
227         BKE_reports_init(&reports, RPT_STORE);
228
229         self->blo_handle= BLO_blendhandle_from_file(self->abspath, &reports);
230
231         if(self->blo_handle == NULL) {
232                 if(BPy_reports_to_error(&reports, PyExc_IOError, TRUE) != -1) {
233                         PyErr_Format(PyExc_IOError,
234                                      "load: %s failed to open blend file",
235                                      self->abspath);
236                 }
237                 return NULL;
238         }
239         else {
240                 int i= 0, code;
241                 while((code= BKE_idcode_iter_step(&i))) {
242                         if(BKE_idcode_is_linkable(code)) {
243                                 const char *name_plural= BKE_idcode_to_name_plural(code);
244                                 PyObject *str= PyUnicode_FromString(name_plural);
245                                 PyDict_SetItem(self->dict, str, PyList_New(0));
246                                 PyDict_SetItem(from_dict, str, _bpy_names(self, code));
247                                 Py_DECREF(str);
248                         }
249                 }
250         }
251
252         /* create a dummy */
253         self_from= PyObject_New(BPy_Library, &bpy_lib_Type);
254         BLI_strncpy(self_from->relpath, self->relpath, sizeof(BPy_Library));
255         BLI_strncpy(self_from->abspath, self->abspath, sizeof(BPy_Library));
256
257         self_from->blo_handle= NULL;
258         self_from->flag= 0;
259         self_from->dict= from_dict; /* owns the dict */
260
261         /* return pair */
262         ret= PyTuple_New(2);
263
264         PyTuple_SET_ITEM(ret, 0, (PyObject *)self_from);
265
266         PyTuple_SET_ITEM(ret, 1, (PyObject *)self);
267         Py_INCREF(self);
268
269         BKE_reports_clear(&reports);
270
271         return ret;
272 }
273
274 static PyObject *bpy_lib_exit(BPy_Library *self, PyObject *UNUSED(args))
275 {
276         Main *mainl= NULL;
277         int err= 0;
278
279         flag_all_listbases_ids(LIB_PRE_EXISTING, 1);
280
281         /* here appending/linking starts */
282         mainl= BLO_library_append_begin(BPy_GetContext(), &(self->blo_handle), self->relpath);
283
284         {
285                 int i= 0, code;
286                 while((code= BKE_idcode_iter_step(&i))) {
287                         if(BKE_idcode_is_linkable(code)) {
288                                 const char *name_plural= BKE_idcode_to_name_plural(code);
289                                 PyObject *ls= PyDict_GetItemString(self->dict, name_plural);
290                                 // printf("lib: %s\n", name_plural);
291                                 if(ls && PyList_Check(ls)) {
292                                         /* loop */
293                                         Py_ssize_t size= PyList_GET_SIZE(ls);
294                                         Py_ssize_t i;
295                                         PyObject *item;
296                                         const char *item_str;
297
298                                         for(i= 0; i < size; i++) {
299                                                 item= PyList_GET_ITEM(ls, i);
300                                                 item_str= _PyUnicode_AsString(item);
301
302                                                 // printf("  %s\n", item_str);
303
304                                                 if(item_str) {
305                                                         if(!BLO_library_append_named_part(NULL, mainl, &(self->blo_handle), item_str, code, self->flag)) {
306                                                                 PyErr_Format(PyExc_KeyError,
307                                                                              "load: %s does not contain %s[\"%s\"]",
308                                                                              self->abspath, name_plural, item_str);
309                                                                 err= -1;
310                                                                 break;
311                                                         }
312                                                 }
313                                                 else {
314                                                         /* XXX, could complain about this */
315                                                         PyErr_Clear();
316                                                 }
317                                         }
318                                 }
319                         }
320                 }
321         }
322
323         if(err == -1) {
324                 /* exception raised above, XXX, this leaks some memory */
325                 BLO_blendhandle_close(self->blo_handle);
326                 self->blo_handle= NULL;
327                 flag_all_listbases_ids(LIB_PRE_EXISTING, 0);
328                 return NULL;
329         }
330         else {
331                 BLO_library_append_end(NULL, mainl, &(self->blo_handle), 0, self->flag);
332                 BLO_blendhandle_close(self->blo_handle);
333                 self->blo_handle= NULL;
334
335                 {       /* copied from wm_operator.c */
336                         /* mark all library linked objects to be updated */
337                         recalc_all_library_objects(G.main);
338
339                         /* append, rather than linking */
340                         if((self->flag & FILE_LINK)==0) {
341                                 Library *lib= BLI_findstring(&G.main->library, self->abspath, offsetof(Library, name));
342                                 if(lib) all_local(lib, 1);
343                                 else    BLI_assert(!"cant find name of just added library!");
344                         }
345                 }
346
347                 flag_all_listbases_ids(LIB_PRE_EXISTING, 0);
348
349                 Py_RETURN_NONE;
350         }
351 }
352
353 static PyObject *bpy_lib_dir(BPy_Library *self)
354 {
355         return PyDict_Keys(self->dict);
356 }
357
358
359 int bpy_lib_init(PyObject *mod_par)
360 {
361         static PyMethodDef load_meth= {"load", (PyCFunction)bpy_lib_load, METH_STATIC|METH_VARARGS|METH_KEYWORDS, bpy_lib_load_doc};
362         PyModule_AddObject(mod_par, "_library_load", PyCFunction_New(&load_meth, NULL));
363
364         /* some compilers dont like accessing this directly, delay assignment */
365         bpy_lib_Type.tp_getattro= PyObject_GenericGetAttr;
366
367         if(PyType_Ready(&bpy_lib_Type) < 0)
368                 return -1;
369
370         return 0;
371 }