faee8f493c70288c850a8755ffa894dd67ed56e5
[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 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         PyObject_GenericGetAttr,        /* 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
159 static PyObject *bpy_lib_load(PyObject *UNUSED(self), PyObject *args, PyObject *kwds)
160 {
161         static const char *kwlist[] = {"filepath", "link", "relative", NULL};
162         BPy_Library *ret;
163         const char* filename = NULL;
164         int is_rel= 0, is_link= 0;
165
166         if(!PyArg_ParseTupleAndKeywords(args, kwds, "s|ii:load", (char **)kwlist, &filename, &is_link, &is_rel))
167                 return NULL;
168
169         ret= PyObject_New(BPy_Library, &bpy_lib_Type);
170
171         BLI_strncpy(ret->relpath, filename, sizeof(BPy_Library));
172         BLI_strncpy(ret->abspath, filename, sizeof(BPy_Library));
173         BLI_path_abs(ret->abspath, G.main->name);
174
175         ret->blo_handle= NULL;
176         ret->flag=      (is_link ? FILE_LINK : 0) |
177                                 (is_rel ? FILE_RELPATH : 0);
178
179         ret->dict= PyDict_New();
180
181         return (PyObject *)ret;
182 }
183
184 static PyObject *_bpy_names(BPy_Library *self, int blocktype)
185 {
186         PyObject *list;
187         LinkNode *l, *names;
188         int totnames;
189
190         names= BLO_blendhandle_get_datablock_names(self->blo_handle, blocktype, &totnames);
191
192         if(names) {
193                 int counter = 0;
194                 list = PyList_New(totnames);
195                 for(l = names; l; l = l->next) {
196                         PyList_SET_ITEM(list, counter, PyUnicode_FromString((char * )l->link));
197                         counter++;
198                 }
199                 BLI_linklist_free(names, free); /* free linklist *and* each node's data */
200         }
201         else {
202                 list= PyList_New(0);
203         }
204
205         return list;
206 }
207
208 static PyObject *bpy_lib_enter(BPy_Library *self, PyObject *UNUSED(args))
209 {
210         PyObject *ret;
211         BPy_Library *self_from;
212         PyObject *from_dict= PyDict_New();
213         ReportList reports;
214
215         BKE_reports_init(&reports, RPT_STORE);
216
217         self->blo_handle= BLO_blendhandle_from_file(self->abspath, &reports);
218
219         if(self->blo_handle == NULL) {
220                 if(BPy_reports_to_error(&reports, PyExc_IOError, TRUE) != -1) {
221                         PyErr_Format(PyExc_IOError, "load: %s failed to open blend file", self->abspath);
222                 }
223                 return NULL;
224         }
225         else {
226                 int i= 0, code;
227                 while((code= BKE_idcode_iter_step(&i))) {
228                         if(BKE_idcode_is_linkable(code)) {
229                                 const char *name_plural= BKE_idcode_to_name_plural(code);
230                                 PyObject *str= PyUnicode_FromString(name_plural);
231                                 PyDict_SetItem(self->dict, str, PyList_New(0));
232                                 PyDict_SetItem(from_dict, str, _bpy_names(self, code));
233                                 Py_DECREF(str);
234                         }
235                 }
236         }
237
238         /* create a dummy */
239         self_from= PyObject_New(BPy_Library, &bpy_lib_Type);
240         BLI_strncpy(self_from->relpath, self->relpath, sizeof(BPy_Library));
241         BLI_strncpy(self_from->abspath, self->abspath, sizeof(BPy_Library));
242
243         self_from->blo_handle= NULL;
244         self_from->flag= 0;
245         self_from->dict= from_dict; /* owns the dict */
246
247         /* return pair */
248         ret= PyTuple_New(2);
249
250         PyTuple_SET_ITEM(ret, 0, (PyObject *)self_from);
251
252         PyTuple_SET_ITEM(ret, 1, (PyObject *)self);
253         Py_INCREF(self);
254
255         BKE_reports_clear(&reports);
256
257         return ret;
258 }
259
260 static PyObject *bpy_lib_exit(BPy_Library *self, PyObject *UNUSED(args))
261 {
262         Main *mainl= NULL;
263         int err= 0;
264
265         flag_all_listbases_ids(LIB_PRE_EXISTING, 1);
266
267         /* here appending/linking starts */
268         mainl = BLO_library_append_begin(BPy_GetContext(), &(self->blo_handle), self->relpath);
269
270         {
271                 int i= 0, code;
272                 while((code= BKE_idcode_iter_step(&i))) {
273                         if(BKE_idcode_is_linkable(code)) {
274                                 const char *name_plural= BKE_idcode_to_name_plural(code);
275                                 PyObject *ls= PyDict_GetItemString(self->dict, name_plural);
276                                 // printf("lib: %s\n", name_plural);
277                                 if(ls && PyList_Check(ls)) {
278                                         /* loop */
279                                         Py_ssize_t size= PyList_GET_SIZE(ls);
280                                         Py_ssize_t i;
281                                         PyObject *item;
282                                         const char *item_str;
283
284                                         for(i= 0; i < size; i++) {
285                                                 item= PyList_GET_ITEM(ls, i);
286                                                 item_str= _PyUnicode_AsString(item);
287
288                                                 // printf("  %s\n", item_str);
289
290                                                 if(item_str) {
291                                                         if(!BLO_library_append_named_part(NULL, mainl, &(self->blo_handle), item_str, code, self->flag)) {
292                                                                 PyErr_Format(PyExc_KeyError, "load: %s does not contain %s[\"%s\"]", self->abspath, name_plural, item_str);
293                                                                 err= -1;
294                                                                 break;
295                                                         }
296                                                 }
297                                                 else {
298                                                         /* XXX, could complain about this */
299                                                         PyErr_Clear();
300                                                 }
301                                         }
302                                 }
303                         }
304                 }
305         }
306
307         if(err == -1) {
308                 /* exception raised above, XXX, this leaks some memory */
309                 BLO_blendhandle_close(self->blo_handle);
310                 self->blo_handle= NULL;
311                 flag_all_listbases_ids(LIB_PRE_EXISTING, 0);
312                 return NULL;
313         }
314         else {
315                 BLO_library_append_end(NULL, mainl, &(self->blo_handle), 0, self->flag);
316                 BLO_blendhandle_close(self->blo_handle);
317                 self->blo_handle= NULL;
318
319                 {       /* copied from wm_operator.c */
320                         /* mark all library linked objects to be updated */
321                         recalc_all_library_objects(G.main);
322
323                         /* append, rather than linking */
324                         if((self->flag & FILE_LINK)==0) {
325                                 Library *lib= BLI_findstring(&G.main->library, self->abspath, offsetof(Library, name));
326                                 if(lib) all_local(lib, 1);
327                                 else    BLI_assert(!"cant find name of just added library!");
328                         }
329                 }
330
331                 flag_all_listbases_ids(LIB_PRE_EXISTING, 0);
332
333                 Py_RETURN_NONE;
334         }
335 }
336
337 static PyObject *bpy_lib_dir(BPy_Library *self)
338 {
339         return PyDict_Keys(self->dict);
340 }
341
342
343 int bpy_lib_init(PyObject *mod_par)
344 {
345         static PyMethodDef load_meth= {"load", (PyCFunction)bpy_lib_load, METH_STATIC|METH_VARARGS|METH_KEYWORDS};
346         PyModule_AddObject(mod_par, "_library_load", PyCFunction_New(&load_meth, NULL));
347
348         if(PyType_Ready(&bpy_lib_Type) < 0)
349                 return -1;
350
351         return 0;
352 }