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