Blender V4.5
bpy_app_handlers.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
12
13#include "BLI_utildefines.h"
14#include <Python.h>
15
16#include "../generic/python_compat.hh" /* IWYU pragma: keep. */
17
18#include "BKE_callbacks.hh"
19
20#include "RNA_access.hh"
21
22#include "bpy_app_handlers.hh"
23#include "bpy_rna.hh"
24
25#include "BPY_extern.hh"
26
28 PointerRNA **pointers,
29 const int pointers_num,
30 void *arg);
31
32static PyTypeObject BlenderAppCbType;
33
34#define FILEPATH_SAVE_ARG \
35 "Accepts one argument: " \
36 "the file being saved, an empty string for the startup-file."
37#define FILEPATH_LOAD_ARG \
38 "Accepts one argument: " \
39 "the file being loaded, an empty string for the startup-file."
40#define RENDER_STATS_ARG \
41 "Accepts one argument: " \
42 "the render stats (render/saving time plus in background mode frame/used [peak] memory)."
43#define DEPSGRAPH_UPDATE_ARG \
44 "Accepts two arguments: " \
45 "The scene datablock and the dependency graph being updated"
46#define RENDER_ARG \
47 "Accepts one argument: " \
48 "the scene datablock being rendered"
49#define OBJECT_BAKE_ARG \
50 "Accepts one argument: " \
51 "the object datablock being baked"
52#define COMPOSITE_ARG \
53 "Accepts one argument: " \
54 "the scene datablock"
55#define ANNOTATION_ARG \
56 "Accepts two arguments: " \
57 "the annotation datablock and dependency graph"
58#define BLENDIMPORT_ARG \
59 "Accepts one argument: " \
60 "a BlendImportContext"
61
65static PyStructSequence_Field app_cb_info_fields[] = {
66 {"frame_change_pre",
67 "Called after frame change for playback and rendering, before any data is evaluated for the "
68 "new frame. This makes it possible to change data and relations (for example swap an object "
69 "to another mesh) for the new frame. Note that this handler is **not** to be used as 'before "
70 "the frame changes' event. The dependency graph is not available in this handler, as data "
71 "and relations may have been altered and the dependency graph has not yet been updated for "
72 "that. " DEPSGRAPH_UPDATE_ARG},
73 {"frame_change_post",
74 "Called after frame change for playback and rendering, after the data has been evaluated "
75 "for the new frame. " DEPSGRAPH_UPDATE_ARG},
76 {"render_pre", "on render (before)"},
77 {"render_post", "on render (after)"},
78 {"render_write", "on writing a render frame (directly after the frame is written)"},
79 {"render_stats", "on printing render statistics. " RENDER_STATS_ARG},
80 {"render_init", "on initialization of a render job. " RENDER_ARG},
81 {"render_complete", "on completion of render job. " RENDER_ARG},
82 {"render_cancel", "on canceling a render job. " RENDER_ARG},
83
84 {"load_pre", "on loading a new blend file (before)." FILEPATH_LOAD_ARG},
85 {"load_post", "on loading a new blend file (after). " FILEPATH_LOAD_ARG},
86 {"load_post_fail", "on failure to load a new blend file (after). " FILEPATH_LOAD_ARG},
87
88 {"save_pre", "on saving a blend file (before). " FILEPATH_SAVE_ARG},
89 {"save_post", "on saving a blend file (after). " FILEPATH_SAVE_ARG},
90 {"save_post_fail", "on failure to save a blend file (after). " FILEPATH_SAVE_ARG},
91
92 {"undo_pre", "on loading an undo step (before)"},
93 {"undo_post", "on loading an undo step (after)"},
94 {"redo_pre", "on loading a redo step (before)"},
95 {"redo_post", "on loading a redo step (after)"},
96 {"depsgraph_update_pre", "on depsgraph update (pre). " DEPSGRAPH_UPDATE_ARG},
97 {"depsgraph_update_post", "on depsgraph update (post). " DEPSGRAPH_UPDATE_ARG},
98 {"version_update", "on ending the versioning code"},
99 {"load_factory_preferences_post", "on loading factory preferences (after)"},
100 {"load_factory_startup_post", "on loading factory startup (after)"},
101 {"xr_session_start_pre", "on starting an xr session (before)"},
102 {"annotation_pre", "on drawing an annotation (before)"},
103 {"annotation_post", "on drawing an annotation (after)"},
104 {"object_bake_pre", "before starting a bake job. " OBJECT_BAKE_ARG},
105 {"object_bake_complete",
106 "on completing a bake job; will be called in the main thread. " OBJECT_BAKE_ARG},
107 {"object_bake_cancel",
108 "on canceling a bake job; will be called in the main thread. " OBJECT_BAKE_ARG},
109 {"composite_pre", "on a compositing background job (before). " COMPOSITE_ARG},
110 {"composite_post", "on a compositing background job (after). " COMPOSITE_ARG},
111 {"composite_cancel", "on a compositing background job (cancel). " COMPOSITE_ARG},
112 {"animation_playback_pre", "on starting animation playback. " DEPSGRAPH_UPDATE_ARG},
113 {"animation_playback_post", "on ending animation playback. " DEPSGRAPH_UPDATE_ARG},
114 {"translation_update_post", "on translation settings update"},
115 /* NOTE(@ideasman42): This avoids bad-level calls into BPY API
116 * but should not be considered part of the public Python API.
117 * If there is a compelling reason to make these public, the leading `_` can be removed. */
118 {"_extension_repos_update_pre", "on changes to extension repos (before)"},
119 {"_extension_repos_update_post", "on changes to extension repos (after)"},
120 {"_extension_repos_sync", "on creating or synchronizing the active repository"},
121 {"_extension_repos_files_clear",
122 "remove files from the repository directory (uses as a string argument)"},
123 {"blend_import_pre",
124 "on linking or appending data (before), get a single `BlendImportContext` parameter"},
125 {"blend_import_post",
126 "on linking or appending data (after), get a single `BlendImportContext` parameter"},
127
128/* sets the permanent tag */
129#define APP_CB_OTHER_FIELDS 1
130 {"persistent",
131 "Function decorator for callback functions not to be removed when loading new files"},
132
133 {nullptr},
134};
135
136static PyStructSequence_Desc app_cb_info_desc = {
137 /*name*/ "bpy.app.handlers",
138 /*doc*/ "This module contains callback lists",
139 /*fields*/ app_cb_info_fields,
140 /*n_in_sequence*/ ARRAY_SIZE(app_cb_info_fields) - 1,
141};
142
143#if 0
144# if (BKE_CB_EVT_TOT != ARRAY_SIZE(app_cb_info_fields))
145# error "Callbacks are out of sync"
146# endif
147#endif
148
149/* -------------------------------------------------------------------- */
152
153#define PERMINENT_CB_ID "_bpy_persistent"
154
155static PyObject *bpy_app_handlers_persistent_new(PyTypeObject * /*type*/,
156 PyObject *args,
157 PyObject * /*kwds*/)
158{
159 PyObject *value;
160
161 if (!PyArg_ParseTuple(args, "O:bpy.app.handlers.persistent", &value)) {
162 return nullptr;
163 }
164
165 if (PyFunction_Check(value)) {
166 PyObject **dict_ptr = _PyObject_GetDictPtr(value);
167 if (dict_ptr == nullptr) {
168 PyErr_SetString(PyExc_ValueError,
169 "bpy.app.handlers.persistent wasn't able to "
170 "get the dictionary from the function passed");
171 return nullptr;
172 }
173
174 /* set id */
175 if (*dict_ptr == nullptr) {
176 *dict_ptr = PyDict_New();
177 }
178
179 PyDict_SetItemString(*dict_ptr, PERMINENT_CB_ID, Py_None);
180
181 Py_INCREF(value);
182 return value;
183 }
184
185 PyErr_SetString(PyExc_ValueError, "bpy.app.handlers.persistent expected a function");
186 return nullptr;
187}
188
190static PyTypeObject BPyPersistent_Type = {
191#if defined(_MSC_VER)
192 /*ob_base*/ PyVarObject_HEAD_INIT(nullptr, 0)
193#else
194 /*ob_base*/ PyVarObject_HEAD_INIT(&PyType_Type, 0)
195#endif
196 /*tp_name*/ "persistent",
197 /*tp_basicsize*/ 0,
198 /*tp_itemsize*/ 0,
199 /*tp_dealloc*/ nullptr,
200 /*tp_vectorcall_offset*/ 0,
201 /*tp_getattr*/ nullptr,
202 /*tp_setattr*/ nullptr,
203 /*tp_as_async*/ nullptr,
204 /*tp_repr*/ nullptr,
205 /*tp_as_number*/ nullptr,
206 /*tp_as_sequence*/ nullptr,
207 /*tp_as_mapping*/ nullptr,
208 /*tp_hash*/ nullptr,
209 /*tp_call*/ nullptr,
210 /*tp_str*/ nullptr,
211 /*tp_getattro*/ nullptr,
212 /*tp_setattro*/ nullptr,
213 /*tp_as_buffer*/ nullptr,
214 /*tp_flags*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
215 /*tp_doc*/ nullptr,
216 /*tp_traverse*/ nullptr,
217 /*tp_clear*/ nullptr,
218 /*tp_richcompare*/ nullptr,
219 /*tp_weaklistoffset*/ 0,
220 /*tp_iter*/ nullptr,
221 /*tp_iternext*/ nullptr,
222 /*tp_methods*/ nullptr,
223 /*tp_members*/ nullptr,
224 /*tp_getset*/ nullptr,
225 /*tp_base*/ nullptr,
226 /*tp_dict*/ nullptr,
227 /*tp_descr_get*/ nullptr,
228 /*tp_descr_set*/ nullptr,
229 /*tp_dictoffset*/ 0,
230 /*tp_init*/ nullptr,
231 /*tp_alloc*/ nullptr,
233 /*tp_free*/ nullptr,
234 /*tp_is_gc*/ nullptr,
235 /*tp_bases*/ nullptr,
236 /*tp_mro*/ nullptr,
237 /*tp_cache*/ nullptr,
238 /*tp_subclasses*/ nullptr,
239 /*tp_weaklist*/ nullptr,
240 /*tp_del*/ nullptr,
241 /*tp_version_tag*/ 0,
242 /*tp_finalize*/ nullptr,
243 /*tp_vectorcall*/ nullptr,
244};
245
247
248static PyObject *py_cb_array[BKE_CB_EVT_TOT] = {nullptr};
249
250static PyObject *make_app_cb_info()
251{
252 PyObject *app_cb_info;
253 int pos;
254
255 app_cb_info = PyStructSequence_New(&BlenderAppCbType);
256 if (app_cb_info == nullptr) {
257 return nullptr;
258 }
259
260 for (pos = 0; pos < BKE_CB_EVT_TOT; pos++) {
261 if (app_cb_info_fields[pos].name == nullptr) {
262 Py_FatalError("invalid callback slots 1");
263 }
264 PyStructSequence_SET_ITEM(app_cb_info, pos, (py_cb_array[pos] = PyList_New(0)));
265 }
266 if (app_cb_info_fields[pos + APP_CB_OTHER_FIELDS].name != nullptr) {
267 Py_FatalError("invalid callback slots 2");
268 }
269
270 /* custom function */
271 PyStructSequence_SET_ITEM(app_cb_info, pos++, (PyObject *)&BPyPersistent_Type);
272
273 return app_cb_info;
274}
275
277{
278 PyObject *ret;
279
280#if defined(_MSC_VER)
281 BPyPersistent_Type.ob_base.ob_base.ob_type = &PyType_Type;
282#endif
283
284 if (PyType_Ready(&BPyPersistent_Type) < 0) {
285 BLI_assert_msg(0, "error initializing 'bpy.app.handlers.persistent'");
286 }
287
288 PyStructSequence_InitType(&BlenderAppCbType, &app_cb_info_desc);
289
291
292 /* prevent user from creating new instances */
293 BlenderAppCbType.tp_init = nullptr;
294 BlenderAppCbType.tp_new = nullptr;
295 /* Without this we can't do `set(sys.modules)` #29635. */
296 BlenderAppCbType.tp_hash = (hashfunc)Py_HashPointer;
297
298 /* assign the C callbacks */
299 if (ret) {
300 static bCallbackFuncStore funcstore_array[BKE_CB_EVT_TOT] = {{nullptr}};
301 bCallbackFuncStore *funcstore;
302 int pos = 0;
303
304 for (pos = 0; pos < BKE_CB_EVT_TOT; pos++) {
305 funcstore = &funcstore_array[pos];
306 funcstore->func = bpy_app_generic_callback;
307 funcstore->alloc = 0;
308 funcstore->arg = POINTER_FROM_INT(pos);
309 BKE_callback_add(funcstore, eCbEvent(pos));
310 }
311 }
312
313 return ret;
314}
315
316void BPY_app_handlers_reset(const bool do_all)
317{
318 PyGILState_STATE gilstate = PyGILState_Ensure();
319 int pos = 0;
320
321 if (do_all) {
322 for (pos = 0; pos < BKE_CB_EVT_TOT; pos++) {
323 /* clear list */
324 PyList_SetSlice(py_cb_array[pos], 0, PY_SSIZE_T_MAX, nullptr);
325 }
326 }
327 else {
328 /* save string conversion thrashing */
329 PyObject *perm_id_str = PyUnicode_FromString(PERMINENT_CB_ID);
330
331 for (pos = 0; pos < BKE_CB_EVT_TOT; pos++) {
332 /* clear only items without PERMINENT_CB_ID */
333 PyObject *ls = py_cb_array[pos];
334 Py_ssize_t i;
335
336 for (i = PyList_GET_SIZE(ls) - 1; i >= 0; i--) {
337 PyObject *item = PyList_GET_ITEM(ls, i);
338
339 if (PyMethod_Check(item)) {
340 PyObject *item_test = PyMethod_GET_FUNCTION(item);
341 if (item_test) {
342 item = item_test;
343 }
344 }
345
346 PyObject **dict_ptr;
347 if (PyFunction_Check(item) && (dict_ptr = _PyObject_GetDictPtr(item)) && (*dict_ptr) &&
348 (PyDict_GetItem(*dict_ptr, perm_id_str) != nullptr))
349 {
350 /* keep */
351 }
352 else {
353 /* remove */
354 // PySequence_DelItem(ls, i); /* more obvious but slower */
355 PyList_SetSlice(ls, i, i + 1, nullptr);
356 }
357 }
358 }
359
360 Py_DECREF(perm_id_str);
361 }
362
363 PyGILState_Release(gilstate);
364}
365
366static PyObject *choose_arguments(PyObject *func, PyObject *args_all, PyObject *args_single)
367{
368 if (!PyFunction_Check(func)) {
369 return args_all;
370 }
371 PyCodeObject *code = (PyCodeObject *)PyFunction_GetCode(func);
372 if (code->co_argcount == 1) {
373 return args_single;
374 }
375 return args_all;
376}
377
378/* the actual callback - not necessarily called from py */
380 PointerRNA **pointers,
381 const int pointers_num,
382 void *arg)
383{
384 PyObject *cb_list = py_cb_array[POINTER_AS_INT(arg)];
385 if (PyList_GET_SIZE(cb_list) > 0) {
386 const PyGILState_STATE gilstate = PyGILState_Ensure();
387
388 const int num_arguments = 2;
389 PyObject *args_all = PyTuple_New(num_arguments); /* save python creating each call */
390 PyObject *args_single = PyTuple_New(1);
391 PyObject *func;
392 PyObject *ret;
393 Py_ssize_t pos;
394
395 /* setup arguments */
396 for (int i = 0; i < pointers_num; ++i) {
397 PyTuple_SET_ITEM(
399 }
400 for (int i = pointers_num; i < num_arguments; ++i) {
401 PyTuple_SET_ITEM(args_all, i, Py_NewRef(Py_None));
402 }
403
404 if (pointers_num == 0) {
405 PyTuple_SET_ITEM(args_single, 0, Py_NewRef(Py_None));
406 }
407 else {
408 PyTuple_SET_ITEM(
409 args_single, 0, pyrna_struct_CreatePyObject_with_primitive_support(pointers[0]));
410 }
411
412 /* Iterate the list and run the callbacks
413 * NOTE: don't store the list size since the scripts may remove themselves. */
414 for (pos = 0; pos < PyList_GET_SIZE(cb_list); pos++) {
415 func = PyList_GET_ITEM(cb_list, pos);
416 PyObject *args = choose_arguments(func, args_all, args_single);
417 ret = PyObject_Call(func, args, nullptr);
418 if (ret == nullptr) {
419 /* Don't set last system variables because they might cause some
420 * dangling pointers to external render engines (when exception
421 * happens during rendering) which will break logic of render pipeline
422 * which expects to be the only user of render engine when rendering
423 * is finished. */
424
425 /* Note the handler called, the exception itself typically has the function name. */
426 PySys_WriteStderr("Error in bpy.app.handlers.%s[%d]:\n",
428 int(pos));
429 PyErr_PrintEx(0);
430 PyErr_Clear();
431 }
432 else {
433 Py_DECREF(ret);
434 }
435 }
436
437 Py_DECREF(args_all);
438 Py_DECREF(args_single);
439
440 PyGILState_Release(gilstate);
441 }
442}
void BKE_callback_add(bCallbackFuncStore *funcstore, eCbEvent evt)
Definition callbacks.cc:74
eCbEvent
@ BKE_CB_EVT_TOT
#define BLI_assert_msg(a, msg)
Definition BLI_assert.h:53
#define ARRAY_SIZE(arr)
#define POINTER_FROM_INT(i)
#define POINTER_AS_INT(i)
PyObject * BPY_app_handlers_struct()
static PyStructSequence_Desc app_cb_info_desc
#define FILEPATH_SAVE_ARG
#define APP_CB_OTHER_FIELDS
static PyTypeObject BPyPersistent_Type
#define RENDER_ARG
#define PERMINENT_CB_ID
#define FILEPATH_LOAD_ARG
#define DEPSGRAPH_UPDATE_ARG
#define COMPOSITE_ARG
#define OBJECT_BAKE_ARG
static PyObject * make_app_cb_info()
void BPY_app_handlers_reset(const bool do_all)
static PyObject * bpy_app_handlers_persistent_new(PyTypeObject *, PyObject *args, PyObject *)
static PyStructSequence_Field app_cb_info_fields[]
static PyObject * py_cb_array[BKE_CB_EVT_TOT]
#define RENDER_STATS_ARG
static PyTypeObject BlenderAppCbType
static PyObject * choose_arguments(PyObject *func, PyObject *args_all, PyObject *args_single)
void bpy_app_generic_callback(Main *main, PointerRNA **pointers, const int pointers_num, void *arg)
PyObject * pyrna_struct_CreatePyObject_with_primitive_support(PointerRNA *ptr)
Definition bpy_rna.cc:8420
uint pos
#define main()
header-only compatibility defines.
#define Py_HashPointer
return ret
void(* func)(Main *, PointerRNA **, int num_pointers, void *arg)
i
Definition text_draw.cc:230