Blender  V2.93
bpy_app_handlers.c
Go to the documentation of this file.
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  */
16 
25 #include "BLI_utildefines.h"
26 #include <Python.h>
27 
28 #include "BKE_callbacks.h"
29 
30 #include "RNA_access.h"
31 #include "RNA_types.h"
32 #include "bpy_app_handlers.h"
33 #include "bpy_rna.h"
34 
35 #include "../generic/python_utildefines.h"
36 
37 #include "BPY_extern.h"
38 
40  struct PointerRNA **pointers,
41  const int num_pointers,
42  void *arg);
43 
44 static PyTypeObject BlenderAppCbType;
45 
46 static PyStructSequence_Field app_cb_info_fields[] = {
47  {"frame_change_pre",
48  "Called after frame change for playback and rendering, before any data is evaluated for the "
49  "new frame. This makes it possible to change data and relations (for example swap an object "
50  "to another mesh) for the new frame. Note that this handler is **not** to be used as 'before "
51  "the frame changes' event. The dependency graph is not available in this handler, as data "
52  "and relations may have been altered and the dependency graph has not yet been updated for "
53  "that."},
54  {"frame_change_post",
55  "Called after frame change for playback and rendering, after the data has been evaluated "
56  "for the new frame."},
57  {"render_pre", "on render (before)"},
58  {"render_post", "on render (after)"},
59  {"render_write", "on writing a render frame (directly after the frame is written)"},
60  {"render_stats", "on printing render statistics"},
61  {"render_init", "on initialization of a render job"},
62  {"render_complete", "on completion of render job"},
63  {"render_cancel", "on canceling a render job"},
64  {"load_pre", "on loading a new blend file (before)"},
65  {"load_post", "on loading a new blend file (after)"},
66  {"save_pre", "on saving a blend file (before)"},
67  {"save_post", "on saving a blend file (after)"},
68  {"undo_pre", "on loading an undo step (before)"},
69  {"undo_post", "on loading an undo step (after)"},
70  {"redo_pre", "on loading a redo step (before)"},
71  {"redo_post", "on loading a redo step (after)"},
72  {"depsgraph_update_pre", "on depsgraph update (pre)"},
73  {"depsgraph_update_post", "on depsgraph update (post)"},
74  {"version_update", "on ending the versioning code"},
75  {"load_factory_preferences_post", "on loading factory preferences (after)"},
76  {"load_factory_startup_post", "on loading factory startup (after)"},
77 
78 /* sets the permanent tag */
79 #define APP_CB_OTHER_FIELDS 1
80  {"persistent",
81  "Function decorator for callback functions not to be removed when loading new files"},
82 
83  {NULL},
84 };
85 
86 static PyStructSequence_Desc app_cb_info_desc = {
87  "bpy.app.handlers", /* name */
88  "This module contains callback lists", /* doc */
89  app_cb_info_fields, /* fields */
91 };
92 
93 #if 0
94 # if (BKE_CB_EVT_TOT != ARRAY_SIZE(app_cb_info_fields))
95 # error "Callbacks are out of sync"
96 # endif
97 #endif
98 
99 /* --------------------------------------------------------------------------*/
100 /* permanent tagging code */
101 #define PERMINENT_CB_ID "_bpy_persistent"
102 
103 static PyObject *bpy_app_handlers_persistent_new(PyTypeObject *UNUSED(type),
104  PyObject *args,
105  PyObject *UNUSED(kwds))
106 {
107  PyObject *value;
108 
109  if (!PyArg_ParseTuple(args, "O:bpy.app.handlers.persistent", &value)) {
110  return NULL;
111  }
112 
113  if (PyFunction_Check(value)) {
114  PyObject **dict_ptr = _PyObject_GetDictPtr(value);
115  if (dict_ptr == NULL) {
116  PyErr_SetString(PyExc_ValueError,
117  "bpy.app.handlers.persistent wasn't able to "
118  "get the dictionary from the function passed");
119  return NULL;
120  }
121 
122  /* set id */
123  if (*dict_ptr == NULL) {
124  *dict_ptr = PyDict_New();
125  }
126 
127  PyDict_SetItemString(*dict_ptr, PERMINENT_CB_ID, Py_None);
128 
129  Py_INCREF(value);
130  return value;
131  }
132 
133  PyErr_SetString(PyExc_ValueError, "bpy.app.handlers.persistent expected a function");
134  return NULL;
135 }
136 
137 /* dummy type because decorators can't be PyCFunctions */
138 static PyTypeObject BPyPersistent_Type = {
139 
140 #if defined(_MSC_VER)
141  PyVarObject_HEAD_INIT(NULL, 0)
142 #else
143  PyVarObject_HEAD_INIT(&PyType_Type, 0)
144 #endif
145 
146  "persistent", /* tp_name */
147  0, /* tp_basicsize */
148  0, /* tp_itemsize */
149  /* methods */
150  0, /* tp_dealloc */
151  0, /* tp_print */
152  0, /* tp_getattr */
153  0, /* tp_setattr */
154  0, /* tp_reserved */
155  0, /* tp_repr */
156  0, /* tp_as_number */
157  0, /* tp_as_sequence */
158  0, /* tp_as_mapping */
159  0, /* tp_hash */
160  0, /* tp_call */
161  0, /* tp_str */
162  0, /* tp_getattro */
163  0, /* tp_setattro */
164  0, /* tp_as_buffer */
165  Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */
166  0, /* tp_doc */
167  0, /* tp_traverse */
168  0, /* tp_clear */
169  0, /* tp_richcompare */
170  0, /* tp_weaklistoffset */
171  0, /* tp_iter */
172  0, /* tp_iternext */
173  0, /* tp_methods */
174  0, /* tp_members */
175  0, /* tp_getset */
176  0, /* tp_base */
177  0, /* tp_dict */
178  0, /* tp_descr_get */
179  0, /* tp_descr_set */
180  0, /* tp_dictoffset */
181  0, /* tp_init */
182  0, /* tp_alloc */
183  bpy_app_handlers_persistent_new, /* tp_new */
184  0, /* tp_free */
185 };
186 
187 static PyObject *py_cb_array[BKE_CB_EVT_TOT] = {NULL};
188 
189 static PyObject *make_app_cb_info(void)
190 {
191  PyObject *app_cb_info;
192  int pos;
193 
194  app_cb_info = PyStructSequence_New(&BlenderAppCbType);
195  if (app_cb_info == NULL) {
196  return NULL;
197  }
198 
199  for (pos = 0; pos < BKE_CB_EVT_TOT; pos++) {
200  if (app_cb_info_fields[pos].name == NULL) {
201  Py_FatalError("invalid callback slots 1");
202  }
203  PyStructSequence_SET_ITEM(app_cb_info, pos, (py_cb_array[pos] = PyList_New(0)));
204  }
206  Py_FatalError("invalid callback slots 2");
207  }
208 
209  /* custom function */
210  PyStructSequence_SET_ITEM(app_cb_info, pos++, (PyObject *)&BPyPersistent_Type);
211 
212  return app_cb_info;
213 }
214 
215 PyObject *BPY_app_handlers_struct(void)
216 {
217  PyObject *ret;
218 
219 #if defined(_MSC_VER)
220  BPyPersistent_Type.ob_base.ob_base.ob_type = &PyType_Type;
221 #endif
222 
223  if (PyType_Ready(&BPyPersistent_Type) < 0) {
224  BLI_assert(!"error initializing 'bpy.app.handlers.persistent'");
225  }
226 
227  PyStructSequence_InitType(&BlenderAppCbType, &app_cb_info_desc);
228 
229  ret = make_app_cb_info();
230 
231  /* prevent user from creating new instances */
232  BlenderAppCbType.tp_init = NULL;
233  BlenderAppCbType.tp_new = NULL;
234  BlenderAppCbType.tp_hash = (hashfunc)
235  _Py_HashPointer; /* without this we can't do set(sys.modules) T29635. */
236 
237  /* assign the C callbacks */
238  if (ret) {
239  static bCallbackFuncStore funcstore_array[BKE_CB_EVT_TOT] = {{NULL}};
240  bCallbackFuncStore *funcstore;
241  int pos = 0;
242 
243  for (pos = 0; pos < BKE_CB_EVT_TOT; pos++) {
244  funcstore = &funcstore_array[pos];
245  funcstore->func = bpy_app_generic_callback;
246  funcstore->alloc = 0;
247  funcstore->arg = POINTER_FROM_INT(pos);
248  BKE_callback_add(funcstore, pos);
249  }
250  }
251 
252  return ret;
253 }
254 
255 void BPY_app_handlers_reset(const short do_all)
256 {
257  PyGILState_STATE gilstate;
258  int pos = 0;
259 
260  gilstate = PyGILState_Ensure();
261 
262  if (do_all) {
263  for (pos = 0; pos < BKE_CB_EVT_TOT; pos++) {
264  /* clear list */
265  PyList_SetSlice(py_cb_array[pos], 0, PY_SSIZE_T_MAX, NULL);
266  }
267  }
268  else {
269  /* save string conversion thrashing */
270  PyObject *perm_id_str = PyUnicode_FromString(PERMINENT_CB_ID);
271 
272  for (pos = 0; pos < BKE_CB_EVT_TOT; pos++) {
273  /* clear only items without PERMINENT_CB_ID */
274  PyObject *ls = py_cb_array[pos];
275  Py_ssize_t i;
276 
277  PyObject *item;
278  PyObject **dict_ptr;
279 
280  for (i = PyList_GET_SIZE(ls) - 1; i >= 0; i--) {
281 
282  if ((PyFunction_Check((item = PyList_GET_ITEM(ls, i)))) &&
283  (dict_ptr = _PyObject_GetDictPtr(item)) && (*dict_ptr) &&
284  (PyDict_GetItem(*dict_ptr, perm_id_str) != NULL)) {
285  /* keep */
286  }
287  else {
288  /* remove */
289  /* PySequence_DelItem(ls, i); */ /* more obvious but slower */
290  PyList_SetSlice(ls, i, i + 1, NULL);
291  }
292  }
293  }
294 
295  Py_DECREF(perm_id_str);
296  }
297 
298  PyGILState_Release(gilstate);
299 }
300 
301 static PyObject *choose_arguments(PyObject *func, PyObject *args_all, PyObject *args_single)
302 {
303  if (!PyFunction_Check(func)) {
304  return args_all;
305  }
306  PyCodeObject *code = (PyCodeObject *)PyFunction_GetCode(func);
307  if (code->co_argcount == 1) {
308  return args_single;
309  }
310  return args_all;
311 }
312 
313 /* the actual callback - not necessarily called from py */
315  struct PointerRNA **pointers,
316  const int num_pointers,
317  void *arg)
318 {
319  PyObject *cb_list = py_cb_array[POINTER_AS_INT(arg)];
320  if (PyList_GET_SIZE(cb_list) > 0) {
321  const PyGILState_STATE gilstate = PyGILState_Ensure();
322 
323  const int num_arguments = 2;
324  PyObject *args_all = PyTuple_New(num_arguments); /* save python creating each call */
325  PyObject *args_single = PyTuple_New(1);
326  PyObject *func;
327  PyObject *ret;
328  Py_ssize_t pos;
329 
330  /* setup arguments */
331  for (int i = 0; i < num_pointers; ++i) {
332  PyTuple_SET_ITEM(args_all, i, pyrna_struct_CreatePyObject(pointers[i]));
333  }
334  for (int i = num_pointers; i < num_arguments; ++i) {
335  PyTuple_SET_ITEM(args_all, i, Py_INCREF_RET(Py_None));
336  }
337 
338  if (num_pointers == 0) {
339  PyTuple_SET_ITEM(args_single, 0, Py_INCREF_RET(Py_None));
340  }
341  else {
342  PyTuple_SET_ITEM(args_single, 0, pyrna_struct_CreatePyObject(pointers[0]));
343  }
344 
345  /* Iterate the list and run the callbacks
346  * note: don't store the list size since the scripts may remove themselves */
347  for (pos = 0; pos < PyList_GET_SIZE(cb_list); pos++) {
348  func = PyList_GET_ITEM(cb_list, pos);
349  PyObject *args = choose_arguments(func, args_all, args_single);
350  ret = PyObject_Call(func, args, NULL);
351  if (ret == NULL) {
352  /* Don't set last system variables because they might cause some
353  * dangling pointers to external render engines (when exception
354  * happens during rendering) which will break logic of render pipeline
355  * which expects to be the only user of render engine when rendering
356  * is finished.
357  */
358  PyErr_PrintEx(0);
359  PyErr_Clear();
360  }
361  else {
362  Py_DECREF(ret);
363  }
364  }
365 
366  Py_DECREF(args_all);
367  Py_DECREF(args_single);
368 
369  PyGILState_Release(gilstate);
370  }
371 }
void BKE_callback_add(bCallbackFuncStore *funcstore, eCbEvent evt)
Definition: callbacks.c:77
@ BKE_CB_EVT_TOT
Definition: BKE_callbacks.h:62
#define BLI_assert(a)
Definition: BLI_assert.h:58
#define ARRAY_SIZE(arr)
#define POINTER_FROM_INT(i)
#define UNUSED(x)
#define POINTER_AS_INT(i)
_GL_VOID GLfloat value _GL_VOID_RET _GL_VOID const GLuint GLboolean *residences _GL_BOOL_RET _GL_VOID GLsizei GLfloat GLfloat GLfloat GLfloat const GLubyte *bitmap _GL_VOID_RET _GL_VOID GLenum type
static PyObject * bpy_app_handlers_persistent_new(PyTypeObject *UNUSED(type), PyObject *args, PyObject *UNUSED(kwds))
void bpy_app_generic_callback(struct Main *main, struct PointerRNA **pointers, const int num_pointers, void *arg)
void BPY_app_handlers_reset(const short do_all)
static PyStructSequence_Desc app_cb_info_desc
static PyObject * choose_arguments(PyObject *func, PyObject *args_all, PyObject *args_single)
static PyObject * make_app_cb_info(void)
#define APP_CB_OTHER_FIELDS
static PyTypeObject BPyPersistent_Type
#define PERMINENT_CB_ID
PyObject * BPY_app_handlers_struct(void)
static PyStructSequence_Field app_cb_info_fields[]
static PyObject * py_cb_array[BKE_CB_EVT_TOT]
static PyTypeObject BlenderAppCbType
PyObject * pyrna_struct_CreatePyObject(PointerRNA *ptr)
Definition: bpy_rna.c:7469
uint pos
int main(int argc, char **argv)
Definition: msgfmt.c:457
return ret
Definition: BKE_main.h:116
void(* func)(struct Main *, struct PointerRNA **, const int num_pointers, void *arg)
Definition: BKE_callbacks.h:67