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