SVN maintenance.
[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
64 static PyMethodDef bpy_lib_methods[] = {
65         {"__enter__", (PyCFunction)bpy_lib_enter, METH_NOARGS},
66         {"__exit__", (PyCFunction)bpy_lib_exit, METH_VARARGS},
67         {NULL}           /* sentinel */
68 };
69
70 static void bpy_lib_dealloc(BPy_Library *self)
71 {
72         Py_XDECREF(self->dict);
73         Py_TYPE(self)->tp_free(self);
74 }
75
76
77 PyTypeObject bpy_lib_Type = {
78         PyVarObject_HEAD_INIT(NULL, 0)
79         "bpy_lib",              /* tp_name */
80         sizeof(BPy_Library),                    /* tp_basicsize */
81         0,                                                      /* tp_itemsize */
82         /* methods */
83         (destructor)bpy_lib_dealloc,/* tp_dealloc */
84         NULL,                       /* printfunc tp_print; */
85         NULL,                                           /* getattrfunc tp_getattr; */
86         NULL,                       /* setattrfunc tp_setattr; */
87         NULL,                                           /* tp_compare */ /* DEPRECATED in python 3.0! */
88         NULL,                                           /* tp_repr */
89
90         /* Method suites for standard classes */
91
92         NULL,                                           /* PyNumberMethods *tp_as_number; */
93         NULL,                                           /* PySequenceMethods *tp_as_sequence; */
94         NULL,                                           /* PyMappingMethods *tp_as_mapping; */
95
96         /* More standard operations (here for binary compatibility) */
97
98         NULL,                                           /* hashfunc tp_hash; */
99         NULL,                       /* ternaryfunc tp_call; */
100         NULL,                       /* reprfunc tp_str; */
101
102         /* will only use these if this is a subtype of a py class */
103         PyObject_GenericGetAttr,        /* getattrofunc tp_getattro; */
104         NULL,                                           /* setattrofunc tp_setattro; */
105
106         /* Functions to access object as input/output buffer */
107         NULL,                       /* PyBufferProcs *tp_as_buffer; */
108
109   /*** Flags to define presence of optional/expanded features ***/
110         Py_TPFLAGS_DEFAULT,         /* long tp_flags; */
111
112         NULL,                                           /*  char *tp_doc;  Documentation string */
113   /*** Assigned meaning in release 2.0 ***/
114         /* call function for all accessible objects */
115         NULL,                       /* traverseproc tp_traverse; */
116
117         /* delete references to contained objects */
118         NULL,                       /* inquiry tp_clear; */
119
120   /***  Assigned meaning in release 2.1 ***/
121   /*** rich comparisons ***/
122         NULL, /* subclassed */          /* richcmpfunc tp_richcompare; */
123
124   /***  weak reference enabler ***/
125         0,
126   /*** Added in release 2.2 ***/
127         /*   Iterators */
128         NULL,                                           /* getiterfunc tp_iter; */
129         NULL,                       /* iternextfunc tp_iternext; */
130
131   /*** Attribute descriptor and subclassing stuff ***/
132         bpy_lib_methods,                        /* struct PyMethodDef *tp_methods; */
133         NULL,                       /* struct PyMemberDef *tp_members; */
134         NULL,                                   /* struct PyGetSetDef *tp_getset; */
135         NULL,                       /* struct _typeobject *tp_base; */
136         NULL,                       /* PyObject *tp_dict; */
137         NULL,                       /* descrgetfunc tp_descr_get; */
138         NULL,                       /* descrsetfunc tp_descr_set; */
139         offsetof(BPy_Library, dict),/* long tp_dictoffset; */
140         NULL,                       /* initproc tp_init; */
141         NULL,                       /* allocfunc tp_alloc; */
142         NULL,                                           /* newfunc tp_new; */
143         /*  Low-level free-memory routine */
144         NULL,                       /* freefunc tp_free;  */
145         /* For PyObject_IS_GC */
146         NULL,                       /* inquiry tp_is_gc;  */
147         NULL,                                           /* PyObject *tp_bases; */
148         /* method resolution order */
149         NULL,                       /* PyObject *tp_mro;  */
150         NULL,                       /* PyObject *tp_cache; */
151         NULL,                       /* PyObject *tp_subclasses; */
152         NULL,                       /* PyObject *tp_weaklist; */
153         NULL
154 };
155
156
157 static PyObject *bpy_lib_load(PyObject *UNUSED(self), PyObject *args, PyObject *kwds)
158 {
159         static const char *kwlist[] = {"filepath", "link", "relative", NULL};
160         BPy_Library *ret;
161         const char* filename = NULL;
162         int is_rel= 0, is_link= 0;
163
164         if(!PyArg_ParseTupleAndKeywords(args, kwds, "s|ii:load", (char **)kwlist, &filename, &is_link, &is_rel))
165                 return NULL;
166
167         ret= PyObject_New(BPy_Library, &bpy_lib_Type);
168
169         BLI_strncpy(ret->relpath, filename, sizeof(BPy_Library));
170         BLI_strncpy(ret->abspath, filename, sizeof(BPy_Library));
171         BLI_path_abs(ret->abspath, G.main->name);
172
173         ret->blo_handle= NULL;
174         ret->flag=      (is_link ? FILE_LINK : 0) |
175                                 (is_rel ? FILE_RELPATH : 0);
176
177         ret->dict= PyDict_New();
178
179         return (PyObject *)ret;
180 }
181
182 static PyObject *_bpy_names(BPy_Library *self, int blocktype)
183 {
184         PyObject *list;
185         LinkNode *l, *names;
186         int totnames;
187
188         names= BLO_blendhandle_get_datablock_names(self->blo_handle, blocktype, &totnames);
189
190         if(names) {
191                 int counter = 0;
192                 list = PyList_New(totnames);
193                 for(l = names; l; l = l->next) {
194                         PyList_SET_ITEM(list, counter, PyUnicode_FromString((char * )l->link));
195                         counter++;
196                 }
197                 BLI_linklist_free(names, free); /* free linklist *and* each node's data */
198         }
199         else {
200                 list= PyList_New(0);
201         }
202
203         return list;
204 }
205
206 static PyObject *bpy_lib_enter(BPy_Library *self, PyObject *UNUSED(args))
207 {
208         PyObject *ret;
209         BPy_Library *self_from;
210         PyObject *from_dict= PyDict_New();
211         ReportList reports;
212
213         BKE_reports_init(&reports, RPT_STORE);
214
215         self->blo_handle= BLO_blendhandle_from_file(self->abspath, &reports);
216
217         if(self->blo_handle == NULL) {
218                 if(BPy_reports_to_error(&reports, PyExc_IOError, TRUE) != -1) {
219                         PyErr_Format(PyExc_IOError, "load: %s failed to open blend file", self->abspath);
220                 }
221                 return NULL;
222         }
223         else {
224                 int i= 0, code;
225                 while((code= BKE_idcode_iter_step(&i))) {
226                         if(BKE_idcode_is_linkable(code)) {
227                                 const char *name_plural= BKE_idcode_to_name_plural(code);
228                                 PyObject *str= PyUnicode_FromString(name_plural);
229                                 PyDict_SetItem(self->dict, str, PyList_New(0));
230                                 PyDict_SetItem(from_dict, str, _bpy_names(self, code));
231                                 Py_DECREF(str);
232                         }
233                 }
234         }
235
236         /* create a dummy */
237         self_from= PyObject_New(BPy_Library, &bpy_lib_Type);
238         BLI_strncpy(self_from->relpath, self->relpath, sizeof(BPy_Library));
239         BLI_strncpy(self_from->abspath, self->abspath, sizeof(BPy_Library));
240
241         self_from->blo_handle= NULL;
242         self_from->flag= 0;
243         self_from->dict= from_dict; /* owns the dict */
244
245         /* return pair */
246         ret= PyTuple_New(2);
247
248         PyTuple_SET_ITEM(ret, 0, (PyObject *)self_from);
249
250         PyTuple_SET_ITEM(ret, 1, (PyObject *)self);
251         Py_INCREF(self);
252
253         BKE_reports_clear(&reports);
254
255         return ret;
256 }
257
258 static PyObject *bpy_lib_exit(BPy_Library *self, PyObject *UNUSED(args))
259 {
260         Main *mainl= NULL;
261
262         flag_all_listbases_ids(LIB_PRE_EXISTING, 1);
263
264         /* here appending/linking starts */
265         mainl = BLO_library_append_begin(BPy_GetContext(), &(self->blo_handle), self->relpath);
266
267         {
268                 int i= 0, code;
269                 while((code= BKE_idcode_iter_step(&i))) {
270                         if(BKE_idcode_is_linkable(code)) {
271                                 const char *name_plural= BKE_idcode_to_name_plural(code);
272                                 PyObject *ls= PyDict_GetItemString(self->dict, name_plural);
273                                 // printf("lib: %s\n", name_plural);
274                                 if(ls && PyList_Check(ls)) {
275                                         /* loop */
276                                         Py_ssize_t size= PyList_GET_SIZE(ls);
277                                         Py_ssize_t i;
278                                         PyObject *item;
279                                         const char *item_str;
280
281                                         for(i= 0; i < size; i++) {
282                                                 item= PyList_GET_ITEM(ls, i);
283                                                 item_str= _PyUnicode_AsString(item);
284
285                                                 // printf("  %s\n", item_str);
286
287                                                 if(item_str) {
288                                                         BLO_library_append_named_part(NULL, mainl, &(self->blo_handle), item_str, code, self->flag);
289                                                 }
290                                                 else {
291                                                         /* XXX, could complain about this */
292                                                         PyErr_Clear();
293                                                 }
294                                         }
295                                 }
296                         }
297                 }
298         }
299
300         BLO_library_append_end(NULL, mainl, &(self->blo_handle), 0, self->flag);
301         BLO_blendhandle_close(self->blo_handle);
302
303         {       /* copied from wm_operator.c */
304                 /* mark all library linked objects to be updated */
305                 recalc_all_library_objects(G.main);
306
307                 /* append, rather than linking */
308                 if((self->flag & FILE_LINK)==0) {
309                         Library *lib= BLI_findstring(&G.main->library, self->abspath, offsetof(Library, name));
310                         if(lib) all_local(lib, 1);
311                         else    BLI_assert(!"cant find name of just added library!");
312                 }
313         }
314
315         flag_all_listbases_ids(LIB_PRE_EXISTING, 0);
316
317         self->blo_handle= NULL;
318
319         Py_RETURN_NONE;
320 }
321
322 int bpy_lib_init(PyObject *mod_par)
323 {
324         static PyMethodDef load_meth= {"load", (PyCFunction)bpy_lib_load, METH_STATIC|METH_VARARGS|METH_KEYWORDS};
325         PyModule_AddObject(mod_par, "_library_load", PyCFunction_New(&load_meth, NULL));
326
327         if(PyType_Ready(&bpy_lib_Type) < 0)
328                 return -1;
329
330         return 0;
331 }