Blender V5.0
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 data-block and the dependency graph being updated"
46#define RENDER_ARG \
47 "Accepts one argument: " \
48 "the scene data-block being rendered"
49#define OBJECT_BAKE_ARG \
50 "Accepts one argument: " \
51 "the object data-block being baked"
52#define COMPOSITE_ARG \
53 "Accepts one argument: " \
54 "the scene data-block"
55#define ANNOTATION_ARG \
56 "Accepts two arguments: " \
57 "the annotation data-block 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). " ANNOTATION_ARG},
103 {"annotation_post", "on drawing an annotation (after). " ANNOTATION_ARG},
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", "on linking or appending data (before). " BLENDIMPORT_ARG},
124 {"blend_import_post", "on linking or appending data (after). " BLENDIMPORT_ARG},
125
126/* sets the permanent tag */
127#define APP_CB_OTHER_FIELDS 1
128 {"persistent",
129 "Function decorator for callback functions not to be removed when loading new files"},
130
131 {nullptr},
132};
133
134static PyStructSequence_Desc app_cb_info_desc = {
135 /*name*/ "bpy.app.handlers",
136 /*doc*/ "This module contains callback lists",
137 /*fields*/ app_cb_info_fields,
138 /*n_in_sequence*/ ARRAY_SIZE(app_cb_info_fields) - 1,
139};
140
141#if 0
142# if (BKE_CB_EVT_TOT != ARRAY_SIZE(app_cb_info_fields))
143# error "Callbacks are out of sync"
144# endif
145#endif
146
147/* -------------------------------------------------------------------- */
150
151#define PERMINENT_CB_ID "_bpy_persistent"
152
153static PyObject *bpy_app_handlers_persistent_new(PyTypeObject * /*type*/,
154 PyObject *args,
155 PyObject * /*kwds*/)
156{
157 PyObject *value;
158
159 if (!PyArg_ParseTuple(args, "O:bpy.app.handlers.persistent", &value)) {
160 return nullptr;
161 }
162
163 if (PyFunction_Check(value)) {
164 PyObject **dict_ptr = _PyObject_GetDictPtr(value);
165 if (dict_ptr == nullptr) {
166 PyErr_SetString(PyExc_ValueError,
167 "bpy.app.handlers.persistent wasn't able to "
168 "get the dictionary from the function passed");
169 return nullptr;
170 }
171
172 /* set id */
173 if (*dict_ptr == nullptr) {
174 *dict_ptr = PyDict_New();
175 }
176
177 PyDict_SetItemString(*dict_ptr, PERMINENT_CB_ID, Py_None);
178
179 Py_INCREF(value);
180 return value;
181 }
182
183 PyErr_SetString(PyExc_ValueError, "bpy.app.handlers.persistent expected a function");
184 return nullptr;
185}
186
188static PyTypeObject BPyPersistent_Type = {
189#if defined(_MSC_VER)
190 /*ob_base*/ PyVarObject_HEAD_INIT(nullptr, 0)
191#else
192 /*ob_base*/ PyVarObject_HEAD_INIT(&PyType_Type, 0)
193#endif
194 /*tp_name*/ "persistent",
195 /*tp_basicsize*/ 0,
196 /*tp_itemsize*/ 0,
197 /*tp_dealloc*/ nullptr,
198 /*tp_vectorcall_offset*/ 0,
199 /*tp_getattr*/ nullptr,
200 /*tp_setattr*/ nullptr,
201 /*tp_as_async*/ nullptr,
202 /*tp_repr*/ nullptr,
203 /*tp_as_number*/ nullptr,
204 /*tp_as_sequence*/ nullptr,
205 /*tp_as_mapping*/ nullptr,
206 /*tp_hash*/ nullptr,
207 /*tp_call*/ nullptr,
208 /*tp_str*/ nullptr,
209 /*tp_getattro*/ nullptr,
210 /*tp_setattro*/ nullptr,
211 /*tp_as_buffer*/ nullptr,
212 /*tp_flags*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
213 /*tp_doc*/ nullptr,
214 /*tp_traverse*/ nullptr,
215 /*tp_clear*/ nullptr,
216 /*tp_richcompare*/ nullptr,
217 /*tp_weaklistoffset*/ 0,
218 /*tp_iter*/ nullptr,
219 /*tp_iternext*/ nullptr,
220 /*tp_methods*/ nullptr,
221 /*tp_members*/ nullptr,
222 /*tp_getset*/ nullptr,
223 /*tp_base*/ nullptr,
224 /*tp_dict*/ nullptr,
225 /*tp_descr_get*/ nullptr,
226 /*tp_descr_set*/ nullptr,
227 /*tp_dictoffset*/ 0,
228 /*tp_init*/ nullptr,
229 /*tp_alloc*/ nullptr,
231 /*tp_free*/ nullptr,
232 /*tp_is_gc*/ nullptr,
233 /*tp_bases*/ nullptr,
234 /*tp_mro*/ nullptr,
235 /*tp_cache*/ nullptr,
236 /*tp_subclasses*/ nullptr,
237 /*tp_weaklist*/ nullptr,
238 /*tp_del*/ nullptr,
239 /*tp_version_tag*/ 0,
240 /*tp_finalize*/ nullptr,
241 /*tp_vectorcall*/ nullptr,
242};
243
245
246static PyObject *py_cb_array[BKE_CB_EVT_TOT] = {nullptr};
247
248static PyObject *make_app_cb_info()
249{
250 PyObject *app_cb_info;
251 int pos;
252
253 app_cb_info = PyStructSequence_New(&BlenderAppCbType);
254 if (app_cb_info == nullptr) {
255 return nullptr;
256 }
257
258 for (pos = 0; pos < BKE_CB_EVT_TOT; pos++) {
259 if (app_cb_info_fields[pos].name == nullptr) {
260 Py_FatalError("invalid callback slots 1");
261 }
262 PyStructSequence_SET_ITEM(app_cb_info, pos, (py_cb_array[pos] = PyList_New(0)));
263 }
265 Py_FatalError("invalid callback slots 2");
266 }
267
268 /* custom function */
269 PyStructSequence_SET_ITEM(app_cb_info, pos++, (PyObject *)&BPyPersistent_Type);
270
271 return app_cb_info;
272}
273
275{
276 PyObject *ret;
277
278#if defined(_MSC_VER)
279 BPyPersistent_Type.ob_base.ob_base.ob_type = &PyType_Type;
280#endif
281
282 if (PyType_Ready(&BPyPersistent_Type) < 0) {
283 BLI_assert_msg(0, "error initializing 'bpy.app.handlers.persistent'");
284 }
285
286 PyStructSequence_InitType(&BlenderAppCbType, &app_cb_info_desc);
287
289
290 /* prevent user from creating new instances */
291 BlenderAppCbType.tp_init = nullptr;
292 BlenderAppCbType.tp_new = nullptr;
293 /* Without this we can't do `set(sys.modules)` #29635. */
294 BlenderAppCbType.tp_hash = (hashfunc)Py_HashPointer;
295
296 /* assign the C callbacks */
297 if (ret) {
298 static bCallbackFuncStore funcstore_array[BKE_CB_EVT_TOT] = {{nullptr}};
299 bCallbackFuncStore *funcstore;
300 int pos = 0;
301
302 for (pos = 0; pos < BKE_CB_EVT_TOT; pos++) {
303 funcstore = &funcstore_array[pos];
304 funcstore->func = bpy_app_generic_callback;
305 funcstore->alloc = 0;
306 funcstore->arg = POINTER_FROM_INT(pos);
307 BKE_callback_add(funcstore, eCbEvent(pos));
308 }
309 }
310
311 return ret;
312}
313
314void BPY_app_handlers_reset(const bool do_all)
315{
316 PyGILState_STATE gilstate = PyGILState_Ensure();
317 int pos = 0;
318
319 if (do_all) {
320 for (pos = 0; pos < BKE_CB_EVT_TOT; pos++) {
321 /* clear list */
322 PyList_SetSlice(py_cb_array[pos], 0, PY_SSIZE_T_MAX, nullptr);
323 }
324 }
325 else {
326 /* save string conversion thrashing */
327 PyObject *perm_id_str = PyUnicode_FromString(PERMINENT_CB_ID);
328
329 for (pos = 0; pos < BKE_CB_EVT_TOT; pos++) {
330 /* clear only items without PERMINENT_CB_ID */
331 PyObject *ls = py_cb_array[pos];
332 Py_ssize_t i;
333
334 for (i = PyList_GET_SIZE(ls) - 1; i >= 0; i--) {
335 PyObject *item = PyList_GET_ITEM(ls, i);
336
337 if (PyMethod_Check(item)) {
338 PyObject *item_test = PyMethod_GET_FUNCTION(item);
339 if (item_test) {
340 item = item_test;
341 }
342 }
343
344 PyObject **dict_ptr;
345 if (PyFunction_Check(item) && (dict_ptr = _PyObject_GetDictPtr(item)) && (*dict_ptr) &&
346 (PyDict_GetItem(*dict_ptr, perm_id_str) != nullptr))
347 {
348 /* keep */
349 }
350 else {
351 /* remove */
352 // PySequence_DelItem(ls, i); /* more obvious but slower */
353 PyList_SetSlice(ls, i, i + 1, nullptr);
354 }
355 }
356 }
357
358 Py_DECREF(perm_id_str);
359 }
360
361 PyGILState_Release(gilstate);
362}
363
364static PyObject *choose_arguments(PyObject *func, PyObject *args_all, PyObject *args_single)
365{
366 if (!PyFunction_Check(func)) {
367 return args_all;
368 }
369 PyCodeObject *code = (PyCodeObject *)PyFunction_GetCode(func);
370 if (code->co_argcount == 1) {
371 return args_single;
372 }
373 return args_all;
374}
375
376/* the actual callback - not necessarily called from py */
378 PointerRNA **pointers,
379 const int pointers_num,
380 void *arg)
381{
382 PyObject *cb_list = py_cb_array[POINTER_AS_INT(arg)];
383 if (PyList_GET_SIZE(cb_list) > 0) {
384 const PyGILState_STATE gilstate = PyGILState_Ensure();
385
386 const int num_arguments = 2;
387 PyObject *args_all = PyTuple_New(num_arguments); /* save python creating each call */
388 PyObject *args_single = PyTuple_New(1);
389 PyObject *func;
390 PyObject *ret;
391 Py_ssize_t pos;
392
393 /* setup arguments */
394 for (int i = 0; i < pointers_num; ++i) {
395 PyTuple_SET_ITEM(
397 }
398 for (int i = pointers_num; i < num_arguments; ++i) {
399 PyTuple_SET_ITEM(args_all, i, Py_NewRef(Py_None));
400 }
401
402 if (pointers_num == 0) {
403 PyTuple_SET_ITEM(args_single, 0, Py_NewRef(Py_None));
404 }
405 else {
406 PyTuple_SET_ITEM(
407 args_single, 0, pyrna_struct_CreatePyObject_with_primitive_support(pointers[0]));
408 }
409
410 /* Iterate the list and run the callbacks
411 * NOTE: don't store the list size since the scripts may remove themselves. */
412 for (pos = 0; pos < PyList_GET_SIZE(cb_list); pos++) {
413 func = PyList_GET_ITEM(cb_list, pos);
414 PyObject *args = choose_arguments(func, args_all, args_single);
415 ret = PyObject_Call(func, args, nullptr);
416 if (ret == nullptr) {
417 /* Don't set last system variables because they might cause some
418 * dangling pointers to external render engines (when exception
419 * happens during rendering) which will break logic of render pipeline
420 * which expects to be the only user of render engine when rendering
421 * is finished. */
422
423 /* Note the handler called, the exception itself typically has the function name. */
424 PySys_WriteStderr("Error in bpy.app.handlers.%s[%d]:\n",
426 int(pos));
427 PyErr_PrintEx(0);
428 }
429 else {
430 Py_DECREF(ret);
431 }
432 }
433
434 Py_DECREF(args_all);
435 Py_DECREF(args_single);
436
437 PyGILState_Release(gilstate);
438 }
439}
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)
#define ANNOTATION_ARG
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)
#define BLENDIMPORT_ARG
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:8532
uint pos
#define main()
header-only compatibility defines.
#define Py_HashPointer
Py_DECREF(oname)
const char * name
return ret
void(* func)(Main *, PointerRNA **, int num_pointers, void *arg)
i
Definition text_draw.cc:230