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