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