5b8c20bb12d00d8d395f28012e36e22c70be17ef
[blender.git] / source / blender / python / intern / bpy_app_handlers.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_app_handlers.c
24  *  \ingroup pythonintern
25  */
26
27 #include <Python.h>
28 #include "BLI_utildefines.h"
29 #include "BLI_callbacks.h"
30
31 #include "RNA_types.h"
32 #include "RNA_access.h"
33 #include "bpy_rna.h"
34 #include "bpy_app_handlers.h"
35
36 void bpy_app_generic_callback(struct Main *main, struct ID *id, void *arg);
37
38 static PyTypeObject BlenderAppCbType;
39
40 static PyStructSequence_Field app_cb_info_fields[]= {
41         {(char *)"frame_change_pre", NULL},
42         {(char *)"frame_change_post", NULL},
43         {(char *)"render_pre", NULL},
44         {(char *)"render_post", NULL},
45         {(char *)"render_stats", NULL},
46         {(char *)"load_pre", NULL},
47         {(char *)"load_post", NULL},
48         {(char *)"save_pre", NULL},
49         {(char *)"save_post", NULL},
50         {(char *)"scene_update_pre", NULL},
51         {(char *)"scene_update_post", NULL},
52
53         /* sets the permanent tag */
54 #   define APP_CB_OTHER_FIELDS 1
55         {(char *)"persistent", NULL},
56
57         {NULL}
58 };
59
60 static PyStructSequence_Desc app_cb_info_desc= {
61         (char *)"bpy.app.handlers",     /* name */
62         (char *)"This module contains callbacks",    /* doc */
63         app_cb_info_fields,    /* fields */
64         (sizeof(app_cb_info_fields)/sizeof(PyStructSequence_Field)) - 1
65 };
66
67 /*
68 #if (BLI_CB_EVT_TOT != ((sizeof(app_cb_info_fields)/sizeof(PyStructSequence_Field))))
69 #  error "Callbacks are out of sync"
70 #endif
71 */
72
73 /* --------------------------------------------------------------------------*/
74 /* permanent tagging code */
75 #define PERMINENT_CB_ID "_bpy_persistent"
76
77 static PyObject *bpy_app_handlers_persistent_new(PyTypeObject *UNUSED(type), PyObject *args, PyObject *UNUSED(kwds))
78 {
79         PyObject *value;
80
81         if(!PyArg_ParseTuple(args, "O:bpy.app.handlers.persistent", &value))
82                 return NULL;
83
84         if (PyFunction_Check(value)) {
85                 PyObject **dict_ptr= _PyObject_GetDictPtr(value);
86                 if (dict_ptr == NULL) {
87                         PyErr_SetString(PyExc_ValueError,
88                                         "bpy.app.handlers.persistent wasn't able to "
89                                         "get the dictionary from the function passed");
90                         return NULL;
91                 }
92                 else {
93                         /* set id */
94                         if (*dict_ptr == NULL) {
95                                 *dict_ptr= PyDict_New();
96                         }
97
98                         PyDict_SetItemString(*dict_ptr, PERMINENT_CB_ID, Py_None);
99                 }
100
101                 Py_INCREF(value);
102                 return value;
103         }
104         else {
105                 PyErr_SetString(PyExc_ValueError,
106                                 "bpy.app.handlers.persistent expected a function");
107                 return NULL;
108         }
109 }
110
111 /* dummy type because decorators can't be PyCFunctions */
112 static PyTypeObject BPyPersistent_Type = {
113
114 #if defined(_MSC_VER) || defined(FREE_WINDOWS)
115     PyVarObject_HEAD_INIT(NULL, 0)
116 #else
117     PyVarObject_HEAD_INIT(&PyType_Type, 0)
118 #endif
119
120     "persistent",                               /* tp_name */
121     0,                                          /* tp_basicsize */
122     0,                                          /* tp_itemsize */
123     /* methods */
124     0,                                          /* tp_dealloc */
125     0,                                          /* tp_print */
126     0,                                          /* tp_getattr */
127     0,                                          /* tp_setattr */
128     0,                                          /* tp_reserved */
129     0,                                          /* tp_repr */
130     0,                                          /* tp_as_number */
131     0,                                          /* tp_as_sequence */
132     0,                                          /* tp_as_mapping */
133     0,                                          /* tp_hash */
134     0,                                          /* tp_call */
135     0,                                          /* tp_str */
136     0,                                          /* tp_getattro */
137     0,                                          /* tp_setattro */
138     0,                                          /* tp_as_buffer */
139     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
140         Py_TPFLAGS_BASETYPE,                    /* tp_flags */
141     0,                                          /* tp_doc */
142     0,                                          /* tp_traverse */
143     0,                                          /* tp_clear */
144     0,                                          /* tp_richcompare */
145     0,                                          /* tp_weaklistoffset */
146     0,                                          /* tp_iter */
147     0,                                          /* tp_iternext */
148     0,                                          /* tp_methods */
149     0,                                          /* tp_members */
150     0,                                          /* tp_getset */
151     0,                                          /* tp_base */
152     0,                                          /* tp_dict */
153     0,                                          /* tp_descr_get */
154     0,                                          /* tp_descr_set */
155     0,                                          /* tp_dictoffset */
156     0,                                          /* tp_init */
157     0,                                          /* tp_alloc */
158     bpy_app_handlers_persistent_new,            /* tp_new */
159     0,                                          /* tp_free */
160 };
161
162 static PyObject *py_cb_array[BLI_CB_EVT_TOT]= {NULL};
163
164 static PyObject *make_app_cb_info(void)
165 {
166         PyObject *app_cb_info;
167         int pos= 0;
168
169         app_cb_info= PyStructSequence_New(&BlenderAppCbType);
170         if (app_cb_info == NULL) {
171                 return NULL;
172         }
173
174         for (pos= 0; pos < BLI_CB_EVT_TOT; pos++) {
175                 if (app_cb_info_fields[pos].name == NULL) {
176                         Py_FatalError("invalid callback slots 1");
177                 }
178                 PyStructSequence_SET_ITEM(app_cb_info, pos, (py_cb_array[pos]= PyList_New(0)));
179         }
180         if (app_cb_info_fields[pos + APP_CB_OTHER_FIELDS].name != NULL) {
181                 Py_FatalError("invalid callback slots 2");
182         }
183
184         /* custom function */
185         PyStructSequence_SET_ITEM(app_cb_info, pos++, (PyObject *)&BPyPersistent_Type);
186
187         return app_cb_info;
188 }
189
190 PyObject *BPY_app_handlers_struct(void)
191 {
192         PyObject *ret;
193
194 #if defined(_MSC_VER) || defined(FREE_WINDOWS)
195         BPyPersistent_Type.ob_base.ob_base.ob_type= &PyType_Type;
196 #endif
197
198         if (PyType_Ready(&BPyPersistent_Type) < 0) {
199                 BLI_assert(!"error initializing 'bpy.app.handlers.persistent'");
200         }
201
202         PyStructSequence_InitType(&BlenderAppCbType, &app_cb_info_desc);
203
204         ret= make_app_cb_info();
205
206         /* prevent user from creating new instances */
207         BlenderAppCbType.tp_init= NULL;
208         BlenderAppCbType.tp_new= NULL;
209
210         /* assign the C callbacks */
211         if (ret) {
212                 static bCallbackFuncStore funcstore_array[BLI_CB_EVT_TOT]= {{NULL}};
213                 bCallbackFuncStore *funcstore;
214                 int pos= 0;
215
216                 for (pos= 0; pos < BLI_CB_EVT_TOT; pos++) {
217                         funcstore= &funcstore_array[pos];
218                         funcstore->func= bpy_app_generic_callback;
219                         funcstore->alloc= 0;
220                         funcstore->arg= SET_INT_IN_POINTER(pos);
221                         BLI_add_cb(funcstore, pos);
222                 }
223         }
224
225         return ret;
226 }
227
228 void BPY_app_handlers_reset(const short do_all)
229 {
230         int pos= 0;
231
232         if (do_all) {
233         for (pos= 0; pos < BLI_CB_EVT_TOT; pos++) {
234                         /* clear list */
235                         PyList_SetSlice(py_cb_array[pos], 0, PY_SSIZE_T_MAX, NULL);
236                 }
237         }
238         else {
239                 /* save string conversion thrashing */
240                 PyObject *perm_id_str= PyUnicode_FromString(PERMINENT_CB_ID);
241
242                 for (pos= 0; pos < BLI_CB_EVT_TOT; pos++) {
243                         /* clear only items without PERMINENT_CB_ID */
244                         PyObject *ls= py_cb_array[pos];
245                         Py_ssize_t i;
246
247                         PyObject *item;
248                         PyObject **dict_ptr;
249
250                         for(i= PyList_GET_SIZE(ls) - 1; i >= 0; i--) {
251
252                                 if (    (PyFunction_Check((item= PyList_GET_ITEM(ls, i)))) &&
253                                         (dict_ptr= _PyObject_GetDictPtr(item)) &&
254                                         (*dict_ptr) &&
255                                         (PyDict_GetItem(*dict_ptr, perm_id_str) != NULL))
256                                 {
257                                         /* keep */
258                                 }
259                                 else {
260                                         /* remove */
261                                         /* PySequence_DelItem(ls, i); */ /* more obvious buw slower */
262                                         PyList_SetSlice(ls, i, i + 1, NULL);
263                                 }
264                         }
265                 }
266
267                 Py_DECREF(perm_id_str);
268         }
269 }
270
271 /* the actual callback - not necessarily called from py */
272 void bpy_app_generic_callback(struct Main *UNUSED(main), struct ID *id, void *arg)
273 {
274         PyObject *cb_list= py_cb_array[GET_INT_FROM_POINTER(arg)];
275         Py_ssize_t cb_list_len;
276         if ((cb_list_len= PyList_GET_SIZE(cb_list)) > 0) {
277                 PyGILState_STATE gilstate= PyGILState_Ensure();
278
279                 PyObject* args= PyTuple_New(1); // save python creating each call
280                 PyObject* func;
281                 PyObject* ret;
282                 Py_ssize_t pos;
283
284                 /* setup arguments */
285                 if (id) {
286                         PointerRNA id_ptr;
287                         RNA_id_pointer_create(id, &id_ptr);
288                         PyTuple_SET_ITEM(args, 0, pyrna_struct_CreatePyObject(&id_ptr));
289                 }
290                 else {
291                         PyTuple_SET_ITEM(args, 0, Py_None);
292                         Py_INCREF(Py_None);
293                 }
294
295                 // Iterate the list and run the callbacks
296                 for (pos=0; pos < cb_list_len; pos++) {
297                         func= PyList_GET_ITEM(cb_list, pos);
298                         ret= PyObject_Call(func, args, NULL);
299                         if (ret==NULL) {
300                                 PyErr_Print();
301                                 PyErr_Clear();
302                         }
303                         else {
304                                 Py_DECREF(ret);
305                         }
306                 }
307
308                 Py_DECREF(args);
309
310                 PyGILState_Release(gilstate);
311         }
312 }