PyAPI: add utilities PyTuple_SET_ITEMS, Py_INCREF_RET
[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 #include <Python.h>
35 #include <stddef.h>
36
37 #include "BLI_utildefines.h"
38 #include "BLI_string.h"
39 #include "BLI_linklist.h"
40 #include "BLI_path_util.h"
41
42 #include "BLO_readfile.h"
43
44 #include "BKE_global.h"
45 #include "BKE_main.h"
46 #include "BKE_library.h"
47 #include "BKE_idcode.h"
48 #include "BKE_report.h"
49 #include "BKE_context.h"
50
51 #include "DNA_space_types.h" /* FILE_LINK, FILE_RELPATH */
52
53 #include "bpy_util.h"
54 #include "bpy_library.h"
55
56 #include "../generic/python_utildefines.h"
57
58 /* nifty feature. swap out strings for RNA data */
59 #define USE_RNA_DATABLOCKS
60
61 #ifdef USE_RNA_DATABLOCKS
62 #  include "bpy_rna.h"
63 #  include "RNA_access.h"
64 #endif
65
66 typedef struct {
67         PyObject_HEAD /* required python macro */
68         /* collection iterator specific parts */
69         char relpath[FILE_MAX];
70         char abspath[FILE_MAX]; /* absolute path */
71         BlendHandle *blo_handle;
72         int flag;
73         PyObject *dict;
74 } BPy_Library;
75
76 static PyObject *bpy_lib_load(PyObject *self, PyObject *args, PyObject *kwds);
77 static PyObject *bpy_lib_enter(BPy_Library *self, PyObject *args);
78 static PyObject *bpy_lib_exit(BPy_Library *self, PyObject *args);
79 static PyObject *bpy_lib_dir(BPy_Library *self);
80
81 static PyMethodDef bpy_lib_methods[] = {
82         {"__enter__", (PyCFunction)bpy_lib_enter, METH_NOARGS},
83         {"__exit__",  (PyCFunction)bpy_lib_exit,  METH_VARARGS},
84         {"__dir__",   (PyCFunction)bpy_lib_dir,   METH_NOARGS},
85         {NULL}           /* sentinel */
86 };
87
88 static void bpy_lib_dealloc(BPy_Library *self)
89 {
90         Py_XDECREF(self->dict);
91         Py_TYPE(self)->tp_free(self);
92 }
93
94
95 static PyTypeObject bpy_lib_Type = {
96         PyVarObject_HEAD_INIT(NULL, 0)
97         "bpy_lib",      /* tp_name */
98         sizeof(BPy_Library),            /* tp_basicsize */
99         0,                          /* tp_itemsize */
100         /* methods */
101         (destructor)bpy_lib_dealloc, /* tp_dealloc */
102         NULL,                       /* printfunc tp_print; */
103         NULL,                       /* getattrfunc tp_getattr; */
104         NULL,                       /* setattrfunc tp_setattr; */
105         NULL,                       /* tp_compare */ /* DEPRECATED in python 3.0! */
106         NULL,                       /* tp_repr */
107
108         /* Method suites for standard classes */
109
110         NULL,                       /* PyNumberMethods *tp_as_number; */
111         NULL,                       /* PySequenceMethods *tp_as_sequence; */
112         NULL,                       /* PyMappingMethods *tp_as_mapping; */
113
114         /* More standard operations (here for binary compatibility) */
115
116         NULL,                       /* hashfunc tp_hash; */
117         NULL,                       /* ternaryfunc tp_call; */
118         NULL,                       /* reprfunc tp_str; */
119
120         /* will only use these if this is a subtype of a py class */
121         NULL /*PyObject_GenericGetAttr is assigned later */,    /* getattrofunc tp_getattro; */
122         NULL,                       /* setattrofunc tp_setattro; */
123
124         /* Functions to access object as input/output buffer */
125         NULL,                       /* PyBufferProcs *tp_as_buffer; */
126
127         /*** Flags to define presence of optional/expanded features ***/
128         Py_TPFLAGS_DEFAULT,         /* long tp_flags; */
129
130         NULL,                       /*  char *tp_doc;  Documentation string */
131         /*** Assigned meaning in release 2.0 ***/
132         /* call function for all accessible objects */
133         NULL,                       /* traverseproc tp_traverse; */
134
135         /* delete references to contained objects */
136         NULL,                       /* inquiry tp_clear; */
137
138         /***  Assigned meaning in release 2.1 ***/
139         /*** rich comparisons ***/
140         NULL, /* subclassed */          /* richcmpfunc tp_richcompare; */
141
142         /***  weak reference enabler ***/
143         0,
144         /*** Added in release 2.2 ***/
145         /*   Iterators */
146         NULL,                       /* getiterfunc tp_iter; */
147         NULL,                       /* iternextfunc tp_iternext; */
148
149         /*** Attribute descriptor and subclassing stuff ***/
150         bpy_lib_methods,            /* struct PyMethodDef *tp_methods; */
151         NULL,                       /* struct PyMemberDef *tp_members; */
152         NULL,                       /* struct PyGetSetDef *tp_getset; */
153         NULL,                       /* struct _typeobject *tp_base; */
154         NULL,                       /* PyObject *tp_dict; */
155         NULL,                       /* descrgetfunc tp_descr_get; */
156         NULL,                       /* descrsetfunc tp_descr_set; */
157         offsetof(BPy_Library, dict), /* long tp_dictoffset; */
158         NULL,                       /* initproc tp_init; */
159         NULL,                       /* allocfunc tp_alloc; */
160         NULL,                       /* newfunc tp_new; */
161         /*  Low-level free-memory routine */
162         NULL,                       /* freefunc tp_free;  */
163         /* For PyObject_IS_GC */
164         NULL,                       /* inquiry tp_is_gc;  */
165         NULL,                       /* PyObject *tp_bases; */
166         /* method resolution order */
167         NULL,                       /* PyObject *tp_mro;  */
168         NULL,                       /* PyObject *tp_cache; */
169         NULL,                       /* PyObject *tp_subclasses; */
170         NULL,                       /* PyObject *tp_weaklist; */
171         NULL
172 };
173
174 PyDoc_STRVAR(bpy_lib_load_doc,
175 ".. method:: load(filepath, link=False, relative=False)\n"
176 "\n"
177 "   Returns a context manager which exposes 2 library objects on entering.\n"
178 "   Each object has attributes matching bpy.data which are lists of strings to be linked.\n"
179 "\n"
180 "   :arg filepath: The path to a blend file.\n"
181 "   :type filepath: string\n"
182 "   :arg link: When False reference to the original file is lost.\n"
183 "   :type link: bool\n"
184 "   :arg relative: When True the path is stored relative to the open blend file.\n"
185 "   :type relative: bool\n"
186 );
187 static PyObject *bpy_lib_load(PyObject *UNUSED(self), PyObject *args, PyObject *kwds)
188 {
189         static const char *kwlist[] = {"filepath", "link", "relative", NULL};
190         BPy_Library *ret;
191         const char *filename = NULL;
192         int is_rel = 0, is_link = 0;
193
194         if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|ii:load", (char **)kwlist, &filename, &is_link, &is_rel))
195                 return NULL;
196
197         ret = PyObject_New(BPy_Library, &bpy_lib_Type);
198
199         BLI_strncpy(ret->relpath, filename, sizeof(ret->relpath));
200         BLI_strncpy(ret->abspath, filename, sizeof(ret->abspath));
201         BLI_path_abs(ret->abspath, G.main->name);
202
203         ret->blo_handle = NULL;
204         ret->flag = ((is_link ? FILE_LINK : 0) |
205                      (is_rel ? FILE_RELPATH : 0));
206
207         ret->dict = PyDict_New();
208
209         return (PyObject *)ret;
210 }
211
212 static PyObject *_bpy_names(BPy_Library *self, int blocktype)
213 {
214         PyObject *list;
215         LinkNode *l, *names;
216         int totnames;
217
218         names = BLO_blendhandle_get_datablock_names(self->blo_handle, blocktype, &totnames);
219
220         if (names) {
221                 int counter = 0;
222                 list = PyList_New(totnames);
223                 for (l = names; l; l = l->next) {
224                         PyList_SET_ITEM(list, counter, PyUnicode_FromString((char *)l->link));
225                         counter++;
226                 }
227                 BLI_linklist_free(names, free); /* free linklist *and* each node's data */
228         }
229         else {
230                 list = PyList_New(0);
231         }
232
233         return list;
234 }
235
236 static PyObject *bpy_lib_enter(BPy_Library *self, PyObject *UNUSED(args))
237 {
238         PyObject *ret;
239         BPy_Library *self_from;
240         PyObject *from_dict = PyDict_New();
241         ReportList reports;
242
243         BKE_reports_init(&reports, RPT_STORE);
244
245         self->blo_handle = BLO_blendhandle_from_file(self->abspath, &reports);
246
247         if (self->blo_handle == NULL) {
248                 if (BPy_reports_to_error(&reports, PyExc_IOError, true) != -1) {
249                         PyErr_Format(PyExc_IOError,
250                                      "load: %s failed to open blend file",
251                                      self->abspath);
252                 }
253                 return NULL;
254         }
255         else {
256                 int i = 0, code;
257                 while ((code = BKE_idcode_iter_step(&i))) {
258                         if (BKE_idcode_is_linkable(code)) {
259                                 const char *name_plural = BKE_idcode_to_name_plural(code);
260                                 PyObject *str = PyUnicode_FromString(name_plural);
261                                 PyDict_SetItem(self->dict, str, PyList_New(0));
262                                 PyDict_SetItem(from_dict, str, _bpy_names(self, code));
263                                 Py_DECREF(str);
264                         }
265                 }
266         }
267
268         /* create a dummy */
269         self_from = PyObject_New(BPy_Library, &bpy_lib_Type);
270         BLI_strncpy(self_from->relpath, self->relpath, sizeof(self_from->relpath));
271         BLI_strncpy(self_from->abspath, self->abspath, sizeof(self_from->abspath));
272
273         self_from->blo_handle = NULL;
274         self_from->flag = 0;
275         self_from->dict = from_dict; /* owns the dict */
276
277         /* return pair */
278         ret = PyTuple_New(2);
279         PyTuple_SET_ITEMS(ret,
280                 (PyObject *)self_from,
281                 (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         BKE_main_id_flag_all(bmain, LIB_PRE_EXISTING, true);
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                                                                 /* swap name for pointer to the id */
357                                                                 Py_DECREF(item);
358                                                                 item = PyCapsule_New((void *)id, NULL, NULL);
359 #endif
360                                                         }
361                                                         else {
362                                                                 bpy_lib_exit_warn_idname(self, name_plural, item_str);
363                                                                 /* just warn for now */
364                                                                 /* err = -1; */
365 #ifdef USE_RNA_DATABLOCKS
366                                                                 item = Py_INCREF_RET(Py_None);
367 #endif
368                                                         }
369
370                                                         /* ID or None */
371                                                 }
372                                                 else {
373                                                         /* XXX, could complain about this */
374                                                         bpy_lib_exit_warn_type(self, item);
375                                                         PyErr_Clear();
376
377 #ifdef USE_RNA_DATABLOCKS
378                                                         item = Py_INCREF_RET(Py_None);
379 #endif
380                                                 }
381
382 #ifdef USE_RNA_DATABLOCKS
383                                                 PyList_SET_ITEM(ls, i, item);
384 #endif
385                                         }
386                                 }
387                         }
388                 }
389         }
390
391         if (err == -1) {
392                 /* exception raised above, XXX, this leaks some memory */
393                 BLO_blendhandle_close(self->blo_handle);
394                 self->blo_handle = NULL;
395                 BKE_main_id_flag_all(bmain, LIB_PRE_EXISTING, false);
396                 return NULL;
397         }
398         else {
399                 Library *lib = mainl->curlib; /* newly added lib, assign before append end */
400                 BLO_library_append_end(NULL, mainl, &(self->blo_handle), 0, self->flag);
401                 BLO_blendhandle_close(self->blo_handle);
402                 self->blo_handle = NULL;
403
404                 /* copied from wm_operator.c */
405                 {
406                         /* mark all library linked objects to be updated */
407                         BKE_main_lib_objects_recalc_all(G.main);
408
409                         /* append, rather than linking */
410                         if ((self->flag & FILE_LINK) == 0) {
411                                 BKE_library_make_local(bmain, lib, true);
412                         }
413                 }
414
415                 BKE_main_id_flag_all(bmain, LIB_PRE_EXISTING, false);
416
417                 /* finally swap the capsules for real bpy objects
418                  * important since BLO_library_append_end initializes NodeTree types used by srna->refine */
419                 {
420                         int idcode_step = 0, idcode;
421                         while ((idcode = BKE_idcode_iter_step(&idcode_step))) {
422                                 if (BKE_idcode_is_linkable(idcode)) {
423                                         const char *name_plural = BKE_idcode_to_name_plural(idcode);
424                                         PyObject *ls = PyDict_GetItemString(self->dict, name_plural);
425                                         if (ls && PyList_Check(ls)) {
426                                                 Py_ssize_t size = PyList_GET_SIZE(ls);
427                                                 Py_ssize_t i;
428                                                 PyObject *item;
429
430                                                 for (i = 0; i < size; i++) {
431                                                         item = PyList_GET_ITEM(ls, i);
432                                                         if (PyCapsule_CheckExact(item)) {
433                                                                 PointerRNA id_ptr;
434                                                                 ID *id;
435
436                                                                 id = PyCapsule_GetPointer(item, NULL);
437                                                                 Py_DECREF(item);
438
439                                                                 RNA_id_pointer_create(id, &id_ptr);
440                                                                 item = pyrna_struct_CreatePyObject(&id_ptr);
441                                                                 PyList_SET_ITEM(ls, i, item);
442                                                         }
443                                                 }
444                                         }
445                                 }
446                         }
447                 }
448
449                 Py_RETURN_NONE;
450         }
451 }
452
453 static PyObject *bpy_lib_dir(BPy_Library *self)
454 {
455         return PyDict_Keys(self->dict);
456 }
457
458
459 int BPY_library_module(PyObject *mod_par)
460 {
461         static PyMethodDef load_meth = {"load", (PyCFunction)bpy_lib_load,
462                                         METH_STATIC | METH_VARARGS | METH_KEYWORDS,
463                                         bpy_lib_load_doc};
464
465         PyModule_AddObject(mod_par, "_library_load", PyCFunction_New(&load_meth, NULL));
466
467         /* some compilers don't like accessing this directly, delay assignment */
468         bpy_lib_Type.tp_getattro = PyObject_GenericGetAttr;
469
470         if (PyType_Ready(&bpy_lib_Type) < 0)
471                 return -1;
472
473         return 0;
474 }