Blender V5.3
bpy_msgbus.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
9
10#include <Python.h>
11
14#include "../generic/python_compat.hh" /* IWYU pragma: keep. */
16
18
19#include "BKE_context.hh"
20
21#include "WM_message.hh"
22
23#include "RNA_access.hh"
24
25#include "bpy_capi_utils.hh"
26#include "bpy_rna.hh"
27
28#include "bpy_msgbus.hh" /* own include */
29
30namespace blender {
31
32/* -------------------------------------------------------------------- */
35
36#define BPY_MSGBUS_RNA_MSGKEY_DOC \
37 " :param key: Represents the type of data being subscribed to\n" \
38 "\n" \
39 " Arguments include\n" \
40 " - A property instance.\n" \
41 " - A struct type.\n" \
42 " - A tuple representing a (struct, property name) pair.\n" \
43 " :type key: :class:`bpy.types.Property` | " \
44 ":class:`bpy.types.Struct` | " \
45 "tuple[:class:`bpy.types.Struct`, str]\n"
46
57static int py_msgbus_rna_key_from_py(PyObject *py_sub,
58 wmMsgParams_RNA *msg_key_params,
59 const char *error_prefix)
60{
61
62 /* Allow common case, object rotation, location - etc. */
63 if (BaseMathObject_CheckExact(py_sub)) {
64 BaseMathObject *py_sub_math = reinterpret_cast<BaseMathObject *>(py_sub);
65 if (py_sub_math->cb_user == nullptr) {
66 PyErr_Format(PyExc_TypeError, "%s: math argument has no owner", error_prefix);
67 return -1;
68 }
69 py_sub = py_sub_math->cb_user;
70 /* Common case will use BPy_PropertyRNA_Check below. */
71 }
72
73 if (BPy_PropertyRNA_Check(py_sub)) {
74 BPy_PropertyRNA *data_prop = reinterpret_cast<BPy_PropertyRNA *>(py_sub);
75 PYRNA_PROP_CHECK_INT(data_prop);
76 msg_key_params->ptr = *data_prop->ptr;
77 msg_key_params->prop = data_prop->prop;
78 }
79 else if (BPy_StructRNA_Check(py_sub)) {
80 /* NOTE: this isn't typically used since we don't edit structs directly. */
81 BPy_StructRNA *data_srna = reinterpret_cast<BPy_StructRNA *>(py_sub);
82 PYRNA_STRUCT_CHECK_INT(data_srna);
83 msg_key_params->ptr = *data_srna->ptr;
84 }
85 /* TODO: property / type, not instance. */
86 else if (PyType_Check(py_sub)) {
87 StructRNA *data_type = pyrna_struct_as_srna(py_sub, false, error_prefix);
88 if (data_type == nullptr) {
89 return -1;
90 }
91 msg_key_params->ptr.type = data_type;
92 }
93 else if (PyTuple_CheckExact(py_sub)) {
94 if (PyTuple_GET_SIZE(py_sub) == 2) {
95 PyObject *data_type_py = PyTuple_GET_ITEM(py_sub, 0);
96 PyObject *data_prop_py = PyTuple_GET_ITEM(py_sub, 1);
97 StructRNA *data_type = pyrna_struct_as_srna(data_type_py, false, error_prefix);
98 if (data_type == nullptr) {
99 return -1;
100 }
101 if (!PyUnicode_CheckExact(data_prop_py)) {
102 PyErr_Format(PyExc_TypeError, "%s: expected property to be a string", error_prefix);
103 return -1;
104 }
105 PointerRNA data_type_ptr{};
106 data_type_ptr.type = data_type;
107
108 const char *data_prop_str = PyUnicode_AsUTF8(data_prop_py);
109 PropertyRNA *data_prop = RNA_struct_find_property(&data_type_ptr, data_prop_str);
110
111 if (data_prop == nullptr) {
112 PyErr_Format(PyExc_TypeError,
113 "%s: struct %.200s does not contain property %.200s",
114 error_prefix,
115 RNA_struct_identifier(data_type),
116 data_prop_str);
117 return -1;
118 }
119
120 msg_key_params->ptr.type = data_type;
121 msg_key_params->prop = data_prop;
122 }
123 else {
124 PyErr_Format(PyExc_ValueError, "%s: Expected a pair (type, property_id)", error_prefix);
125 return -1;
126 }
127 }
128 return 0;
129}
130
132
133/* -------------------------------------------------------------------- */
136
137#define BPY_MSGBUS_USER_DATA_LEN 2
138
139/* Follow wmMsgNotifyFn spec */
141 wmMsgSubscribeKey * /*msg_key*/,
142 wmMsgSubscribeValue *msg_val)
143{
144 PyGILState_STATE gilstate;
145 bpy_context_set(C, &gilstate);
146 const bool is_write_ok = pyrna_write_check();
147 if (!is_write_ok) {
148 pyrna_write_set(true);
149 }
150
151 PyObject *user_data = static_cast<PyObject *>(msg_val->user_data);
152 BLI_assert(PyTuple_GET_SIZE(user_data) == BPY_MSGBUS_USER_DATA_LEN);
153
154 PyObject *callback_args = PyTuple_GET_ITEM(user_data, 0);
155 PyObject *callback_notify = PyTuple_GET_ITEM(user_data, 1);
156
157 PyObject *ret = PyObject_CallObject(callback_notify, callback_args);
158
159 if (ret == nullptr) {
160 PyC_Err_PrintWithFunc(callback_notify);
161 }
162 else {
163 if (ret != Py_None) {
164 PyErr_SetString(PyExc_ValueError, "the return value must be None");
165 PyC_Err_PrintWithFunc(callback_notify);
166 }
167 Py_DECREF(ret);
168 }
169
170 if (!is_write_ok) {
171 pyrna_write_set(false);
172 }
173 bpy_context_clear(C, &gilstate);
174}
175
176/* Follow wmMsgSubscribeValueFreeDataFn spec */
178 wmMsgSubscribeValue *msg_val)
179{
180 const PyGILState_STATE gilstate = PyGILState_Ensure();
181 Py_DECREF(msg_val->owner);
182 Py_DECREF(msg_val->user_data);
183 PyGILState_Release(gilstate);
184}
185
187
188/* -------------------------------------------------------------------- */
191
193 /* Wrap. */
194 bpy_msgbus_subscribe_rna_doc,
195 ".. function:: subscribe_rna(*, key, owner, args, notify, options=set())\n"
196 "\n"
197 " Register a message bus subscription. It will be cleared when another blend file is\n"
198 " loaded, or can be cleared explicitly via :func:`bpy.msgbus.clear_by_owner`.\n"
200 " :param owner: Handle for this subscription (compared by identity).\n"
201 " :type owner: Any\n"
202 " :param args: Arguments passed to the callback.\n"
203 " :type args: tuple\n"
204 " :param notify: The callback function.\n"
205 " :type notify: Callable[..., None]\n"
206 " :param options: Change the behavior of the subscriber.\n"
207 "\n"
208 " - ``PERSISTENT`` when set, the subscriber will be kept when remapping ID data.\n"
209 "\n"
210 " :type options: set[Literal['PERSISTENT']]\n"
211 "\n"
212 ".. note::\n"
213 "\n"
214 " All subscribers will be cleared on file-load. Subscribers can be re-registered on load,\n"
215 " see :mod:`bpy.app.handlers.load_post`.\n");
216static PyObject *bpy_msgbus_subscribe_rna(PyObject * /*self*/, PyObject *args, PyObject *kw)
217{
218 const char *error_prefix = "subscribe_rna";
219 PyObject *py_sub = nullptr;
220 PyObject *py_owner = nullptr;
221 PyObject *callback_args = nullptr;
222 PyObject *callback_notify = nullptr;
223
224 enum {
225 IS_PERSISTENT = (1 << 0),
226 };
227 PyObject *py_options = nullptr;
228 const EnumPropertyItem py_options_enum[] = {
229 {IS_PERSISTENT, "PERSISTENT", 0, ""},
230 {0, nullptr, 0, nullptr, nullptr},
231 };
232 int options = 0;
233
234 if (PyTuple_GET_SIZE(args) != 0) {
235 PyErr_Format(PyExc_TypeError, "%s: only keyword arguments are supported", error_prefix);
236 return nullptr;
237 }
238 static const char *_keywords[] = {
239 "key",
240 "owner",
241 "args",
242 "notify",
243 "options",
244 nullptr,
245 };
246 static _PyArg_Parser _parser = {
247 "O" /* `key` */
248 "O" /* `owner` */
249 "O!" /* `args` */
250 "O" /* `notify` */
251 "|$" /* Optional, keyword only arguments. */
252 "O!" /* `options` */
253 ":subscribe_rna",
254 _keywords,
255 nullptr,
256 };
257 if (!_PyArg_ParseTupleAndKeywordsFast(args,
258 kw,
259 &_parser,
260 &py_sub,
261 &py_owner,
262 &PyTuple_Type,
263 &callback_args,
264 &callback_notify,
265 &PySet_Type,
266 &py_options))
267 {
268 return nullptr;
269 }
270
271 if (py_options &&
272 (pyrna_enum_bitfield_from_set(py_options_enum, py_options, &options, error_prefix) == -1))
273 {
274 return nullptr;
275 }
276
277 /* NOTE: we may want to have a way to pass this in. */
280 wmMsgParams_RNA msg_key_params = {{}};
281
282 wmMsgSubscribeValue msg_val_params = {nullptr};
283
284 if (py_msgbus_rna_key_from_py(py_sub, &msg_key_params, error_prefix) == -1) {
285 return nullptr;
286 }
287
288 if (!PyFunction_Check(callback_notify)) {
289 PyErr_Format(PyExc_TypeError,
290 "notify expects a function, found %.200s",
291 Py_TYPE(callback_notify)->tp_name);
292 return nullptr;
293 }
294
295 if (options != 0) {
296 if (options & IS_PERSISTENT) {
297 msg_val_params.is_persistent = true;
298 }
299 }
300
301 /* owner can be anything. */
302 {
303 msg_val_params.owner = py_owner;
304 Py_INCREF(py_owner);
305 }
306
307 {
308 PyObject *user_data = PyTuple_New(2);
309 PyTuple_SET_ITEMS(user_data, Py_NewRef(callback_args), Py_NewRef(callback_notify));
310 msg_val_params.user_data = user_data;
311 }
312
313 msg_val_params.notify = bpy_msgbus_notify;
315
316 WM_msg_subscribe_rna_params(mbus, &msg_key_params, &msg_val_params, __func__);
317
318 if (false) { /* For debugging. */
319 WM_msg_dump(mbus, __func__);
320 }
321
322 Py_RETURN_NONE;
323}
324
326 /* Wrap. */
327 bpy_msgbus_publish_rna_doc,
328 ".. function:: publish_rna(*, key)\n"
330 "\n"
331 " Notify subscribers of changes to this property\n"
332 " (this typically doesn't need to be called explicitly since changes will automatically "
333 "publish updates).\n"
334 " In some cases it may be useful to publish changes explicitly using more general keys.\n");
335static PyObject *bpy_msgbus_publish_rna(PyObject * /*self*/, PyObject *args, PyObject *kw)
336{
337 const char *error_prefix = "publish_rna";
338 PyObject *py_sub = nullptr;
339
340 if (PyTuple_GET_SIZE(args) != 0) {
341 PyErr_Format(PyExc_TypeError, "%s: only keyword arguments are supported", error_prefix);
342 return nullptr;
343 }
344 static const char *_keywords[] = {
345 "key",
346 nullptr,
347 };
348 static _PyArg_Parser _parser = {
349 "O" /* `key` */
350 ":publish_rna",
351 _keywords,
352 nullptr,
353 };
354 if (!_PyArg_ParseTupleAndKeywordsFast(args, kw, &_parser, &py_sub)) {
355 return nullptr;
356 }
357
358 /* NOTE: we may want to have a way to pass this in. */
361 wmMsgParams_RNA msg_key_params = {{}};
362
363 if (py_msgbus_rna_key_from_py(py_sub, &msg_key_params, error_prefix) == -1) {
364 return nullptr;
365 }
366
367 WM_msg_publish_rna_params(mbus, &msg_key_params);
368
369 Py_RETURN_NONE;
370}
371
373 /* Wrap. */
374 bpy_msgbus_clear_by_owner_doc,
375 ".. function:: clear_by_owner(owner)\n"
376 "\n"
377 " Clear all subscribers using this owner.\n"
378 "\n"
379 " :param owner: The owner handle passed to :func:`subscribe_rna`.\n"
380 " :type owner: Any\n");
381static PyObject *bpy_msgbus_clear_by_owner(PyObject * /*self*/, PyObject *py_owner)
382{
385 WM_msgbus_clear_by_owner(mbus, py_owner);
386 Py_RETURN_NONE;
387}
388
389#ifdef __GNUC__
390# ifdef __clang__
391# pragma clang diagnostic push
392# pragma clang diagnostic ignored "-Wcast-function-type"
393# else
394# pragma GCC diagnostic push
395# pragma GCC diagnostic ignored "-Wcast-function-type"
396# endif
397#endif
398
399static PyMethodDef BPy_msgbus_methods[] = {
400 {"subscribe_rna",
401 reinterpret_cast<PyCFunction>(bpy_msgbus_subscribe_rna),
402 METH_VARARGS | METH_KEYWORDS,
403 bpy_msgbus_subscribe_rna_doc},
404 {"publish_rna",
405 reinterpret_cast<PyCFunction>(bpy_msgbus_publish_rna),
406 METH_VARARGS | METH_KEYWORDS,
407 bpy_msgbus_publish_rna_doc},
408 {"clear_by_owner",
409 static_cast<PyCFunction>(bpy_msgbus_clear_by_owner),
410 METH_O,
411 bpy_msgbus_clear_by_owner_doc},
412 {nullptr, nullptr, 0, nullptr},
413};
414
415#ifdef __GNUC__
416# ifdef __clang__
417# pragma clang diagnostic pop
418# else
419# pragma GCC diagnostic pop
420# endif
421#endif
422
423static PyModuleDef _bpy_msgbus_def = {
424 /*m_base*/ PyModuleDef_HEAD_INIT,
425 /*m_name*/ "msgbus",
426 /*m_doc*/ nullptr,
427 /*m_size*/ 0,
428 /*m_methods*/ BPy_msgbus_methods,
429 /*m_slots*/ nullptr,
430 /*m_traverse*/ nullptr,
431 /*m_clear*/ nullptr,
432 /*m_free*/ nullptr,
433};
434
436{
437 PyObject *submodule;
438
439 submodule = PyModule_Create(&_bpy_msgbus_def);
440
441 return submodule;
442}
443
445
446} // namespace blender
#define C
Definition RandGen.cpp:29
#define BPY_MSGBUS_USER_DATA_LEN
#define BPY_MSGBUS_RNA_MSGKEY_DOC
Definition bpy_msgbus.cc:36
#define PYRNA_STRUCT_CHECK_INT(obj)
Definition bpy_rna.hh:86
#define PYRNA_PROP_CHECK_INT(obj)
Definition bpy_rna.hh:97
#define BPy_StructRNA_Check(v)
Definition bpy_rna.hh:76
#define BPy_PropertyRNA_Check(v)
Definition bpy_rna.hh:78
CCL_NAMESPACE_BEGIN struct Options options
#define BaseMathObject_CheckExact(v)
Definition mathutils.hh:85
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
static PyObject * bpy_msgbus_clear_by_owner(PyObject *, PyObject *py_owner)
PropertyRNA * RNA_struct_find_property(PointerRNA *ptr, const char *identifier)
int pyrna_enum_bitfield_from_set(const EnumPropertyItem *items, PyObject *value, int *r_value, const char *error_prefix)
void WM_msg_dump(wmMsgBus *mbus, const char *info_str)
PyDoc_STRVAR(bpy_bm_new_doc, ".. function:: new(*, use_operators=True)\n" "\n" " :param use_operators: Support calling operators in :mod:`bmesh.ops` (uses some " "extra memory per vert/edge/face).\n" " :type use_operators: bool\n" " :return: Return a new, empty BMesh.\n" " :rtype: :class:`bmesh.types.BMesh`\n")
static PyModuleDef _bpy_msgbus_def
static PyMethodDef BPy_msgbus_methods[]
void WM_msg_subscribe_rna_params(wmMsgBus *mbus, const wmMsgParams_RNA *msg_key_params, const wmMsgSubscribeValue *msg_val_params, const char *id_repr)
static void bpy_msgbus_notify(bContext *C, wmMsgSubscribeKey *, wmMsgSubscribeValue *msg_val)
static PyObject * bpy_msgbus_publish_rna(PyObject *, PyObject *args, PyObject *kw)
struct bContext * BPY_context_get()
PyObject * BPY_msgbus_module()
static int py_msgbus_rna_key_from_py(PyObject *py_sub, wmMsgParams_RNA *msg_key_params, const char *error_prefix)
Definition bpy_msgbus.cc:57
void WM_msgbus_clear_by_owner(wmMsgBus *mbus, void *owner)
wmMsgBus * CTX_wm_message_bus(const bContext *C)
void PyC_Err_PrintWithFunc(PyObject *py_func)
const char * RNA_struct_identifier(const StructRNA *type)
void pyrna_write_set(bool val)
Definition bpy_rna.cc:522
StructRNA * pyrna_struct_as_srna(PyObject *self, const bool parent, const char *error_prefix)
Definition bpy_rna.cc:9338
bool bpy_context_set(struct bContext *C, PyGILState_STATE *gilstate) ATTR_NONNULL(1)
bool pyrna_write_check()
Definition bpy_rna.cc:515
static PyObject * bpy_msgbus_subscribe_rna(PyObject *, PyObject *args, PyObject *kw)
void bpy_context_clear(struct bContext *C, const PyGILState_STATE *gilstate)
static void bpy_msgbus_subscribe_value_free_data(wmMsgSubscribeKey *, wmMsgSubscribeValue *msg_val)
void WM_msg_publish_rna_params(wmMsgBus *mbus, const wmMsgParams_RNA *msg_key_params)
header-only compatibility defines.
header-only utilities
#define PyTuple_SET_ITEMS(op_arg,...)
PyObject_HEAD std::optional< PointerRNA > ptr
Definition bpy_rna.hh:153
PyObject_HEAD std::optional< PointerRNA > ptr
Definition bpy_rna.hh:133
StructRNA * type
Definition RNA_types.hh:63
const PropertyRNA * prop
wmMsgSubscribeValueFreeDataFn free_data