change BLO_library_append_begin to take a main argument rather then a context, means...
[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 /* nifty feature. swap out strings for RNA data */
30 #define USE_RNA_DATABLOCKS
31
32 #include <Python.h>
33 #include <stddef.h>
34
35 #include "BLO_readfile.h"
36
37 #include "BKE_global.h"
38 #include "BKE_main.h"
39 #include "BKE_library.h"
40 #include "BKE_idcode.h"
41 #include "BKE_report.h"
42 #include "BKE_context.h"
43
44 #include "BLI_utildefines.h"
45 #include "BLI_string.h"
46 #include "BLI_linklist.h"
47 #include "BLI_path_util.h"
48 #include "BLI_listbase.h"
49
50 #include "DNA_space_types.h" /* FILE_LINK, FILE_RELPATH */
51
52 #include "bpy_util.h"
53
54 #ifdef USE_RNA_DATABLOCKS
55 #  include "bpy_rna.h"
56 #  include "RNA_access.h"
57 #endif
58
59 typedef struct {
60         PyObject_HEAD /* required python macro   */
61         /* collection iterator spesific parts */
62         char relpath[FILE_MAX];
63         char abspath[FILE_MAX]; /* absolute path */
64         BlendHandle *blo_handle;
65         int flag;
66         PyObject *dict;
67 } BPy_Library;
68
69 static PyObject *bpy_lib_load(PyObject *self, PyObject *args, PyObject *kwds);
70 static PyObject *bpy_lib_enter(BPy_Library *self, PyObject *args);
71 static PyObject *bpy_lib_exit(BPy_Library *self, PyObject *args);
72 static PyObject *bpy_lib_dir(BPy_Library *self);
73
74 static PyMethodDef bpy_lib_methods[]= {
75         {"__enter__", (PyCFunction)bpy_lib_enter, METH_NOARGS},
76         {"__exit__", (PyCFunction)bpy_lib_exit, METH_VARARGS},
77         {"__dir__", (PyCFunction)bpy_lib_dir, METH_NOARGS},
78         {NULL}           /* sentinel */
79 };
80
81 static void bpy_lib_dealloc(BPy_Library *self)
82 {
83         Py_XDECREF(self->dict);
84         Py_TYPE(self)->tp_free(self);
85 }
86
87
88 static PyTypeObject bpy_lib_Type= {
89         PyVarObject_HEAD_INIT(NULL, 0)
90         "bpy_lib",              /* tp_name */
91         sizeof(BPy_Library),                    /* tp_basicsize */
92         0,                                                      /* tp_itemsize */
93         /* methods */
94         (destructor)bpy_lib_dealloc,/* tp_dealloc */
95         NULL,                       /* printfunc tp_print; */
96         NULL,                                           /* getattrfunc tp_getattr; */
97         NULL,                       /* setattrfunc tp_setattr; */
98         NULL,                                           /* tp_compare */ /* DEPRECATED in python 3.0! */
99         NULL,                                           /* tp_repr */
100
101         /* Method suites for standard classes */
102
103         NULL,                                           /* PyNumberMethods *tp_as_number; */
104         NULL,                                           /* PySequenceMethods *tp_as_sequence; */
105         NULL,                                           /* PyMappingMethods *tp_as_mapping; */
106
107         /* More standard operations (here for binary compatibility) */
108
109         NULL,                                           /* hashfunc tp_hash; */
110         NULL,                       /* ternaryfunc tp_call; */
111         NULL,                       /* reprfunc tp_str; */
112
113         /* will only use these if this is a subtype of a py class */
114         NULL /*PyObject_GenericGetAttr is assigned later */,    /* getattrofunc tp_getattro; */
115         NULL,                                           /* setattrofunc tp_setattro; */
116
117         /* Functions to access object as input/output buffer */
118         NULL,                       /* PyBufferProcs *tp_as_buffer; */
119
120   /*** Flags to define presence of optional/expanded features ***/
121         Py_TPFLAGS_DEFAULT,         /* long tp_flags; */
122
123         NULL,                                           /*  char *tp_doc;  Documentation string */
124   /*** Assigned meaning in release 2.0 ***/
125         /* call function for all accessible objects */
126         NULL,                       /* traverseproc tp_traverse; */
127
128         /* delete references to contained objects */
129         NULL,                       /* inquiry tp_clear; */
130
131   /***  Assigned meaning in release 2.1 ***/
132   /*** rich comparisons ***/
133         NULL, /* subclassed */          /* richcmpfunc tp_richcompare; */
134
135   /***  weak reference enabler ***/
136         0,
137   /*** Added in release 2.2 ***/
138         /*   Iterators */
139         NULL,                                           /* getiterfunc tp_iter; */
140         NULL,                       /* iternextfunc tp_iternext; */
141
142   /*** Attribute descriptor and subclassing stuff ***/
143         bpy_lib_methods,                        /* struct PyMethodDef *tp_methods; */
144         NULL,                       /* struct PyMemberDef *tp_members; */
145         NULL,                                   /* struct PyGetSetDef *tp_getset; */
146         NULL,                       /* struct _typeobject *tp_base; */
147         NULL,                       /* PyObject *tp_dict; */
148         NULL,                       /* descrgetfunc tp_descr_get; */
149         NULL,                       /* descrsetfunc tp_descr_set; */
150         offsetof(BPy_Library, dict),/* long tp_dictoffset; */
151         NULL,                       /* initproc tp_init; */
152         NULL,                       /* allocfunc tp_alloc; */
153         NULL,                                           /* newfunc tp_new; */
154         /*  Low-level free-memory routine */
155         NULL,                       /* freefunc tp_free;  */
156         /* For PyObject_IS_GC */
157         NULL,                       /* inquiry tp_is_gc;  */
158         NULL,                                           /* PyObject *tp_bases; */
159         /* method resolution order */
160         NULL,                       /* PyObject *tp_mro;  */
161         NULL,                       /* PyObject *tp_cache; */
162         NULL,                       /* PyObject *tp_subclasses; */
163         NULL,                       /* PyObject *tp_weaklist; */
164         NULL
165 };
166
167 PyDoc_STRVAR(bpy_lib_load_doc,
168 ".. method:: load(filepath, link=False, relative=False)\n"
169 "\n"
170 "   Returns a context manager which exposes 2 library objects on entering.\n"
171 "   Each object has attributes matching bpy.data which are lists of strings to be linked.\n"
172 "\n"
173 "   :arg filepath: The path to a blend file.\n"
174 "   :type filepath: string\n"
175 "   :arg link: When False reference to the original file is lost.\n"
176 "   :type link: bool\n"
177 "   :arg relative: When True the path is stored relative to the open blend file.\n"
178 "   :type relative: bool\n"
179 );
180 static PyObject *bpy_lib_load(PyObject *UNUSED(self), PyObject *args, PyObject *kwds)
181 {
182         static const char *kwlist[]= {"filepath", "link", "relative", NULL};
183         BPy_Library *ret;
184         const char* filename= NULL;
185         int is_rel= 0, is_link= 0;
186
187         if(!PyArg_ParseTupleAndKeywords(args, kwds, "s|ii:load", (char **)kwlist, &filename, &is_link, &is_rel))
188                 return NULL;
189
190         ret= PyObject_New(BPy_Library, &bpy_lib_Type);
191
192         BLI_strncpy(ret->relpath, filename, sizeof(ret->relpath));
193         BLI_strncpy(ret->abspath, filename, sizeof(ret->abspath));
194         BLI_path_abs(ret->abspath, G.main->name);
195
196         ret->blo_handle= NULL;
197         ret->flag=      (is_link ? FILE_LINK : 0) |
198                                 (is_rel ? FILE_RELPATH : 0);
199
200         ret->dict= PyDict_New();
201
202         return (PyObject *)ret;
203 }
204
205 static PyObject *_bpy_names(BPy_Library *self, int blocktype)
206 {
207         PyObject *list;
208         LinkNode *l, *names;
209         int totnames;
210
211         names= BLO_blendhandle_get_datablock_names(self->blo_handle, blocktype, &totnames);
212
213         if(names) {
214                 int counter= 0;
215                 list= PyList_New(totnames);
216                 for(l= names; l; l= l->next) {
217                         PyList_SET_ITEM(list, counter, PyUnicode_FromString((char *)l->link));
218                         counter++;
219                 }
220                 BLI_linklist_free(names, free); /* free linklist *and* each node's data */
221         }
222         else {
223                 list= PyList_New(0);
224         }
225
226         return list;
227 }
228
229 static PyObject *bpy_lib_enter(BPy_Library *self, PyObject *UNUSED(args))
230 {
231         PyObject *ret;
232         BPy_Library *self_from;
233         PyObject *from_dict= PyDict_New();
234         ReportList reports;
235
236         BKE_reports_init(&reports, RPT_STORE);
237
238         self->blo_handle= BLO_blendhandle_from_file(self->abspath, &reports);
239
240         if(self->blo_handle == NULL) {
241                 if(BPy_reports_to_error(&reports, PyExc_IOError, TRUE) != -1) {
242                         PyErr_Format(PyExc_IOError,
243                                      "load: %s failed to open blend file",
244                                      self->abspath);
245                 }
246                 return NULL;
247         }
248         else {
249                 int i= 0, code;
250                 while((code= BKE_idcode_iter_step(&i))) {
251                         if(BKE_idcode_is_linkable(code)) {
252                                 const char *name_plural= BKE_idcode_to_name_plural(code);
253                                 PyObject *str= PyUnicode_FromString(name_plural);
254                                 PyDict_SetItem(self->dict, str, PyList_New(0));
255                                 PyDict_SetItem(from_dict, str, _bpy_names(self, code));
256                                 Py_DECREF(str);
257                         }
258                 }
259         }
260
261         /* create a dummy */
262         self_from= PyObject_New(BPy_Library, &bpy_lib_Type);
263         BLI_strncpy(self_from->relpath, self->relpath, sizeof(BPy_Library));
264         BLI_strncpy(self_from->abspath, self->abspath, sizeof(BPy_Library));
265
266         self_from->blo_handle= NULL;
267         self_from->flag= 0;
268         self_from->dict= from_dict; /* owns the dict */
269
270         /* return pair */
271         ret= PyTuple_New(2);
272
273         PyTuple_SET_ITEM(ret, 0, (PyObject *)self_from);
274
275         PyTuple_SET_ITEM(ret, 1, (PyObject *)self);
276         Py_INCREF(self);
277
278         BKE_reports_clear(&reports);
279
280         return ret;
281 }
282
283 static void bpy_lib_exit_warn_idname(BPy_Library *self, const char *name_plural, const char *idname)
284 {
285         PyObject *exc, *val, *tb;
286         PyErr_Fetch(&exc, &val, &tb);
287         if (PyErr_WarnFormat(PyExc_UserWarning, 1,
288                                                  "load: '%s' does not contain %s[\"%s\"]",
289                              self->abspath, name_plural, idname)) {
290                 /* Spurious errors can appear at shutdown */
291                 if (PyErr_ExceptionMatches(PyExc_Warning)) {
292                         PyErr_WriteUnraisable((PyObject *)self);
293                 }
294         }
295         PyErr_Restore(exc, val, tb);
296 }
297
298 static void bpy_lib_exit_warn_type(BPy_Library *self, PyObject *item)
299 {
300         PyObject *exc, *val, *tb;
301         PyErr_Fetch(&exc, &val, &tb);
302         if (PyErr_WarnFormat(PyExc_UserWarning, 1,
303                                                  "load: '%s' expected a string type, not a %.200s",
304                              self->abspath, Py_TYPE(item)->tp_name)) {
305                 /* Spurious errors can appear at shutdown */
306                 if (PyErr_ExceptionMatches(PyExc_Warning)) {
307                         PyErr_WriteUnraisable((PyObject *)self);
308                 }
309         }
310         PyErr_Restore(exc, val, tb);
311 }
312
313 static PyObject *bpy_lib_exit(BPy_Library *self, PyObject *UNUSED(args))
314 {
315         Main *mainl= NULL;
316         int err= 0;
317
318         flag_all_listbases_ids(LIB_PRE_EXISTING, 1);
319
320         /* here appending/linking starts */
321         mainl= BLO_library_append_begin(CTX_data_main(BPy_GetContext()), &(self->blo_handle), self->relpath);
322
323         {
324                 int i= 0, code;
325                 while((code= BKE_idcode_iter_step(&i))) {
326                         if(BKE_idcode_is_linkable(code)) {
327                                 const char *name_plural= BKE_idcode_to_name_plural(code);
328                                 PyObject *ls= PyDict_GetItemString(self->dict, name_plural);
329                                 // printf("lib: %s\n", name_plural);
330                                 if(ls && PyList_Check(ls)) {
331                                         /* loop */
332                                         Py_ssize_t size= PyList_GET_SIZE(ls);
333                                         Py_ssize_t i;
334                                         PyObject *item;
335                                         const char *item_str;
336
337                                         for(i= 0; i < size; i++) {
338                                                 item= PyList_GET_ITEM(ls, i);
339                                                 item_str= _PyUnicode_AsString(item);
340
341                                                 // printf("  %s\n", item_str);
342
343                                                 if(item_str) {
344                                                         ID *id= BLO_library_append_named_part(mainl, &(self->blo_handle), item_str, code);
345                                                         if(id) {
346 #ifdef USE_RNA_DATABLOCKS
347                                                                 PointerRNA id_ptr;
348                                                                 RNA_id_pointer_create(id, &id_ptr);
349                                                                 Py_DECREF(item);
350                                                                 item= pyrna_struct_CreatePyObject(&id_ptr);
351 #endif
352                                                         }
353                                                         else {
354                                                                 bpy_lib_exit_warn_idname(self, name_plural, item_str);
355                                                                 /* just warn for now */
356                                                                 /* err = -1; */
357 #ifdef USE_RNA_DATABLOCKS
358                                                                 item= Py_None;
359                                                                 Py_INCREF(item);
360 #endif
361                                                         }
362
363                                                         /* ID or None */
364                                                 }
365                                                 else {
366                                                         /* XXX, could complain about this */
367                                                         bpy_lib_exit_warn_type(self, item);
368                                                         PyErr_Clear();
369
370 #ifdef USE_RNA_DATABLOCKS
371                                                         item= Py_None;
372                                                         Py_INCREF(item);
373 #endif
374                                                 }
375
376 #ifdef USE_RNA_DATABLOCKS
377                                                 PyList_SET_ITEM(ls, i, item);
378 #endif
379                                         }
380                                 }
381                         }
382                 }
383         }
384
385         if(err == -1) {
386                 /* exception raised above, XXX, this leaks some memory */
387                 BLO_blendhandle_close(self->blo_handle);
388                 self->blo_handle= NULL;
389                 flag_all_listbases_ids(LIB_PRE_EXISTING, 0);
390                 return NULL;
391         }
392         else {
393                 BLO_library_append_end(NULL, mainl, &(self->blo_handle), 0, self->flag);
394                 BLO_blendhandle_close(self->blo_handle);
395                 self->blo_handle= NULL;
396
397                 {       /* copied from wm_operator.c */
398                         /* mark all library linked objects to be updated */
399                         recalc_all_library_objects(G.main);
400
401                         /* append, rather than linking */
402                         if((self->flag & FILE_LINK)==0) {
403                                 Library *lib= BLI_findstring(&G.main->library, self->abspath, offsetof(Library, name));
404                                 if(lib) all_local(lib, 1);
405                                 else    BLI_assert(!"cant find name of just added library!");
406                         }
407                 }
408
409                 flag_all_listbases_ids(LIB_PRE_EXISTING, 0);
410
411                 Py_RETURN_NONE;
412         }
413 }
414
415 static PyObject *bpy_lib_dir(BPy_Library *self)
416 {
417         return PyDict_Keys(self->dict);
418 }
419
420
421 int bpy_lib_init(PyObject *mod_par)
422 {
423         static PyMethodDef load_meth= {"load", (PyCFunction)bpy_lib_load, METH_STATIC|METH_VARARGS|METH_KEYWORDS, bpy_lib_load_doc};
424         PyModule_AddObject(mod_par, "_library_load", PyCFunction_New(&load_meth, NULL));
425
426         /* some compilers dont like accessing this directly, delay assignment */
427         bpy_lib_Type.tp_getattro= PyObject_GenericGetAttr;
428
429         if(PyType_Ready(&bpy_lib_Type) < 0)
430                 return -1;
431
432         return 0;
433 }